我正在尝试在Python3上使用OpenCV来创建带有QR码的图像,然后将其读回。
这是一些相关的代码:
def make_qr_code(self, data):
qr = qrcode.QRCode(
version=2,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=4,
)
qr.add_data(data)
return numpy.array( qr.make_image().get_image())
# // DEBUG
img = numpy.ones([380, 380, 3]) * 255
index = self.make_qr_code('Hello StackOverflow!')
img[:index.shape[0], :index.shape[1]][index] = [0, 0, 255]
frame = img
# // DEBUG
self.show_image_in_canvas(0, frame)
frame_mono = cv.cvtColor(numpy.uint8(frame), cv.COLOR_BGR2GRAY)
self.show_image_in_canvas(1, frame_mono)
qr_detector = cv.QRCodeDetector()
data, bbox, rectifiedImage = qr_detector.detectAndDecode(frame_mono)
if len(data) > 0:
print("Decoded Data : {}".format(data))
self.show_image_in_canvas(2, rectifiedImage)
else:
print("QR Code not detected")
(对的调用show_image_in_canvas
仅用于在GUI中显示图像,因此我可以看到发生了什么)。
当检查frame
和frame_mono
视觉上,它看起来OK我
但是,QR码检测器不返回任何内容(进入其他:“未检测到QR码”)。
实际上,框架中除了我刚刚生成的QR码外没有其他内容。我需要对cv.QRCodeDetector进行哪些配置,或者需要对框架进行哪些其他预处理才能使其找到QR码?
在这里操作;通过仔细查看生成的QR码并将其与其他来源进行比较,解决了该问题。
问题不在于检测,而在于QR码的生成。显然,阵列qrcode.QRCode
返回具有False
(或者也许是0
和我假定这是一个布尔值)在方格即是代码的一部分,和True
(或非零)中是正方形不。
因此,当我这样做时img[:index.shape[0], :index.shape[1]][index] = [0, 0, 255]
,实际上是在创建QR码的负片。
当我反转index
阵列时,QR码从左侧的图像更改为右侧的图像,检测成功。
另外,我决定切换到ZBar库,因为它在不太理想的情况下(例如从网络摄像头图像中)检测这些代码要好得多。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句