Chapter 08:Contour and Shape Detection

   随着本专栏的学习,你可以快速的掌握如何使用Opencv,请注意更多的学习内容还请看官方文档,本专栏是为了给对于视觉方向比较感兴趣的新手所写,带领它们做好一个基础的框架,让他们快速学会如何通过这个框架调取函数做自己感兴趣的项目,同时我也正在更新我的Opencv项目实战专栏,你可以搭配着一起学习。

订阅此专栏, (2条消息) Opencv项目实战_夏天是冰红茶的博客-CSDN博客


效果展示 

 在这里,我们对于原图像中的轮廓和形状进行了检测。分别含有三角形、圆形、正方形、矩形等。且根据图像的大小添加了矩形框。

本篇代码

import cv2
import numpy as np

def stackImages(scale,imgArray):
    rows = len(imgArray)
    cols = len(imgArray[0])
    rowsAvailable = isinstance(imgArray[0], list)
    width = imgArray[0][0].shape[1]
    height = imgArray[0][0].shape[0]
    if rowsAvailable:
        for x in range ( 0, rows):
            for y in range(0, cols):
                if imgArray[x][y].shape[:2] == imgArray[0][0].shape [:2]:
                    imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)
                else:
                    imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)
                if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv2.cvtColor( imgArray[x][y], cv2.COLOR_GRAY2BGR)
        imageBlank = np.zeros((height, width, 3), np.uint8)
        hor = [imageBlank]*rows
        hor_con = [imageBlank]*rows
        for x in range(0, rows):
            hor[x] = np.hstack(imgArray[x])
        ver = np.vstack(hor)
    else:
        for x in range(0, rows):
            if imgArray[x].shape[:2] == imgArray[0].shape[:2]:
                imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)
            else:
                imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale)
            if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)
        hor= np.hstack(imgArray)
        ver = hor
    return ver

#获取轮廓函数
def getContours(img):
    contours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
    #contours轮廓,hierarchy次等级,cv2.findContours查找轮廓函数,第二个参数为检索方法,cv2.RETR_EXTERNAL检索极端的外部轮廓
    for cnt in contours:
        area = cv2.contourArea(cnt)  #轮廓区域
        print(area)
        if area>500:
            cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), 3)  #绘制轮廓函数
            #参数:原始图像,轮廓,轮廓索引=-1,即绘制所有的轮廓
            peri = cv2.arcLength(cnt,True)
            #曲线长度,找到轮廓的弧长
            #print(peri)
            #逼近角点
            approx = cv2.approxPolyDP(cnt,0.02*peri,True)
            print(len(approx))
            #多变型拟合后点的个数
            objCor = len(approx)
            #边界框边界矩形
            x, y, w, h = cv2.boundingRect(approx)

            if objCor ==3: objectType ="Tri"
            elif objCor == 4:
                aspRatio = w/float(h)
                #纵横比判断正方形还是长方形
                if aspRatio >0.98 and aspRatio <1.03:
                    objectType= "Square"
                else:
                    objectType="Rectangle"
            elif objCor>4: objectType= "Circles"
            else:objectType="None"
            #绘制外框
            cv2.rectangle(imgContour,(x,y),(x+w,y+h),(0,255,0),2)

            cv2.putText(imgContour,objectType,
                        (x+(w//2)-10,y+(h//2)-10),cv2.FONT_HERSHEY_COMPLEX,0.7,
                        (0,0,0),2)
            #0.7—大小,2—厚度




path = 'Resources/shapes.png'
img = cv2.imread(path)
imgContour = img.copy()  #原始图像副本

imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgGray,(7,7),1)
#参数,灰度图像,内核,sigma=1,越高越模糊
imgCanny = cv2.Canny(imgBlur,50,50)
#边缘检测
getContours(imgCanny)

imgBlank = np.zeros_like(img)  #黑色图像
imgStack = stackImages(0.6,([img,imgGray,imgBlur],
                            [imgCanny,imgContour,imgBlank]))

cv2.imshow("Stack", imgStack)

cv2.waitKey(0)

就像我之前所说的,我们只需要调用stackImages,接下来需要写一个getContours()的函数,以便于我们寻找它的轮廓,然后根据我们的一拟合点,判断它们的形状是三角形、正方形等,其中的一些函数可能第一次接触,我就尽可能的将注释添上。在这之后,我们就可以根据原图像的一系列转换——灰度转换、高斯模糊、Canny检测。

现实意义

在之后的轮廓检测中,也是非常重要的一个思路,比如物体检测或识别,当我们将这个框架搭好后,后面我们就可以根据这个框架调用,创建好我们项目的搭建,比如拼接合并图形,特征检测这些。

猜你喜欢

转载自blog.csdn.net/m0_62919535/article/details/127218928