OpenCV 學習筆記03 boundingRect、minAreaRect、minEnclosingCircle 函數的用法
1 cv2.boundingRect
作用:矩形邊框(boundingRect),用於計算圖像一系列點的外部矩形邊界。
cv2.boundingRect(array) -> retval
參數
array - 灰度圖像(gray-scale image)或 2D點集( 2D point set )
返回值
元組(x, y, w, h ) 矩形左上點坐標,w, h 是矩陣的寬、高,例如 (161, 153, 531, 446)
代碼示例:
contours, hierarchy = cv2.findContours(re_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)for c in contours: # find bounding box coordinates # 現計算出一個簡單的邊界框 x, y, w, h = cv2.boundingRect(c) # 畫出矩形 cv2.rectangle(img, (x,y), (x+w, y+h), (0, 255, 0), 2)
2 cv2.minAreaRect
作用:minAreaRect - min Area Rect 最小區域矩形;計算指定點集的最小區域的邊界矩形,矩形可能會發生旋轉 possibly rotated,以保證區域面積最小。
cv2.minAreaRect(points) -> retval
參數:
points - 2D點的矢量( vector of 2D points )
返回值:
元組((最小外接矩形的中心坐標),(寬,高),旋轉角度)-----> ((x, y), (w, h), θ )
如 ((458.70343017578125, 381.97894287109375), (202.513916015625, 634.2526245117188), -45.707313537597656)
但繪制這個矩形,一般需要知道矩形的 4 個頂點坐標;通常是通過函數 cv2.boxPoints()獲取。
附 : cv2.boxPoints
作用:查找旋轉矩形的 4 個頂點(用於繪制旋轉矩形的輔助函數)。
cv2.boxPoints(box) -> points參數:
box - 旋轉的矩形
返回值:
points - 矩形 4 個頂點組成的數組
返回值示例:
[[614.9866 675.9137 ] [161. 232.99997] [302.4203 88.04419] [756.40686 530.9579 ]]
代碼示例:
contours, hierarchy = cv2.findContours(re_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for c in contours: # find minimum area # 計算包圍目標的最小矩形區域 rect = cv2.minAreaRect(c) # calculate coordinate of the minimum area rectangle box = cv2.boxPoints(rect) # normalize coordinates to integers box =np.int0(box) # 註:OpenCV沒有函數能直接從輪廓信息中計算出最小矩形頂點的坐標。所以需要計算出最小矩形區域, # 然後計算這個矩形的頂點。由於計算出來的頂點坐標是浮點型,但是所得像素的坐標值是整數(不能獲取像素的一部分), # 所以需要做一個轉換 # draw contours cv2.drawContours(img, [box], 0, (0, 0, 255), 3) # 畫出該矩形
但是要繪制這個矩形,我們需要矩形的4個頂點坐標box, 通過函數 cv2.cv.BoxPoints() 獲得,box:[ [x0,y0], [x1,y1], [x2,y2], [x3,y3] ]
最小外接矩形的4個頂點順序、中心坐標、寬度、高度、旋轉角度(是度數形式,不是弧度數)的對應關系如下:
註:當數據
該函數計算並返回指定點集的最小區域邊界矩形(可能旋轉)。 開發人員應該記住,當數據接近包含的Mat元素邊界時,返回的RotatedRect可以包含負索引。
。
OpenCV 學習筆記03 boundingRect、minAreaRect、minEnclosingCircle 函數的用法