【opencv4 检测二维码】cv4判断图片是否包含二维码

opencv4.0版本以后,加入了二维码定位解码的功能。下面我们将使用该功能,进行图片二维码检测。

由于 python中cv2模块的imread函数呆以正常读取’jpg’,'png’格式的图片,但是不能处理’gif’图片。可以改用imageio模块来处理。

安装 imageio 模块

pip install imageio

安装 opencv4

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv-python==4.0.0.21

# -*- coding: utf-8 -*-
import cv2
import os
import imageio

import numpy as np



def readImg(image_path):
    """
    :param image_path: 图片路径
    :return:
    """

    im = cv2.imread(image_path)
    if im is None :
        tmp = imageio.mimread(image_path)
        if tmp is not None:
            imt = np.array(tmp)
            imt = imt[0]
            im = imt[:,:,0:3]
    return im



def cv4_detect_qrcode(image_path):
    """
    :param image_path: 图片路径
    :return: 是否包含二维码
    """
    image_type = []
    try:
        img = readImg(image_path)
        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        qrcode = cv2.QRCodeDetector()
        result_detection, transform, straight_qrcode = qrcode.detectAndDecode(img_gray)

        if transform is not None:
            image_type.append(1)
        else:
            image_type.append(0)

    except Exception as e:
        print(e)
        image_type.append(0)

    return image_type[0]








if __name__ == '__main__':

    filepath = 'F:/img_spam/test_pyzbar/'
    for parent, dirnames, filenames in os.walk(filepath):
        for filename in filenames:
            image_path = filepath + filename
            image_type = cv4_detect_qrcode(image_path)
            if image_type==1:
                print(filename,image_type)

我们这里只用到了定位功能,若定位到有二维码,则transform 返回的是坐标。没有定位到坐标,则判断该图片没有二维码。

你可能感兴趣的:(数据科学--python)