opencv学习记录之图像轮廓之二

计算轮廓的面积:contourArea

retval  = cv2.contourArea(contour [, oriented])

retval 为返回的面积

contour 为轮廓

oriented 为布尔值 ,为True时 返回值包含正负号,用来表示轮廓是顺时针还是逆时针,党委False时返回值为绝对值

以下代码计算了各轮廓的面积还将面积大于15000的轮廓画为红色

 1 import cv2                                                                       
 2 import numpy as np 
 3 o = cv2.imread("contours.bmp")
 4 cv2.imshow("original" , o) 
 5 gray = cv2.cvtColor(o , cv2.COLOR_BGR2GRAY)
 6 ret , binary = cv2.threshold(gray , 127 , 255 , cv2.THRESH_BINARY)
 7 contours , hierarchy = cv2.findContours(binary, cv2.RETR_LIST ,
 8         cv2.CHAIN_APPROX_SIMPLE)
 9 n = len(contours)
10 contoursImg =[]
11 for i in range(n):
12     temp = np.zeros(o.shape , np.uint8)
13     contoursImg.append(temp)
14     if cv2.contourArea(contours[i]) > 15000:
15         contoursImg[i] = cv2.drawContours(contoursImg[i] , contours , i ,
16                 (0,0,255) , 3) 
17     else:
18         contoursImg[i] = cv2.drawContours(contoursImg[i] , contours ,
19                 i , (255,255,255) , 3) 
20     cv2.imshow("contours[" + str(i) +"]" , contoursImg[i])
21 cv2.waitKey()
22 cv2.destroyAllWindows()

 

计算轮廓的长度,

retval = cv2.arcLength(curve , closed)

retval 是轮廓的周长

curve是轮廓

closed 是布尔值表示轮廓是否为封闭的,True表示轮廓为封闭的

 1 import cv2                                                                       
 2 import numpy as np 
 3 o = cv2.imread("contours0.bmp")
 4 cv2.imshow("original" , o) 
 5 gray = cv2.cvtColor(o , cv2.COLOR_BGR2GRAY)
 6 ret , binary = cv2.threshold(gray, 127 , 255 , cv2.THRESH_BINARY)
 7 contours , hierarchy = cv2.findContours(binary , cv2.RETR_LIST ,
 8         cv2.CHAIN_APPROX_SIMPLE)
 9 n = len(contours)
10 cntLen = [] 
11 for i in range(n):
12     cntLen.append(cv2.arcLength(contours[i] , True))
13     print("" +str(i) + "个轮廓的长度:%d" %cntLen[i])
14 cntLenSum = np.sum(cntLen)
15 cntLenAvr = cntLenSum/n
16 print("zongchangdu :%d"%cntLenSum)
17 print("pingjunchangdu:%d"%cntLenAvr)
18 contoursImg = [] 
19 for i in range(n):
20     temp = np.zeros(o.shape , np.uint8)
21     contoursImg.append(temp)
22     contoursImg[i] = cv2.drawContours(contoursImg[i] , contours , i ,
23             (255,255,255) , 3) 
24     if cv2.arcLength(contours[i] , True) > cntLenAvr:
25         cv2.imshow("contours[" +str(i) +"] " ,contoursImg[i])
26 cv2.waitKey()
27 cv2.destroyAllWindows()

代码会将长度大于平均长度的轮廓显示出来

第0个轮廓的长度:145
第1个轮廓的长度:147
第2个轮廓的长度:398
第3个轮廓的长度:681
第4个轮廓的长度:1004
第5个轮廓的长度:398
第6个轮廓的长度:681
第7个轮廓的长度:1004
第8个轮廓的长度:2225
第9个轮廓的长度:2794
zongchangdu :9480
pingjunchangdu:948

原始图像

 第四个轮廓

 第七个轮廓

 第八个轮廓

第九个轮廓即图像最外层整体轮廓

原文地址:https://www.cnblogs.com/miaorn/p/12263726.html