树莓派 二维码(QR)识别 python篇

                         树莓派 二维码(QR)识别 python篇

 

要使用的工具

  • python Image 图像包
  • zbar条码及二维码识别库
  • opencv 库

 

识别效果

识别效果图
在树莓派终端键入的命令以及得到的识别结果:
运行效果命令
可以看到识别结果被红色矩形框标记,QR码的内容为YGSOFT001

接下来详细的描述整个工作过程。

 

python Image图像包的安装

sudo apt-get install python-imaging

zbar 安装

执行如下代码:

sudo apt-get -y install libzbar-dev
wget https://pypi.python.org/packages/source/z/zbar/zbar-0.10.tar.gz
tar xzf zbar-0.10.tar.gz

cd zbar-0.10
wget https://github.com/npinchot/zbar/commit/d3c1611ad2411fbdc3e79eb96ca704a63d30ae69.patch

git apply d3c1611ad2411fbdc3e79eb96ca704a63d30ae69.patch
sudo python setup.py install
 

如果安装出现问题,请尝试 sudo apt-get update 以及 sudo apt-get upgrade,然后再重试上面的安装步骤。

编写python程序

首先是导入相应的包

import cv2
import pyzbar.pyzbar as pyzbar
import time

下面是源程序:

import cv2
import pyzbar.pyzbar as pyzbar
import time

 
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,

                    .5, (0, 0, 125), 2)

 

        # 向终端打印条形码数据和条形码类型

        print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData))

    return image

 

 

def detect():

    camera = cv2.VideoCapture(0)
    camera.set(3,640) #设置分辨率
    camera.set(4,480) #设置分辨率
    #time.sleep(0.5)
       

    while True:

        # 读取当前帧

        ret, frame = camera.read()

        # 转为灰度图像

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        im = decodeDisplay(gray)

 

        cv2.waitKey(5)

        cv2.imshow("camera", im)

 

    camera.release()

    cv2.destroyAllWindows()

 

 

if __name__ == '__main__':

    detect()

运行结果:

希望对你有帮助。

猜你喜欢

转载自blog.csdn.net/qq_41204464/article/details/84933226
今日推荐