我最近一直在使用 pyzbar,因为 python 3 不支持 zbar。有没有办法检测二维码的位置(4 个角)?在 zbar 中很容易,其中 symbol.location() 将显示二维码四个角的坐标。
最佳答案
描述
如果 pyzbar
检测到矩形二维码,以下代码计算其角坐标。 .
验证
代码在Windows 10 Pro N X64 上Anaconda Prompt 4.8.3 的python 3.6 环境中验证。在该操作系统中,它需要安装 Visual Studio 2013 的 Visual C++ Redistributable Packages。可以找到实现此设置的说明 here .
代码
# import libraries
from pyzbar.pyzbar import decode
from PIL import Image
# read the qr code from an image
qrcode = decode(Image.open('test6.png'))
# Get the rect/contour coordinates:
left = qrcode[0].rect[0]
top = qrcode[0].rect[1]
width = qrcode[0].rect[2]
height = qrcode[0].rect[3]
print(f'left={left},top={top},width={width},height={height}')
# get the rectangular contour corner coordinates
top_left = [top,left]
print(f'top_left={top_left}')
top_right = [top,left+width]
print(f'top_right={top_right}')
bottom_left = [top-height,left]
print(f'bottom_left={bottom_left}')
bottom_right = [top-height,left+width]
print(f'bottom_right={bottom_right}')
代码解释
注意 decode(Image.open('test6.png'))
返回第一个元素为:Decoded(data=b'9', type='QRCODE', rect=Rect(left=11, top=179, width=90, height=89), polygon=[Point(x=11, y=179), Point(x=11, y=268), Point(x=101, y=268), Point(x=101, y=179)])
的列表(但使用您测试它的二维码的数据/属性)。因此,qrcode[0].rect
对象返回 4 个矩形属性 left
, top
, width
和 height
的二维码。例如 qrcode[0].rect[3]
中的第二个索引用于选择二维码的特定矩形属性。然后使用二维码的这些特定矩形属性来计算二维码的角坐标。
关于zbar - 使用Pyzbar获取二维码位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48287816/