图像轮廓(三)
🍔小小搬运工,一边搬运一边思考
参考书籍 《OpenCV轻松入门——面向Python李立宗著,电子工业出版社出版
0 引言
本节将介绍几个轮廓自身的属性特征及轮廓所包围的对象。
1 宽高比 AspectRation
矩形轮廓的宽高比为:
矩 形 轮 廓 的 宽 高 比 = 宽 度 ( W i d t h ) / 高 度 ( H e i g h t ) 矩形轮廓的宽高比=宽度(Width)/高度(Height) 矩形轮廓的宽高比=宽度(Width)/高度(Height)
例28:计算矩形的宽高比。
import cv2
#-----------------------读取并显示轮廓-----------------------------------------
o = cv2.imread("C:\\Users\\Kris\\Desktop\\3.jpg")
cv2.imshow("original",o)
#---------------------------------提取图像轮廓---------------------------------
gray1 = cv2.cvtColor(o,cv2.COLOR_BGR2GRAY)
ret,binary1 = cv2.threshold(gray1,127,255,cv2.THRESH_BINARY)
contour1,hierarchy = cv2.findContours(binary1,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
#--------------------------构造并显示矩形边界----------------------------
x,y,w,h = cv2.boundingRect(contour1[0])
cv2.rectangle(o,(x,y),(x+w,y+h),(255,255,255),3)
cv2.imshow("result",o)
#----------------------------计算宽高比--------------------------------------
aspectRatio = float(w)/h
print(aspectRatio)
#------------------------------等待释放窗口-------------------------------------
cv2.waitKey()
cv2.destroyAllWindows()
结果显示如下。
2 面积之比 Extend
轮廓面积与矩形边界(矩形包围框、矩形轮廓)面积之比来描述图像及其轮廓特征:
E x t e n d = 轮 廓 面 积 ( 对 象 面 积 ) / 矩 形 边 界 面 积 Extend = 轮廓面积(对象面积)/矩形边界面积 Extend=轮廓面积(对象面积)/矩形边界面积
例29:计算图像的轮廓面积与其矩形边界面积之比。
import cv2
#-----------------------读取并显示轮廓-----------------------------------------
o = cv2.imread("C:\\Users\\Kris\\Desktop\\3.jpg")
cv2.imshow("original",o)
#---------------------------------提取图像轮廓---------------------------------
gray1 = cv2.cvtColor(o,cv2.COLOR_BGR2GRAY)
ret,binary1 = cv2.threshold(gray1,127,255,cv2.THRESH_BINARY)
contour1,hierarchy = cv2.findContours(binary1,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
#--------------------------构造并显示矩形边界----------------------------
x,y,w,h = cv2.boundingRect(contour1[0])
cv2.drawContours(o,contour1[0],-1,(0,0,255),3)
cv2.rectangle(o,(x,y),(x+w,y+h),(255,0,0),3)
cv2.imshow("result",o)
#----------------------------计算--------------------------------------
rectArea = w*h
cntArea = cv2.contourArea(contour1[0])
extend = float(cntArea)/rectArea
print(extend)
#------------------------------等待释放窗口-------------------------------------
cv2.waitKey()
cv2.destroyAllWindows()
结果显示如下。
3 Solidity
轮廓面积与凸包面积之比Solidity来衡量图像、轮廓及凸包特征。
S o l i d i t y = 轮 廓 面 积 ( 对 象 面 积 ) / 凸 包 面 积 Solidity=轮廓面积(对象面积)/凸包面积 Solidity=轮廓面积(对象面积)/凸包面积
例30:编写程序计算图像轮廓面积与凸包面积之比。
import cv2
#-----------------------读取并显示轮廓-----------------------------------------
o = cv2.imread("C:\\Users\\Kris\\Desktop\\3.jpg")
cv2.imshow("original",o