【问题标题】:How to get barcode from image?如何从图像中获取条形码?
【发布时间】:2019-12-02 20:49:16
【问题描述】:

我需要使用 Python pyzbar 库获取以下条形码中的信息,但它无法识别。在使用pyzbar之前我应该​​做任何改进吗?

这是代码:

from pyzbar.pyzbar import decode
import cv2

    def barcodeReader(image):
        gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        barcodes = decode(gray_img)

    barcode = barcodeReader("My_image")
    print (barcode)

结果:[]

【问题讨论】:

  • 您可以尝试应用锐化滤镜,但它可能无法被识别,因为您的图像太损坏了

标签: python image opencv noise-reduction


【解决方案1】:

您可以尝试通过以下方式重建条形码:

  1. 使用cv2.threshold 对图像进行反向二值化,这样您就可以在黑色背景上看到白线。
  2. 使用np.count_nonzero 沿行计算所有非零像素。
  3. 获取计数超过预定义阈值的所有索引,例如100
  4. 在新的全白图像上,在找到的索引处绘制黑线。

这里有一些代码:

import cv2
import numpy as np
from skimage import io      # Only needed for web grabbing images, use cv2.imread for local images

# Read image from web, convert to grayscale, and inverse binary threshold
image = cv2.cvtColor(io.imread('https://i.stack.imgur.com/D8Jk7.jpg'), cv2.COLOR_RGB2GRAY)
_, image_thr = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY_INV)

# Count non-zero pixels along the rows; get indices, where count exceeds certain threshold (here: 100)
row_nz = np.count_nonzero(image_thr, axis=0)
idx = np.argwhere(row_nz > 100)

# Generate new image, draw lines at found indices
image_new = np.ones_like(image_thr) * 255
image_new[35:175, idx] = 0

cv2.imshow('image_thr', image_thr)
cv2.imshow('image_new', image_new)
cv2.waitKey(0)
cv2.destroyAllWindows()

反二值化图像:

重建图像:

我不确定结果是否是有效的条形码。要改进解决方案,您可以事先去掉这些数字。另外,玩弄阈值。

希望有帮助!

【讨论】:

  • @AndresMarin 真可惜!但正如 nathancy 在他的评论中已经说过的那样,您的图像可能太破碎而无法进行适当的重建。
  • 因为这出现在另一个问题中:这种方法相当于沿列积分/求和然后阈值化。这个想法是使用集成来抑制噪音。
【解决方案2】:

您可以按照以下方法:

  1. 使用形态学运算检测垂直线并存储垂直图像的xmin ymin、xmax和ymax。
  2. 对所有 xmin 值进行排序并根据距离对它们进行分组。
  3. 做同样的练习 ymin 和 ymax 并将它们分组。
  4. 分别考虑较大组 xmin 和 ymin 较大组中的最小像素值。
  5. 分别考虑较大组 xmax 和 ymax 较大组中的最大值。
  6. 您将获得准确的 xmin,ymin,xmax,ymax 条码。

【讨论】:

    猜你喜欢
    • 2010-09-11
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 2013-11-21
    • 2010-12-06
    • 2015-07-11
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多