cv2.findContours
判斷物件的形狀,可以通過計算輪廓的某些特徵來實現的。利用 cv2.findContours
判斷物件的形狀,可以通過計算輪廓的某些特徵來實現的。常用的方法包括:
import cv2
import numpy as np
# 讀取圖像並轉換為灰階
image = cv2.imread('圖片路徑')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 使用cv2.findContours來檢測輪廓
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print(len(contours))
for contour in contours:
# 獲取輪廓近似
epsilon = 0.04 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
# 使用頂點數判斷形狀
if len(approx) == 3:
shape = "Triangle"
elif len(approx) == 4:
# 檢測是否是矩形
(x, y, w, h) = cv2.boundingRect(approx)
aspect_ratio = float(w) / h
if 0.95 <= aspect_ratio <= 1.05:
shape = "Square"
else:
shape = "Rectangle"
else:
# 檢查是否為圓形,通過輪廓面積和邊界框面積的比率判斷
area = cv2.contourArea(contour)
circle_area = np.pi * (radius ** 2)
if 0.8 <= area / circle_area <= 1.2: # 比較輪廓面積與理論圓面積
shape = "Circle"
(x, y), radius = cv2.minEnclosingCircle(contour) #最小外接圓
else:
shape = "Unknown"
# 繪製輪廓和標註形狀
cv2.drawContours(image, [contour], -1, (0, 255, 0), 2)
x, y, w, h = cv2.boundingRect(contour) # 重新計算文字放置的位置
cv2.putText(image, shape, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
cv2.imshow('Shape detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
接下來的程式碼對每個輪廓進行處理和判斷:
for contour in contours:
epsilon = 0.04 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
if len(approx) == 3:
shape = "Triangle"
elif len(approx) == 4:
(x, y, w, h) = cv2.boundingRect(approx)
aspect_ratio = float(w) / h
if 0.95 <= aspect_ratio <= 1.05:
shape = "Square"
else:
shape = "Rectangle"
else:
area = cv2.contourArea(contour)
(x, y), radius = cv2.minEnclosingCircle(contour)
circle_area = np.pi * (radius ** 2)
if 0.8 <= area / circle_area <= 1.2:
shape = "Circle"