QR码定位方法--适用背景简单的QR码

#-*-coding:utf-8-*- 
__author__ = 'kavin.zhang'
import os
import cv2
import math
from matplotlib import pyplot as plt
import numpy as np

def show_rgb(img, code=cv2.COLOR_BGR2RGB):
    cv_rgb = cv2.cvtColor(img, code)
    cv2.namedWindow("image")
    cv2.imshow("image", cv_rgb)
    cv2.waitKey()
def show(img):
    cv2.namedWindow("image")
    cv2.imshow("image", img)
    cv2.waitKey()


image_path = ".\\QRImage"
img_list = os.listdir(image_path)
for image in img_list:
    img = os.path.join(image_path, image)
    img = cv2.imread(img)
    show_rgb(img)

    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # cv2.resize(img_gray,img_gray,(512,512))
    # img_gb = cv2.GaussianBlur(img_gray, (5, 5), 0)
    # show(img_gb) 
    edges = cv2.Canny(img_gray, 80, 150)
    show(edges)

    img_fc, contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    hierarchy = hierarchy[0]
    found = []
    for i in range(len(contours)):
        k = i
        c = 0
        while hierarchy[k][2] != -1:
            k = hierarchy[k][2]
            c = c + 1
        if c >= 5:
            found.append(i)

    for i in found:
        img_dc = img.copy()
        cv2.drawContours(img_dc, contours, i, (0, 255, 0), 3)
        show(img_dc)

    # 寻找定位标记的顶点
    draw_img = img.copy()
    for i in found:
        rect = cv2.minAreaRect(contours[i])
        box = cv2.boxPoints(rect)
        box = np.int0(box)
        cv2.drawContours(draw_img,[box], 0, (0,0,255), 2)
    show(draw_img)

    # 定位筛选,一个QR码有三个Position Detection Pattern 组
    # 寻找定位标记的顶点

    draw_img = img.copy()
    for i in found:
        rect = cv2.minAreaRect(contours[i])
        box = cv2.boxPoints(rect)
        box = np.int0(box)
        cv2.drawContours(draw_img,[box], 0, (0,0,255), 2)
    show(draw_img)

猜你喜欢

转载自blog.csdn.net/fly_caffe/article/details/80612575