如何在 OpenCV Python 中找到物體的最小外接圓?
物體的最小外接圓(外接圓)是一個完全覆蓋物體且面積最小的圓。我們可以使用函式cv2.minEnclosingCircle()來找到物體的最小外接圓。
語法
此函式的語法如下:
(x,y),radius = cv2.minEnclosingCircle(cnt)
其中,“cnt”是輪廓點。它表示為輪廓點的陣列。
輸出 - 它返回中心座標 (x,y) 和最小外接圓的半徑。(x,y) 和半徑為浮點型別。因此,要在影像上繪製圓圈,我們將它們轉換為整數。
要繪製最小外接圓,我們使用與在影像上繪製圓圈的函式相同的函式:
cv2.circle(img,center,radius,(0,255,0),2)
步驟
您可以使用以下步驟來找到物體的最小外接圓:
匯入所需的庫。在以下所有 Python 示例中,所需的 Python 庫為OpenCV。確保您已安裝它。
import cv2
使用cv2.imread()讀取輸入影像並將其轉換為灰度影像。這裡我們載入一個名為fourpoint-star.png的影像。
img = cv2.imread('fourpoint-star.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.minEnclosingCircle(cnt) 函式查詢輪廓 cnt 的最小外接圓。
cnt = contours[0] (x,y),radius = cv2.minEnclosingCircle(cnt)
將中心和半徑傳遞給以下函式,在輸入影像上繪製最小外接圓。第三個和第四個引數是繪製的圓圈的顏色和粗細。
center = (int(x),int(y)) radius = int(radius) cv2.circle(img,center,radius,(0,255,0),2)
顯示帶有繪製的凸包的影像。
cv2.imshow("Circle", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
讓我們看一些示例以更清楚地理解。
示例 1
在下面的 Python 程式中,我們檢測影像中物體的輪廓並找到物體的最小外接圓。我們還在輸入影像上繪製最小外接圓。
# import required libraries import cv2 # load the input image img = cv2.imread('fourpoint-star.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 enclosing circle (x,y),radius = cv2.minEnclosingCircle(cnt) # convert the radius and center to integer number center = (int(x),int(y)) radius = int(radius) # Draw the enclosing circle on the image cv2.circle(img,center,radius,(0,255,0),2) cv2.imshow("Circle", img) cv2.waitKey(0) cv2.destroyAllWindows()
我們將在本程式中使用此影像作為輸入檔案:

輸出
執行上述程式碼後,將產生以下輸出:
Number of contours detected: 1
並且,我們將獲得以下輸出視窗:

檢測到的物體的最小外接圓以綠色繪製。
示例 2
在此示例中,我們檢測影像中物體的輪廓並找到物體的最小外接圓。我們還在輸入影像上繪製所有最小外接圓。
import cv2 import matplotlib.pyplot as plt img = cv2.imread('shape.png') img1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(img1,150,255,0) contours,hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) print("Number of objects detected:", len(contours)) # find the enclosing circle for all the contours in the image for cnt in contours: (x,y),radius = cv2.minEnclosingCircle(cnt) center = (int(x),int(y)) radius = int(radius) img = cv2.circle(img,center,radius,(0,0,255),3) # Display the image cv2.imshow("Circle", img) cv2.waitKey(0) cv2.destroyAllWindows()
我們將在本程式中使用此影像作為輸入檔案:

輸出
當我們執行上述程式碼時,它將產生以下輸出:
Number of contours detected: 3
並且我們將獲得以下輸出視窗:

檢測到的物體的最小外接圓以紅色顯示。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP