Opencv最强案例——使用摄像头、OpenCV和Python扫描条形码和二维码。

        Dynamsoft是唯一一家为Windows、Linux、macOS和Raspberry Pi OS提供企业级Python条形码和二维码SDK的公司。SDK允许开发人员快速构建健壮的命令行、web和桌面应用程序,这些应用程序可以扫描来自各种来源的条形码和QR码。在本文中,我们使用条形阅读器OpenCV和网络摄像头,用Python创建跨平台的桌面条形码和二维码扫描仪。

下载SDK

  • 开放计算机视觉

    用于访问网络摄像头和拼接图像。

    pip install opencv-python

  • Dynamsoft条形码阅读器

    用于解码图像中的条形码和QR码。

    pip install dbr

许可证激活

从获取桌面许可证密钥这里要激活Dynamsoft条形码阅读器:

BarcodeReader.init_license("LICENSE-KEY")

用Python构建条形码和QR码扫描仪的步骤

据知,Python的GIL(全局解释器锁)是多线程应用程序的性能瓶颈。因此,建议使用Python的多处理库来运行CPU密集型的条形码和二维码检测算法。示例代码视频_线程. py演示如何使用Python的多处理库。

以下是构建我们的条形码和QR码扫描仪的步骤:

  1. 导入必要的包:

    import numpy as np
    import cv2 as cv
    
    from multiprocessing.pool import ThreadPool
    from collections import deque
    
    import dbr
    from dbr import *

  2. 设置许可证密钥以激活和实例化Dynamsoft条形码读取器:

    threadn = 1 # cv.getNumberOfCPUs()
    pool = ThreadPool(processes = threadn)
    barcodeTasks = deque()

  3. 使用您想要使用的进程数量创建一个线程池:

    threadn = 1 # cv.getNumberOfCPUs()
    pool = ThreadPool(processes = threadn)
    barcodeTasks = deque()

    注意:如果您使用所有CPU核心,CPU使用率将会很高。

  4. 创建一个任务功能,从网络摄像头视频帧中检测条形码和QR码:

    def process_frame(frame):
        results = None
        try:
            results = reader.decode_buffer(frame)
        except BarcodeReaderError as bre:
            print(bre)
    
        return results
    
    while True:
        ret, frame = cap.read()
        while len(barcodeTasks) > 0 and barcodeTasks[0].ready():
            results = barcodeTasks.popleft().get()
            if results != None:
                for result in results:
                    points = result.localization_result.localization_points
                    cv.line(frame, points[0], points[1], (0,255,0), 2)
                    cv.line(frame, points[1], points[2], (0,255,0), 2)
                    cv.line(frame, points[2], points[3], (0,255,0), 2)
                    cv.line(frame, points[3], points[0], (0,255,0), 2)
                    cv.putText(frame, result.barcode_text, points[0], cv.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255))
    
        if len(barcodeTasks) < threadn:
            task = pool.apply_async(process_frame, (frame.copy(), ))
            barcodeTasks.append(task)
    
        cv.imshow('Barcode & QR Code Scanner', frame)
        ch = cv.waitKey(1)
        if ch == 27:
            break

  5. 运行条形码和QR码扫描仪:

    Opencv最强案例——使用摄像头、OpenCV和Python扫描条形码和二维码。_第1张图片

Dynamsoft条形码阅读器可以从一幅图像中检测多个条形码和QR码。然而,图像质量影响检测精度。正如你在上面的图像中看到的,为了捕捉所有的条形码和二维码,我们需要增加镜头的景深。这样,条形码和二维码可能会变得太小而无法读取。为了解决这一问题,我们将摄像头拉近以获得高质量的扫描图像,然后使用OpenCV拼接API将多个条形码和二维码图像拼接成一幅全景图。

将多个条形码和QR码图像拼接成全景图

OpenCV存储库包含一个stitching.py展示如何使用OpenCV缝合器API的文件。

要实现全景拼接:

  1. 初始化stitcher对象:

    modes = (cv.Stitcher_PANORAMA, cv.Stitcher_SCANS)
    stitcher = cv.Stitcher.create(modes[1])
    stitcher.setPanoConfidenceThresh(0.5)

  2. 为拼接包含条形码和QR码的图像创建新的任务功能:

    panoramaPool = ThreadPool(processes = threadn)
    panoramaTask = deque()
    
    def stitch_frame(self, frame):
        try:
            results = self.reader.decode_buffer(frame)
            if results != None:
                for result in results:
                    points = result.localization_result.localization_points
                    cv.line(frame, points[0], points[1], (0,255,0), 2)
                    cv.line(frame, points[1], points[2], (0,255,0), 2)
                    cv.line(frame, points[2], points[3], (0,255,0), 2)
                    cv.line(frame, points[3], points[0], (0,255,0), 2)
                    cv.putText(frame, result.barcode_text, points[0], cv.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255))
    
                self.panorama.append((frame, len(results)))
                print('Stitching .............')
                try:
                    all_images = [frame for frame, count in self.panorama]
                    status, image = self.stitcher.stitch(all_images)
    
                    if status != cv.Stitcher_OK:
                        print("Can't stitch images, error code = %d" % status)
                        return self.panorama[0][0]
                    else:
                        # Stop stitching if the output image is out of control
                        if image.shape[0] >= frame.shape[0] * 1.5:
                            self.isPanoramaDone = True
                            self.save_frame(all_images[0])
                            print('Stitching is done.............')
                            return None
    
                        # Drop the stitched image if its quality is not good enough
                        total = 0
                        for frame, count in self.panorama:
                            total += count
    
                        count_stitch = self.count_barcodes(image)
                        if count_stitch > total or count_stitch < self.panorama[0][1]:
                            return self.panorama[0][0]
    
                        # Wait for the next stitching and return the current stitched image
                        self.panorama = [(image, count_stitch)]
                        return image
                except Exception as e:
                    print(e)
                    return None
    
        except BarcodeReaderError as e:
            print(e)
            return None
    
        return None
    
    while len(panoramaTask) > 0 and panoramaTask[0].ready():
        image = panoramaTask.popleft().get()
        if image is not None:
            cv.imshow('panorama', image)
    
    if len(panoramaTask) < threadn:
        task = panoramaPool.apply_async(self.stitch_frame, (frame_cp, ))
        panoramaTask.append(task)

  3. 运行代码以获得全景拼接结果。

    Opencv最强案例——使用摄像头、OpenCV和Python扫描条形码和二维码。_第2张图片

  完整源代码关注公众号:Python源码或点这里即可获取 

你可能感兴趣的:(程序员,Python,python,源码,大数据)