Posted on

取得輪廓的中心點

以下為範例程式:

import cv2

# 讀取圖像,並將其轉換為灰度圖像
img = cv2.imread("image.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 進行閾值處理,以便更好地找到輪廓
ret, thresh = cv2.threshold(gray, 127, 255, 0)

# 查找輪廓
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# 繪製輪廓,以便在圖像上進行視覺化
cv2.drawContours(img, contours, -1, (0, 255, 0), 3)

# 計算輪廓的中心點
if len(contours) > 0:
    # 取最大的輪廓
    c = max(contours, key=cv2.contourArea)
    # 計算輪廓的矩
    M = cv2.moments(c)
    # 計算中心點座標
    center_x = int(M["m10"] / M["m00"])
    center_y = int(M["m01"] / M["m00"])
    # 繪製中心點,以便在圖像上進行視覺化
    cv2.circle(img, (center_x, center_y), 5, (255, 0, 0), -1)

# 顯示圖像
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()