轮廓拟合
矩形包围轮廓
1,函数cv2.boundingRect()能够绘制轮廓的矩形边界
retval = cv2.boundingRect( array)
retval 表示返回矩形边界左上角顶点的坐标值及矩形边界的宽和高 , 也可以是4个返回值形式
x , y ,w ,h = cv2.boundingRect( array)
array 是灰度图像或轮廓
然后使用函数cv2.drawContours()来绘制矩形包围框
1 importcv22 importnumpy as np3 o = cv2.imread("cc.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 x,y,w,h =cv2.boundingRect(contours[0])10 brcnt = np.array([[[x,y]] ,[[x+w , y]] , [[x+w , y+h]] , [[x,y+h]]] )11 cv2.drawContours(o , [brcnt] , -1 ,(255,255,255) , 2)12 cv2.imshow("result",o)13 cv2.waitKey()14 cv2.destroyAllWindows()
原图
效果图
2,使用函数cv2.boundingRect() 即cv2.rectangle()绘制矩形包围框
1 importcv22 importnumpy as np3 o = cv2.imread("cc.bmp")4 gray =cv2.cvtColor(o , cv2.COLOR_BGR2GRAY)5 ret , binary = cv2.threshold(gray , 127 , 255,cv2.THRESH_BINARY)6 contours , hierarchy =cv2.findContours(binary , cv2.RETR_LIST ,7 cv2.CHAIN_APPROX_SIMPLE)8 x,y,w,h =cv2.boundingRect(contours[0])9 cv2.rectangle(o , (x,y) , (x+w , y+h) ,(255,255,255) , 2)10 cv2.imshow("result",o)11 cv2.waitKey()12 cv2.destroyAllWindows()
效果图
3。,最小包围矩形框函数cv2.minAreaRect()
该函数能绘制轮廓的最小包围矩形框,函数形式:
retval = cv2.minAreaRect( points )
返回值retval表示返回矩阵特征的信息,结构为(最小外接矩形的中心(x,y) , (宽度, 高度) , 旋转角度)
poin