一、功能需求
通过opencv及pyzbar库将图片中的二维码边界定位出来,然后再通过pyzbar识别二维码的信息
参考代码
import cv2 as cv
from pyzbar import pyzbar as pyzbar
def decodeDisplay(image):
barcodes = pyzbar.decode(image)
for barcode in barcodes:
# 提取二维码的边界框的位置
# 画出图像中条形码的边界框
(x, y, w, h) = barcode.rect
cv.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
# 提取二维码数据为字节对象,所以如果我们想在输出图像上
# 画出来,就需要先将它转换成字符串
barcodeData = barcode.data.decode("UTF8")
barcodeType = barcode.type
# 绘出图像上条形码的数据和条形码类型
text = "{} ({})".format(barcodeData, barcodeType)
cv.putText(image, text, (x, y - 10), cv.FONT_HERSHEY_SIMPLEX,.5, (0, 0, 125), 2)
# 向终端打印条形码数据和条形码类型
print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData))
return image,x,y,w,h
def detect():
camera = cv.VideoCapture(0)
while True:
# 读取当前帧
ret, frame = camera.read()
# 转为灰度图像
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
im = decodeDisplay(gray)
c=cv.waitKey(5)#等待5毫秒
cv.imshow("camera", im)
if(c==27):#按下esc键关闭摄像头窗口
camera.release()
cv.destroyAllWindows()
break
def detect2():
img=cv.imread('3.jpg')
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
im,x,y,w,h = decodeDisplay(gray)
print('x=%d y=%d w=%d h=%d'%(x,y,w,h))
cv.imshow('result',im)
cv.waitKey(0)
if __name__ == '__main__':
detect2()
二、代码实现
import cv2 as cv
from pyzbar import pyzbar as pyzbar
def detect(img):
barcodes = pyzbar.decode(img)
for barcode in barcodes:
# 提取二维码的边界框的位置
# 画出图像中条形码的边界框
(x, y, w, h) = barcode.rect
#目标区域y1:y2,x1:x2
img_dst = img[y-5:y+h+5,x-5:x+w+5]
return img_dst,x,y,w,h
def process():
img=cv.imread('1.jpg')
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
img_dst,x,y,w,h=detect(gray)
print('x=%d y=%d w=%d h=%d'%(x,y,w,h))
#将二维码区域保存
cv.imwrite('result.jpg',img_dst)
#用红色矩形框标记处二维码位置
cv.rectangle(img, (x-25, y-25), (x + w+25, y + h+25), (0, 0, 255), 8)
#窗口自适应显示
cv.namedWindow('result',cv.WINDOW_NORMAL)
cv.imshow('result',img_dst)
cv.waitKey(0)
if __name__ == '__main__':
process()