如何从图像中获取条形码?

时间:2019-12-02 20:49:16

标签: python image opencv noise-reduction

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

BarCode

这是代码:

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)
  

结果:[]

2 个答案:

答案 0 :(得分: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()

反二值化图像:

Binarized

重建的图像:

Reconstruction

我不确定结果是否为有效的条形码。为了改善解决方案,您可以事先删除数字。另外,请尝试使用阈值。

希望有帮助!

答案 1 :(得分:0)

您可以遵循以下方法:

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