Files
label-extractor/read_image.py
gkonoplya 3f8e6935a8 Refactor barcode extraction and enhance PDF processing capabilities
- 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.
2026-02-21 12:42:17 +03:00

73 lines
2.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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("Код не распознан")