[英]Read blurry barcode in python with pyzbar
我一直在嘗試使用 Python 和 pyzbar 從圖像中讀取一些條形碼。 不幸的是,這些圖像是在幾個限制條件下從幾英尺外拍攝的,我無法將相機移動或變焦得更近。 是否可以使用任何現有的 Python 庫來讀取這種模糊的條形碼?
到目前為止,我已經嘗試了一些預處理,包括閾值、銳化、應用垂直關閉過濾器和維納過濾,但似乎沒有任何幫助。 我可能是在祈求奇跡,但如果您有任何建議,我將不勝感激。
代碼(注釋部分是我嘗試過但沒有成功的預處理方法):
import numpy as np
import cv2 as cv
from pyzbar import pyzbar
barcode_img = cv.imread('barcode_example.jpg', cv.IMREAD_GRAYSCALE)
# threshold
# (_, barcode_img) = cv.threshold(barcode_img, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
# close
# barcode_img = cv.morphologyEx(barcode_img, cv.MORPH_CLOSE,
# cv.getStructuringElement(cv.MORPH_RECT, (1, 21)))
# sharpen
# barcode_img_blur = cv.GaussianBlur(barcode_img, (15, 1), 3)
# barcode_img = cv.addWeighted(barcode_img, 1.5, barcode_img_blur, -0.5, 0)
# wiener filter
# from skimage import img_as_float
# from skimage.restoration import wiener, unsupervised_wiener
# dim = 3
# psf = np.ones((dim, dim)) / dim ** 2
# barcode_img = wiener(barcode_img, psf, 1.0, clip=False)
barcodes = pyzbar.decode(barcode_img)
print(barcodes)
#========================
# Import Libraies
#========================
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
from pyzbar import pyzbar
#------------------------
# Read Image
#========================
img = cv.imread('barcode_example.jpg', cv.IMREAD_GRAYSCALE)
# #------------------------
# # Morphology
# #========================
# # Closing
# #------------------------
closed = cv.morphologyEx(img, cv.MORPH_CLOSE, cv.getStructuringElement(cv.MORPH_RECT, (1, 21)))
# #------------------------
# # Statistics
# #========================
print(img.shape)
dens = np.sum(img, axis=0)
mean = np.mean(dens)
print(mean)
#------------------------
# Thresholding
#========================
thresh = closed.copy()
for idx, val in enumerate(dens):
if val< 10800:
thresh[:,idx] = 0
(_, thresh2) = cv.threshold(thresh, 128, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
#------------------------
# plotting the results
#========================
plt.figure(num='barcode')
plt.subplot(221)
plt.imshow(img, cmap='gray')
plt.title('Original')
plt.axis('off')
plt.subplot(224)
plt.imshow(thresh, cmap='gray')
plt.title('Thresholded')
plt.axis('off')
plt.subplot(223)
plt.imshow(thresh2, cmap='gray')
plt.title('Result')
plt.axis('off')
plt.subplot(222)
plt.hist(dens)
plt.axvline(dens.mean(), color='k', linestyle='dashed', linewidth=1)
plt.title('dens hist')
plt.show()
#------------------------
# Printing the Output
#========================
barcodes = pyzbar.decode(thresh2)
print(barcodes)
輸出是:
[Decoded(data=b'00004980072868003004', type='CODE128', rect=Rect(left=34, top=0, width=526, height=99), polygon=[Point(x=34, y=1), Point(x=34, y=99), Point(x=560, y=98), Point(x=560, y=0)])]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.