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()

结果:

相关推荐
chao_78911 分钟前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
烛阴20 分钟前
Python装饰器解除:如何让被装饰的函数重获自由?
前端·python
Boilermaker199233 分钟前
【Java EE】Mybatis-Plus
java·开发语言·java-ee
JNU freshman37 分钟前
计算机视觉速成 之 概述
人工智能·计算机视觉
aramae38 分钟前
C++ -- STL -- vector
开发语言·c++·笔记·后端·visual studio
Tony小周38 分钟前
实现一个点击输入框可以弹出的数字软键盘控件 qt 5.12
开发语言·数据库·qt
noravinsc1 小时前
django 一个表中包括id和parentid,如何通过parentid找到全部父爷id
python·django·sqlite
lixzest1 小时前
C++ Lambda 表达式详解
服务器·开发语言·c++·算法
ajassi20001 小时前
开源 python 应用 开发(三)python语法介绍
linux·python·开源·自动化
沉默媛1 小时前
如何安装python以及jupyter notebook
开发语言·python·jupyter