python - 如何使用python定位和读取Data Matrix代码

标签 python opencv datamatrix

我正在尝试读取微管底部的数据矩阵条形码。我试过 libdmtx它有 python 绑定(bind),当矩阵的点是正方形时工作得相当好,但当它们是圆形时更糟糕,如下所示:

datamatrix sample

另一种复杂情况是在某些情况下会到达代码区域。

条形码在平板扫描仪的架子上进行扫描,因此它们具有恒定的大小并且大致居中。方向是随机的。

我得出的结论是,我必须自己找到代码并改进图像。我使用 python 和 OpenCV 3.1。我已经尝试过阈值化、轮廓:

import matplotlib.pyplot as plt
import numpy as np
import cv2

well = plt.imread('/image/kqHkw.png')
well = cv2.cvtColor(well, cv2.COLOR_BGRA2GRAY)
plt.subplot(151); plt.imshow(well)

x, thr = cv2.threshold(well, .4[enter image description here][2], 1, cv2.THRESH_BINARY)
thr = np.uint8(thr)
plt.subplot(152); plt.imshow(thr)

dst, contours, hierarchy = cv2.findContours(thr.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
c = cv2.drawContours(np.zeros_like(thr), contours, -1, 255, 1)
plt.subplot(153); plt.imshow(c)

areas = map(lambda x: cv2.contourArea(cv2.convexHull(x)), contours)
max_i = areas.index(max(areas))
d = cv2.drawContours(np.zeros_like(thr), contours, max_i, 255, 1)
plt.subplot(154); plt.imshow(d)

rect = cv2.minAreaRect(contours[max_i])
box = cv2.boxPoints(rect)
box = np.int0(box)
e = cv2.drawContours(np.zeros_like(thr),[box],0,255,1)
plt.subplot(155); plt.imshow(e)

plt.show()

result

最佳答案

事实证明,Harris 角检测器 (B) 通过适当的设置可以很好地找到圆形元素。

result image here

在阈值化 (C) 之后,我们检测结果区域的轮廓。我们选择最大的轮廓 (D) 并找到最小的边界框 (E)。

import matplotlib.pyplot as plt
import numpy as np
import cv2
import PIL
from urllib.request import urlopen

well = np.array(PIL.Image.open(urlopen('/image/kqHkw.png')))
well = cv2.cvtColor(well, cv2.COLOR_BGRA2GRAY)
plt.subplot(151); plt.title('A')
plt.imshow(well)

harris = cv2.cornerHarris(well,4, 1,0.00)
plt.subplot(152); plt.title('B')
plt.imshow(harris)

x, thr = cv2.threshold(harris, 0.1 * harris.max(), 255, cv2.THRESH_BINARY)
thr = thr.astype('uint8')
plt.subplot(153); plt.title('C')
plt.imshow(thr)

contours, hierarchy = cv2.findContours(thr, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
areas = [cv2.contourArea(cv2.convexHull(x)) for x in contours]
max_i = areas.index(max(areas))
d = cv2.drawContours(np.zeros_like(thr), contours, max_i, 255, 1)
plt.subplot(154); plt.title('D')
plt.imshow(d)

rect = cv2.minAreaRect(contours[max_i])
box = cv2.boxPoints(rect)
box = np.int0(box)
e = cv2.drawContours(well,[box],0,1,1)
plt.subplot(155); plt.title('E')
plt.imshow(e)

plt.show()

关于python - 如何使用python定位和读取Data Matrix代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44926316/

相关文章:

python 记录 : is it possible to add module name to formatter

python - 如何去掉日期中无关的零?

python - 用户模型的 Django 自定义管理器

python - pylibdmtx 库,尝试除了不工作 - 断言 `value >= 0 && value < 256'

android - 使用 zxing 的 DataMatrix 编码仅生成 14px 位图

python - 如何在Excel文件中导出wxpython gui文本?

c - 函数cvShowImage使程序崩溃。为什么?开放式CV

c++ - 为什么 aHash 比 dHash 效果更好?

android - 从 ANDROID 设备实时流式传输视频到 OPENCV

r - 如何识别两个数据矩阵之间的哪些列和行匹配?