最终实现视频动态识别二维码。
import cv2 as cv
import numpy as np
src_image = cv.imread("E:\VSCode\qrcoder\hello.jpg")
qrcoder = cv.QRCodeDetector()
codeinfo, points, straight_qrcode = qrcoder.detectAndDecode(src_image)
cv.drawContours(src_image, [np.int32(points)], 0, (0, 0, 255), 2)
print(points)
print("qrcode :", codeinfo)
cv.imshow("result", src_image)
cv.waitKey(0)
points
得到的二维码四个点的坐标信息。
import cv2
import pyzbar.pyzbar as pyzbar
import numpy as np
from PIL import Image, ImageDraw, ImageFont
def decodeDisplay(video):
gray = cv2.cvtColor(video, cv2.COLOR_BGR2GRAY)
barcodes = pyzbar.decode(gray)
for barcode in barcodes:
(x, y, w, h) = barcode.rect # 提取二维码的位置,然后用边框标识出来在视频中
cv2.rectangle(video, (x, y), (x + w, y + h), (0, 255, 0), 2)
barcodeData = barcode.data.decode("utf-8") # 字符串转换
barcodeType = barcode.type
# 在图像上面显示识别出来的内容 #不能显示中文
# text = "{}".format(barcodeData)
# cv2.putText(video, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,1, (0, 255, 0), 2)
img_PIL = Image.fromarray(cv2.cvtColor(video, cv2.COLOR_BGR2RGB))
font = ImageFont.truetype('font/simsun.ttc', 35) # 参数(字体,大小)
fillColor = (0,255,255) # 字体颜色(rgb)
position = (x, y-50) # 文字输出位置
str = barcodeData # 输出内容
draw = ImageDraw.Draw(img_PIL)
draw.text(position, str, font=font, fill=fillColor)
video = np.array(img_PIL)
print("[扫描结果] 二维码类别: {0} 内容: {1}".format(barcodeType, barcodeData))
cv2.imshow("cam", video)
def detect():
cv2.namedWindow("hello",cv2.WINDOW_NORMAL)
cam = cv2.VideoCapture(0)
while True:
ret, frame = cam.read()
decodeDisplay(frame)
if(cv2.waitKey(5)==27):
break
cam.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
detect()
import serial
ser = serial.Serial("com12", 115200, timeout=0.5)
UartSend_Data = bytearray([0xff, 0x00, 0x00, 0x00])
ser.write(UartSend_Data)
result=ser.write("nihao你好 ".encode("gbk"))
print("写总字节数:",result)
# print(ser.read())#读一个字节
# print(ser.read(10).decode("gbk"))#读十个字节
# print(ser.readline().decode("gbk"))#读一行
# print(ser.readlines())#读取多行,返回列表,必须匹配超时(timeout)使用
# print(ser.in_waiting)#获取输入缓冲区的剩余字节数
# print(ser.out_waiting)#获取输出缓冲区的字节数
def serload():
if ser.in_waiting:
str1 = ser.readline().decode('GBK') # 读一行,以/n结束。
print(str1)
while True:
serload()
from pygame import mixer
import time
mixer.init()
mixer.music.load('E:/VSCode/qrcoder/14361.mp3')
mixer.music.play()
time.sleep(5)
mixer.music.stop()
把上述4个功能结合在一起,当识别到特定二维码开启音乐并且串口发送数据给单片机。留给你完成。