OpenCV二维码检测器未绘边框却在原点生成圆形问题求助
问题:二维码检测器无法绘制边框反而在(0,0)生成圆形
我是OpenCV及高阶Python代码的入门学习者,正在开发一款基于图片(非摄像头流)的二维码检测器。我从网上找到参考代码并尝试修改,但现在程序未在二维码周围绘制边框,反而以(0,0)为中心生成圆形(将厚度改为100时更明显),无法理解原因,相关代码如下:
import cv2 import numpy as np import sys import time if len(sys.argv)>1: inputImage = cv2.imread(sys.argv[1]) else: inputImage = cv2.imread("path/qrcode.jpg") # Display barcode and QR code location def display(im, bbox): n = len(bbox) bbox = bbox.astype(int) for j in range(n): cv2.line(im, tuple(bbox[j][0]), tuple(bbox[ (j+1) % n][0]), (255,0,0), 3) # Display results cv2.imshow("Results", im) # Create a qrCodeDetector Object qrDecoder = cv2.QRCodeDetector() # Detect and decode the qrcode t = time.time() data,bbox,rectifiedImage = qrDecoder.detectAndDecode(inputImage) print("Time Taken for Detect and Decode : {:.3f} seconds".format(time.time() - t)) if len(data)>0: print("Decoded Data : {}".format(data)) display(inputImage, bbox) rectifiedImage = np.uint8(rectifiedImage); cv2.imshow("Rectified QRCode", rectifiedImage); else: print("QR Code not detected") cv2.imshow("Results", inputImage) cv2.waitKey(0) cv2.destroyAllWindows()
问题原因
你代码里的bbox索引逻辑错误,导致传递给cv2.line的坐标不完整。OpenCV的QRCodeDetector.detectAndDecode返回的bbox是**形状为(4,2)**的numpy数组,每个元素对应二维码四个角的(x,y)坐标。但你用了bbox[j][0],这只会提取每个角坐标的第一个值(x),第二个值(y)被忽略,OpenCV会默认把缺失的y值设为0,所有线条都从(x,0)出发,最终呈现出类似(0,0)附近圆形的效果。
修复方案
修改display函数中的坐标索引方式,直接使用bbox[j]和bbox[(j+1)%n]获取完整的(x,y)坐标,同时为了兼容不同OpenCV版本可能返回的(1,4,2)形状的bbox,可以先添加一步维度调整:
# Display barcode and QR code location def display(im, bbox): # 调整bbox维度,确保是(4,2)的形状 bbox = bbox.reshape(4, 2).astype(int) n = len(bbox) for j in range(n): # 直接取bbox[j]作为完整坐标 cv2.line(im, tuple(bbox[j]), tuple(bbox[(j+1) % n]), (255,0,0), 3) # Display results cv2.imshow("Results", im)
修改后,程序会正确识别二维码的四个角坐标,并在其周围绘制蓝色边框。
内容的提问来源于stack exchange,提问作者SilverGerry118
相关产品推荐
相关产品推荐

