[英]How to calculate the number of edges in a polygon using PIL/numpy
要計算邊緣數,您可以使用輪廓近似。 這個想法是一條曲線可以用一系列短線段來近似。 這導致生成的近似曲線由原始曲線定義的點的子集組成。
這是使用 OpenCV 的解決方案。 輪廓近似已經實現為cv2.approxPolyDP
近似多邊形曲線。 返回值的長度將是多邊形的邊數。
代碼
import cv2
# Load image, grayscale, Otsu's threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# Find contours and perform contour approximation
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.03 * peri, True)
print(len(approx))
結果
7
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.