如何使用OpenCV Python將橢圓擬合到影像中的物體?
我們可以使用函式cv2.fitEllipse()將橢圓擬合到物體上。橢圓內接於旋轉矩形。旋轉矩形是包含物體的最小面積的邊界矩形。
語法
此函式使用的語法為:
ellipse = cv2.fitEllipse(cnt)
其中,“cnt”是輪廓點。它表示為輪廓點的陣列。
輸出 - 它返回一個元組的元組,格式為((x,y), (majorAxis, minorAxis), angle)。(x,y)是中心的座標,(majorAxis, minorAxis)是短軸和長軸的長度,angle是橢圓的旋轉角度。
要在輸入影像上繪製橢圓,我們使用以下函式:
cv2.ellipse(img,ellipse, (0,0,255), 3)
步驟
您可以使用以下步驟將橢圓擬合到物體:
匯入所需的庫。在以下所有Python示例中,所需的Python庫為OpenCV。確保您已安裝它。
import cv2
使用cv2.imread()讀取輸入影像並將其轉換為灰度影像。這裡我們載入名為star1.png的影像。
img = cv2.imread('star1.png') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
對灰度影像應用閾值處理以建立二值影像。調整第二個引數以獲得更好的輪廓檢測。
ret,thresh = cv2.threshold(gray,150,255,0)
使用cv2.findContours()函式查詢影像中的輪廓。
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
選擇一個輪廓“cnt”或迴圈遍歷所有輪廓。使用“cv2.fitEllipse(cnt)”函式將橢圓擬合到物體輪廓“cnt”。
cnt = contours[0] ellipse = cv2.fitEllipse(cnt)
在輸入影像上繪製橢圓。
cv2.ellipse(img,ellipse, (0,0,255), 3)
顯示帶有繪製的凸包的影像。
cv2.imshow("Ellipse", img) cv2.waitKey(0) cv2.destroyAllWindows()
讓我們看一些例子以便更清楚地理解。
我們使用以下影像作為以下示例的輸入檔案。
示例1
在下面的Python程式中,我們檢測影像中物體的輪廓並找到擬合物體的橢圓。我們在輸入影像上繪製橢圓。
# import required libraries import cv2 import numpy as np # load the input image img = cv2.imread('star1.png') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # apply thresholding to convert grayscale to binary image ret,thresh = cv2.threshold(gray,150,255,0) # find the contours contours,hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) print("Number of contours detected:", len(contours)) # select the first contour cnt = contours[0] # fit the ellipse to the selected object ellipse = cv2.fitEllipse(cnt) # draw the ellipse on the input image cv2.ellipse(img,ellipse, (0,0,255), 3) # display the image with an ellipse drawn on it. cv2.imshow("Ellipse", img) cv2.waitKey(0) cv2.destroyAllWindows()
輸出
執行上述程式碼後,將產生以下輸出:
Number of contours detected: 1
我們將得到以下輸出視窗:
擬合檢測到的物體的橢圓以紅色繪製。
讓我們找到橢圓內接的旋轉矩形。
示例2
在這個Python程式中,我們檢測影像中物體的輪廓並找到擬合物體的橢圓。我們還找到橢圓內接的旋轉矩形。我們在輸入影像上繪製橢圓和旋轉矩形。
# import required libraries import cv2 import numpy as np # load the input image img = cv2.imread('star1.png') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # apply thresholding to convert grayscale to binary image ret,thresh = cv2.threshold(gray,150,255,0) # find the contours contours,hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) print("Number of contours detected:", len(contours)) # select the first contour cnt = contours[0] # find the minimum area rectangle rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) box = np.int0(box) cv2.drawContours(img,[box],0,(0,255,255),2) # fit the ellipse ellipse = cv2.fitEllipse(cnt) cv2.ellipse(img,ellipse, (0,0,255), 3) # display the image with an ellipse drawn on it. cv2.imshow("ellipse", img) cv2.waitKey(0) cv2.destroyAllWindows()
輸出
執行上述程式碼後,將產生以下輸出:
Number of contours detected: 1
我們將得到以下輸出視窗:
橢圓以紅色繪製,旋轉矩形(最小面積)以黃色繪製。請注意,橢圓內接於旋轉矩形內。