Python OpenCV查找图中的四边形/矩形

时间:2022-07-22
本文章向大家介绍Python OpenCV查找图中的四边形/矩形,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
实例来源于OpenCV自带历程,这里以OpenCV4.2为例,路径为:

F:opencv4.2_releaseopencvsourcessamplespythonsquares.py

本文稍作修改,做简要说明。目标是找到下图中的矩形轮廓和四边形轮廓:

矩形的检测包含检测轮廓是四个顶点,同时两条边的夹角接近90°,代码和效果如下:

import numpy as np
import cv2 as cv
# 设置putText函数字体
font=cv.FONT_HERSHEY_SIMPLEX
#计算两边夹角额cos值
def angle_cos(p0, p1, p2):
    d1, d2 = (p0-p1).astype('float'), (p2-p1).astype('float')
    return abs( np.dot(d1, d2) / np.sqrt( np.dot(d1, d1)*np.dot(d2, d2) ) )

def find_squares(img):
    squares = []
    img = cv.GaussianBlur(img, (3, 3), 0)   
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    bin = cv.Canny(gray, 30, 100, apertureSize=3)    
    contours, _hierarchy = cv.findContours(bin, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
    print("轮廓数量:%d" % len(contours))
    index = 0
    # 轮廓遍历
    for cnt in contours:
        cnt_len = cv.arcLength(cnt, True) #计算轮廓周长
        cnt = cv.approxPolyDP(cnt, 0.02*cnt_len, True) #多边形逼近
        # 条件判断逼近边的数量是否为4,轮廓面积是否大于1000,检测轮廓是否为凸的
        if len(cnt) == 4 and cv.contourArea(cnt) > 1000 and cv.isContourConvex(cnt):
            M = cv.moments(cnt) #计算轮廓的矩
            cx = int(M['m10']/M['m00'])
            cy = int(M['m01']/M['m00'])#轮廓重心
            
            cnt = cnt.reshape(-1, 2)
            max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in range(4)])
            # 只检测矩形(cos90° = 0)
            if max_cos < 0.1:
            # 检测四边形(不限定角度范围)
            #if True:
                index = index + 1
                cv.putText(img,("#%d"%index),(cx,cy),font,0.7,(255,0,255),2)
                squares.append(cnt)
    return squares, img

def main():
    img = cv.imread("./test.png")
    squares, img = find_squares(img)
    cv.drawContours( img, squares, -1, (0, 0, 255), 2 )
    cv.imshow('squares', img)
    ch = cv.waitKey()
    

    print('Done')


if __name__ == '__main__':
    print(__doc__)
    main()
    cv.destroyAllWindows()

代码比较简单,核心步骤上面已添加注释,筛选条件自己可以改,如果只想检测四边形,不限制为矩形,则修改如下地方:

# 只检测矩形(cos90° = 0)
if max_cos < 0.1:
# 检测四边形(不限定角度范围)
#if True:

效果如下:

大家使用的时候根据具体情况进行修改,C++的demo路径如下:

F:opencv4.2_releaseopencvsourcessamplescppsquares.cpp