Spaces:
Running
Running
File size: 5,759 Bytes
36ccd32 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
"""Barcode detector and reader models"""
# pylint: disable=E1101
import logging
from typing import Any, Tuple
from dataclasses import dataclass, field
from pathlib import Path
import numpy as np
import cv2
from pyzbar.pyzbar import decode
from qreader import QReader
from .base import BarcodeBase, ReaderResults
logger = logging.getLogger(__name__)
@dataclass
class BarcodeOpencv(BarcodeBase):
"""This a simple 1D barcode reader using OpenCV. It can be used with
EAN-8, EAN-13, UPC-A and UPC-E types of barcodes"""
proto_file: Path = field(
init=False, default=Path("./src/deep_barcode_reader/models/sr.prototxt")
)
model_file: Path = field(
init=False, default=Path("./src/deep_barcode_reader/models/sr.caffemodel")
)
def __post_init__(self) -> None:
"""Post initialization of the barcode reader class"""
if not self.model_file.exists():
logger.error(
"The model file does not exist for the BarcodeOpencv model. Please check the path."
)
if not self.proto_file.exists():
logger.error(
"The proto file does not exist for the BarcodeOpencv model. Please check the path."
)
async def detect_decode(self, image: Any) -> ReaderResults:
"""Detect and decode barcode method from an image"""
result = ReaderResults(image=image)
barcode_reader = cv2.barcode.BarcodeDetector(
str(self.proto_file), str(self.model_file)
)
retval, decoded_info, barcode_types, boundary_boxs = (
barcode_reader.detectAndDecodeWithType(image)
)
if retval:
for idx, barc_txt in enumerate(decoded_info):
if barc_txt:
result.decoded_data.append(barc_txt)
result.bbox_data.append(
np.array(boundary_boxs[idx], dtype=np.int32)
)
result.decoded_types.append(barcode_types[idx])
if result.decoded_data:
logger.info(
"The barcode/qr code is detected and decoded successfully with BarcodeOpencv method."
)
else:
logger.warning(
"The barcode/qr code is not detected or decoded with BarcodeOpencv method."
)
return result
@dataclass
class BarcodeQRZbar(BarcodeBase):
"""This is a QR code and barcode reader using Zbar library"""
async def detect_decode(self, image: Any) -> ReaderResults:
"""Detect and decode barcode/qr method from an image"""
result = ReaderResults(image=image)
decoder = decode(image)
decoded_data = []
decoded_types = []
bbox_data = []
if decoder:
for decoded in decoder:
if decoded.data.decode("utf-8"):
decoded_data.append(decoded.data.decode("utf-8"))
decoded_types.append(decoded.type)
bbox_data.append(np.array(decoded.polygon, np.int64))
result.decoded_data = decoded_data
result.decoded_types = decoded_types
result.bbox_data = bbox_data
if result.decoded_data:
logger.info(
"The barcode/qr code is detected and decoded successfully with BarcodeQRZbar method."
)
else:
logger.warning(
"The barcode/qr code is not detected or decoded with BarcodeQRZbar method."
)
return result
@dataclass
class QRreader(BarcodeBase):
"""This is a QR code reader using Qreader library"""
model_size: str = field(default="l")
async def detect_decode(self, image: Any) -> ReaderResults:
"""Detect and decode barcode/qr method from an image"""
result = ReaderResults(image=image)
qr_reader = QReader(model_size=self.model_size)
detections = qr_reader.detect(image=image)
decoded_data = []
decoded_types = []
bbox_data = []
if detections:
for detection in detections:
decoded_text = qr_reader.decode(image, detection)
if decoded_text:
decoded_data.append(decoded_text)
decoded_types.append("QR")
bbox_data.append(np.array(detection["polygon_xy"], np.int64))
if decoded_data:
result.decoded_data = decoded_data
result.decoded_types = decoded_types
result.bbox_data = bbox_data
logger.info(
"The barcode/qr code is detected and decoded successfully with QRreader method."
)
else:
logger.warning(
"The barcode/qr code is not detected or decoded with QRreader method."
)
else:
logger.warning("The barcode/qr code is not detected with QRreader method.")
return result
@dataclass
class Wrapper:
"""Wrapper class for barcode readers"""
method: str = field(default="opencv")
model_size: str = field(default="l")
async def method_selection(self, image: Any, result_path: str) -> Tuple[Any, Any]:
"""Wrap the method selection for barcode reader"""
if self.method == "opencv":
barcode: Any = BarcodeOpencv()
elif self.method == "zbar":
barcode = BarcodeQRZbar()
elif self.method == "qrreader":
barcode = QRreader(model_size=self.model_size)
else:
barcode = BarcodeOpencv()
detections = await barcode.detect_decode(image)
result_image = await detections.visualize_results_async(result_path)
return detections, result_image
|