我正在使用 zxing-cpp 库从图像中读取条形码。
import cv2
import zxingcpp
img = cv2.imread('test.jpg')
results = zxingcpp.read_barcodes(img)
for result in results:
print('Found barcode:'
f'\n Valid: "{result.valid}"'
f'\n Text: "{result.text}"'
f'\n Format: {result.format}'
f'\n Content: {result.content_type}'
f'\n Position: {result.position}')
if len(results) == 0:
print("Could not find any barcode.")
但是,该库无法从图像扫描这个简单的条形码。
如何处理图像并提高图像质量以便读取条形码?
我使用这个问题的答案作为指导,但仍然不成功,因此我问这个问题并寻求帮助?
参考这个问题和这个问题,我只是增加了图像的亮度和对比度。这似乎对你的形象有用。但是,您应该知道,仅仅因为此解决方案适用于这张照片,并不能保证它适用于您测试的每张照片。我只是按照这些步骤操作,因为我发现您的照片有点暗且模糊。我认为这些步骤可以让您了解条形码检测的一些要求。
import cv2
import zxingcpp
def increase_brightness(img, value=30):
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
lim = 255 - value
v[v > lim] = 255
v[v <= lim] += value
final_hsv = cv2.merge((h, s, v))
img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
return img
def increase_contrast(img, clip_limit=2.0, tile_grid_size=(8,8)):
lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
l_channel, a, b = cv2.split(lab)
clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=tile_grid_size)
cl = clahe.apply(l_channel)
limg = cv2.merge((cl,a,b))
enhanced_img = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
return enhanced_img
img = cv2.imread('test.jpg')
cv2.namedWindow("original", cv2.WINDOW_NORMAL)
cv2.imshow("original", img)
img = increase_brightness(img, 30)
cv2.namedWindow("brightness_increased", cv2.WINDOW_NORMAL)
cv2.imshow("brightness_increased", img)
img = increase_contrast(img)
cv2.namedWindow("contrast_increased", cv2.WINDOW_NORMAL)
cv2.imshow("contrast_increased", img)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.namedWindow("grayscale", cv2.WINDOW_NORMAL)
cv2.imshow("grayscale", img)
results = zxingcpp.read_barcodes(img)
for result in results:
print('Found barcode:'
f'\n Valid: "{result.valid}"'
f'\n Text: "{result.text}"'
f'\n Format: {result.format}'
f'\n Content: {result.content_type}'
f'\n Position: {result.position}')
if len(results) == 0:
print("Could not find any barcode.")
cv2.waitKey(0)
输出为:
Found barcode:
Valid: "True"
Text: "4607023704821"
Format: BarcodeFormat.EAN13
Content: ContentType.Text
Position: 198x549 720x549 720x561 198x561