使用Pyzbar获取qr代码的位置

时间:2018-01-16 18:39:57

标签: zbar

我最近一直在使用pyzbar,因为python 3不支持zbar。有没有办法检测qr代码的位置(4个角)?在zbar中很容易,其中symbol.location()将显示qr代码四个角的坐标。

2 个答案:

答案 0 :(得分:0)

您可以提取条形码的边界框位置,如下所示。

barcodes = pyzbar.decode(image)
(x, y, w, h) = barcode.rect

其中x和y是起始坐标,w和h是边界框的宽度和高度。

答案 1 :(得分:0)

说明

如果pyzbar检测到以下qr代码,则以下代码将计算该矩形qr代码的角坐标。

验证

该代码已在Windows 10 Pro N X64上的Anaconda Prompt 4.8.3中的python 3.6环境中进行了验证。在该操作系统中,需要安装Visual Studio 2013的Visual C ++可再发行组件程序包。有关实现此设置的说明,请参见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)])(但包含对其进行测试的qr代码的数据/属性)。因此,qrcode[0].rect对象返回qr代码的4个矩形属性lefttopwidthheight。例如,qrcode[0].rect[3]中的第二个索引用于选择qr码的特定矩形属性。然后,使用这些二维码的特定矩形属性来计算二维码的角坐标。