你好啊
今天我们来学习利用OpenCV识别二维码和条形码,首先我们需要准备一个二维码,我准备个两个
接下来我们需要下载几个包,numpy,opencv,和pyzbar(这个工具包可以识别二维码,条形码等)
import cv2
import numpy as np
from pyzbar.pyzbar import decode
img = cv2.imread('Like.png')
code = decode(img)
print(code)
接下这一步我们利用摄像头去识别
import cv2
import numpy as np
from pyzbar.pyzbar import decode
#img = cv2.imread('Like.png')
cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)
while True:
success,img =cap.read()
for barcode in decode(img):
print(barcode.data)
myData = barcode.data.decode('utf-8')
print(myData)
cv2.imshow("Result",img)
cv2.waitKey(1)
这一步结束后就可以实时识别二维码了。接下来我们对识别的二维码添加一个方框:
for barcode in decode(img):
print(barcode.data)
#添加方框
pts = np.array([barcode.polygon],np.int32)
pts = pts.reshape((-1,1,2))
cv2.polylines(img,[pts],True,(255,15,255),5)
myData = barcode.data.decode('utf-8')
print(myData)
然后将识别出来的文本添加在二维码上:
#添加文本
pts2 = barcode.rect
cv2.putText(img,myData,(pts2[0],pts2[1]),cv2.FONT_HERSHEY_SIMPLEX,0.9,(255,50,255),2)
到这里这个功能就实现了,当然我们可以进一步扩展,做成一个身份识别的工具,效果无图:
完整代码:
import cv2
import numpy as np
from pyzbar.pyzbar import decode
#img = cv2.imread('Like.png')
cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)
with open('myDataID.text') as f:
myDatalist = f.read().splitlines()
while True:
success,img =cap.read()
for barcode in decode(img):
myData = barcode.data.decode('utf-8')
print(myData)
if myData in myDatalist:
myOutPut = 'Authorization'
myColour = (0,255,0)
else:
myOutPut = 'Un-Authorization'
myColour = (0,0,255)
#添加方框
pts = np.array([barcode.polygon],np.int32)
pts = pts.reshape((-1,1,2))
cv2.polylines(img,[pts],True,myColour,5)
#添加文本
pts2 = barcode.rect
cv2.putText(img,myOutPut,(pts2[0],pts2[1]),cv2.FONT_HERSHEY_SIMPLEX,0.9,myColour,2)
cv2.imshow("Result",img)
cv2.waitKey(1)
再见