Python_OpenCV通过摄像头识别二维码和条形码

 参考:

python3 + opencv +pyzbar 摄像头检测二维码并获取二维码内容/版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/zx66zx/article/details/82785334

 

安装pyzbar库

pip install pyzbar

用的摄像头OpenCV打不开,只能用厂家的SDK,改了改参考代码

import cv2
import pyzbar.pyzbar as pyzbar
import numpy as np
 
from dvp import *#摄像头厂家提供的封装库
 
def frame2mat(frameBuffer):
    frame, buffer = frameBuffer
    bits = np.uint8 if(frame.bits == Bits.BITS_8) else np.uint16
    shape = None
    convertType = None
    if(frame.format >= ImageFormat.FORMAT_MONO and frame.format <= ImageFormat.FORMAT_BAYER_RG):
        shape = 1
    elif(frame.format == ImageFormat.FORMAT_BGR24 or frame.format == ImageFormat.FORMAT_RGB24):
        shape = 3
    elif(frame.format == ImageFormat.FORMAT_BGR32 or frame.format == ImageFormat.FORMAT_RGB32):
        shape = 4
    else:
        return None

    mat = np.frombuffer(buffer, bits)
    mat = mat.reshape(frame.iHeight, frame.iWidth, shape)   #转换维度
    return mat

def decodeDisplay(image):
    barcodes = pyzbar.decode(image)
    for barcode in barcodes:
        # 提取二维码的边界框的位置
        # 画出图像中条形码的边界框
        (x, y, w, h) = barcode.rect
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
 
        # 提取二维码数据为字节对象,所以如果我们想在输出图像上
        # 画出来,就需要先将它转换成字符串
        barcodeData = barcode.data.decode("utf-8")
        barcodeType = barcode.type
 
        # 绘出图像上条形码的数据和条形码类型
        text = "{} ({})".format(barcodeData, barcodeType)
        cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,
                    3, color=(0, 255, 0), thickness=5)
 
        # 向终端打印条形码数据和条形码类型
        print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData))
    return image
 
 
def detect():
    camera = Camera(0)#以索引号的方式打开相机
    camera.Start()#启动视频流
    cv2.namedWindow(u"Camera",0)#可以拖动窗口大小
    cv2.resizeWindow(u"Camera", 640, 480)#设置窗口大小
    cv2.moveWindow(u"Camera",1200,500)#设置窗口位置
 
    while (cv2.waitKey(1) != 27):
        # 读取当前帧
        frame = camera.GetFrame(3000)#从相机采集图像数据,超时时间为3000毫秒
        mat = frame2mat(frame)#转换为标准数据格式
        # 转为灰度图像
        #mat = cv2.cvtColor(mat, cv2.COLOR_BGR2GRAY)
        im = decodeDisplay(mat)
        cv2.imshow(u"Camera", im)
 
    cv2.destroyAllWindows()
 
 
if __name__ == '__main__':
    detect()

运行效果:

cv2.putText可以设置显示的提示文本的颜色,但是不是RGB而是BGR顺序,以及如果用的是黑白摄像头或者彩色摄像头进行了灰度图转换,就算设置了颜色也会输出为黑白的

二维码

Python_OpenCV通过摄像头识别二维码和条形码_第1张图片

条形码,不过识别框的显示有点问题

Python_OpenCV通过摄像头识别二维码和条形码_第2张图片

你可能感兴趣的:(工业摄像机,Python,python,opencv,计算机视觉,图像识别)