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

结果:

相关推荐
Java面试题总结1 小时前
基于 Java 的 PDF 文本水印实现方案(iText7 示例)
java·python·pdf
不懒不懒1 小时前
【决策树算法实战指南:从原理到Python实现】
python·决策树·id3·c4.5·catr
马猴烧酒.2 小时前
【面试八股|Java集合】Java集合常考面试题详解
java·开发语言·python·面试·八股
以卿a2 小时前
C++(继承)
开发语言·c++·算法
lly2024062 小时前
XQuery 选择和过滤
开发语言
天空属于哈夫克32 小时前
Java 版:利用外部群 API 实现自动“技术开课”倒计时提醒
数据库·python·mysql
测试工程师成长之路2 小时前
Serenity BDD 框架:Java + Selenium 全面指南(2026 最新)
java·开发语言·selenium
czxyvX2 小时前
017-AVL树(C++实现)
开发语言·数据结构·c++
喵手2 小时前
Python爬虫实战:全站 Sitemap 自动发现 - 解析 sitemap.xml → 自动生成抓取队列的工业级实现!
爬虫·python·爬虫实战·零基础python爬虫教学·sitemap·解析sitemap.xml·自动生成抓取队列实现
luoluoal2 小时前
基于深度学习的web端多格式纠错系统(源码+文档)
python·mysql·django·毕业设计·源码