- Added extract_barcodes_from_pdf function to read barcodes from PDF files using fitz. - Updated read_datamatrix_zxing to return both the barcode text and its Base64 representation. - Modified main execution block to include PDF barcode extraction. - Improved image loading for better compatibility with zxing. - Updated requirements.txt to include pymupdf for PDF processing.
73 lines
2.8 KiB
Python
73 lines
2.8 KiB
Python
import zxingcpp as zxing_cpp
|
||
from PIL import Image
|
||
import base64
|
||
import fitz
|
||
|
||
|
||
def extract_barcodes_from_pdf(pdf_path: str):
|
||
results = []
|
||
|
||
doc = fitz.open(pdf_path)
|
||
|
||
for page_num in range(len(doc)):
|
||
page = doc[page_num]
|
||
|
||
matrix = fitz.Matrix(2.0, 2.0)
|
||
pix = page.get_pixmap(matrix=matrix)
|
||
|
||
img = Image.frombytes(mode="RGB", size=(pix.width, pix.height), data=pix.samples)
|
||
|
||
barcodes = zxing_cpp.read_barcodes(img)
|
||
|
||
for barcode in barcodes:
|
||
b64_string = base64.b64encode(barcode.bytes).decode('ascii')
|
||
results.append({
|
||
"page": page_num + 1,
|
||
"text": barcode.text,
|
||
"base64": b64_string,
|
||
"format": barcode.format.name
|
||
})
|
||
|
||
doc.close()
|
||
return results
|
||
|
||
def read_datamatrix_zxing(file_path: str) -> tuple[str, str]:
|
||
# Открываем изображение через Pillow
|
||
with Image.open(file_path) as img:
|
||
img.load(scale=10)
|
||
# Для EPS файлов (и других специфичных форматов) Pillow загружает данные "лениво".
|
||
# Чтобы избежать ошибки "does not support the buffer protocol" в zxing,
|
||
# нам нужно принудительно загрузить данные и конвертировать их в понятный цветовой режим,
|
||
# например, в 'L' (оттенки серого) или 'RGB', который zxing гарантированно поддерживает.
|
||
img = img.convert("RGB")
|
||
|
||
# Читаем штрих-код.
|
||
# zxing_cpp.read_barcodes умеет работать напрямую с объектами PIL
|
||
results = zxing_cpp.read_barcodes(img)
|
||
|
||
if not results:
|
||
print("Коды не найдены на изображении.")
|
||
return ('','')
|
||
|
||
# Берем первый найденный код
|
||
result = results[0]
|
||
|
||
# Извлекаем именно байты (важно для непечатаемых символов GS/FNC1)
|
||
raw_bytes = result.bytes
|
||
|
||
# Кодируем байты в Base64
|
||
# b64encode возвращает bytes, поэтому делаем .decode('ascii') для получения строки
|
||
b64_string = base64.b64encode(raw_bytes).decode('ascii')
|
||
|
||
return (result.text, b64_string)
|
||
|
||
if __name__ == "__main__":
|
||
image_path = "data/output.png"
|
||
text, data = read_datamatrix_zxing(image_path)
|
||
pdf_read_path = 'data/output_pdfs/Labels_04639970975115.pdf'
|
||
results = extract_barcodes_from_pdf(pdf_read_path)
|
||
|
||
if data:
|
||
print(f"Успешно прочитано: {data}")
|
||
else:
|
||
print("Код не распознан") |