Python - OpenCV识别条形码、二维码(已封装,拿来即用)

此代码可识别条形码和二维码,已封装好,拿来即用:

复制代码
import cv2
import pyzbar.pyzbar as pyzbar
import numpy
from PIL import Image, ImageDraw, ImageFont


class CodeScan():
    def __init__(self):
        super(CodeScan, self).__init__()

    def decodeDisplay(self, imagex1):
        # 转为灰度图像
        gray = cv2.cvtColor(imagex1, cv2.COLOR_BGR2GRAY)
        barcodes = pyzbar.decode(gray)

        for barcode in barcodes:

            # 提取条形码的边界框的位置
            # 画出图像中条形码的边界框
            (x, y, w, h) = barcode.rect
            cv2.rectangle(imagex1, (x, y), (x + w, y + h), (0, 255, 0), 2)

            # 条形码数据为字节对象,所以如果我们想在输出图像上
            # 画出来,就需要先将它转换成字符串
            barcodeData = barcode.data.decode("utf-8")
            barcodeType = barcode.type

            #不能显示中文
            # 绘出图像上条形码的数据和条形码类型
            #text = "{} ({})".format(barcodeData, barcodeType)
            #cv2.putText(imagex1, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,5, (0, 0, 125), 2)


            #更换为:
            img_PIL = Image.fromarray(cv2.cvtColor(imagex1, cv2.COLOR_BGR2RGB))

            # 参数(字体,默认大小)
            # font = ImageFont.truetype('fontx/hwst.ttf', 35)
            # 字体颜色(rgb)
            fillColor = (0,255,255)
            # 文字输出位置
            position = (x, y-10)
            # 输出内容
            str = barcodeData

            # 需要先把输出的中文字符转换成Unicode编码形式(  str.decode("utf-8)   )
            draw = ImageDraw.Draw(img_PIL)

            # 转换回OpenCV格式
            imagex1 = cv2.cvtColor(numpy.asarray(img_PIL), cv2.COLOR_RGB2BGR)

            # 向终端打印条形码数据和条形码类型
            print("Result->类别:{0} 内容:{1}".format(barcodeType, barcodeData))
        cv2.imshow("camera", imagex1)

    def detect(self):
        camera = cv2.VideoCapture(0)

        while True:
            # 读取当前帧
            ret, frame = camera.read()
            #print(ret.shape)
            self.decodeDisplay(frame)

            if(cv2.waitKey(5)==27):
                break
        camera.release()
        cv2.destroyAllWindows()


if __name__ == "__main__":
    scan = CodeScan()
    scan.detect()

结果:

相关推荐
小眼睛羊羊4 分钟前
pyinstaller打包paddleocr
python
java1234_小锋8 分钟前
基于Python的旅游推荐协同过滤算法系统(去哪儿网数据分析及可视化(Django+echarts))
python·数据分析·旅游
蓝婷儿10 分钟前
Python 机器学习核心入门与实战进阶 Day 4 - 支持向量机(SVM)原理与分类实战
python·机器学习·支持向量机
linux kernel11 分钟前
第七讲:C++中的string类
开发语言·c++
玩代码25 分钟前
Java线程池原理概述
java·开发语言·线程池
PyAIExplorer30 分钟前
图像处理中的边缘填充:原理与实践
图像处理·人工智能
%d%d234 分钟前
python 在运行时没有加载修改后的版本
java·服务器·python
泰勒疯狂展开41 分钟前
Java研学-MongoDB(三)
java·开发语言·mongodb
zzywxc7871 小时前
AI技术通过提示词工程(Prompt Engineering)正在深度重塑职场生态和行业格局,这种变革不仅体现在效率提升,更在重构人机协作模式。
java·大数据·开发语言·人工智能·spring·重构·prompt
高hongyuan1 小时前
Go语言教程-占位符及演示代码
开发语言·后端·golang