python-opencv轮廓检测(外轮廓检测和全部轮廓检测,计算轮廓面积和周长)

python-opencv轮廓检测(外轮廓检测和全部轮廓检测,计算轮廓面积和周长)

通过cv2.findContours,我们可以进行轮廓检测,当然也有很多检测模式,我们可以通过选择检测模式,进行外轮廓检测,或者全部轮廓检测等等,可以实现不同的需求。
另外opencv也封装了计算轮廓面积和周长的函数,注意,轮廓基本上都是点组成的,也就是说,我们可以通过opencv封装的函数计算一堆点集的周长和面积。

print(cv2.contourArea(cnt))#输出面接
print(cv2.arcLength(cnt,True))#True闭合的周长,输出周长
cnt为轮廓点集,这个函数,以后博主觉得是有很大实用效果的。
代码如下:

from ctypes.wintypes import SIZE
from multiprocessing.pool import IMapUnorderedIterator
import cv2
import copy
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import os

path=r'D:learnphotocvcontours.png'

img=cv2.imread(path,1)

img_gray=cv2.imread(path,0)



def cv_show(name,img):
    cv2.imshow(name,img)
    #cv2.waitKey(0),接收0,表示窗口暂停
    cv2.waitKey(0)
    #销毁所有窗口
    cv2.destroyAllWindows()


#cv_show('img_gray',img_gray)



#进行二值化处理
ret,binary=cv2.threshold(img_gray,127,255,cv2.THRESH_BINARY)


#cv_show('dist',dist)

def BGR_TO_RGB(img):
    return img[:,:, ::-1]
#检测轮廓

#取值一:CV_RETR_EXTERNAL只检测最外围轮廓,包含在外围轮廓内的内围轮廓被忽略


#           取值二:CV_RETR_LIST   检测所有的轮廓,包括内围、外围轮廓,但是检测到的轮廓不建立等级关

#                  系,彼此之间独立,没有等级关系,这就意味着这个检索模式下不存在父轮廓或内嵌轮廓,

#                  所以hierarchy向量内所有元素的第3、第4个分量都会被置为-1,具体下文会讲到


#           取值三:CV_RETR_CCOMP  检测所有的轮廓,但所有轮廓只建立两个等级关系,外围为顶层,若外围

#                  内的内围轮廓还包含了其他的轮廓信息,则内围内的所有轮廓均归属于顶层


#           取值四:CV_RETR_TREE, 检测所有轮廓,所有轮廓建立一个等级树结构。外层轮廓包含内层轮廓,内

#                   层轮廓还可以继续包含内嵌轮廓。

#countourClose 轮廓坐标信息
#hierrachyclose 轮廓之间的层次结构


   
countourClose,hierrachyclose=cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)


result2=cv2.drawContours(img.copy(),countourClose,-1,(0,0,255),2)

#CV_RETR_CCOMP  检测所有的轮廓,但所有轮廓只建立两个等级关系,外围为顶层,若外围

#                  内的内围轮廓还包含了其他的轮廓信息,则内围内的所有轮廓均归属于顶层
   
countourClose,hierrachyclose=cv2.findContours(binary,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)


result3=cv2.drawContours(img.copy(),countourClose,-1,(0,0,255),2)


countourClose,hierrachyclose=cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

result=cv2.drawContours(img.copy(),countourClose,-1,(0,0,255),2)

print("len(countourclose) is",len(countourClose))

    #

plt.figure(figsize=(400,600))




print(img_gray.shape)
print(img_gray[0][0])
plt.subplot(221)
#img_gray=BGR_TO_RGB(img_gray,'gray')
plt.imshow(img_gray,'gray')
plt.title('img_gray')


plt.subplot(222)

plt.imshow(result,'gray')

plt.title('RETR_TREE')

plt.subplot(223)

plt.imshow(result2,'gray')

plt.title('RETR_EXTERNAL')
plt.subplot(224)

plt.imshow(result3,'gray')

plt.title('RETR_CCOMP')
plt.show()

#输出面接和周长


for  i in range(len(countourClose)):
     cnt=countourClose[i]
     print(cv2.contourArea(cnt))#输出面接
     print(cv2.arcLength(cnt,True))#True闭合的周长,输出周长



     


os.system("pause")


运行结果如下:

在这里插入图片描述
在这里插入图片描述

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>