cv2.arcLength(curve, closed) -> retval
cv2.contourArea(contour, oriented=None) -> retval
cv2.boundingRect(array) -> retval
cv2.minEnclosingCircle(points) -> center, radius
cv2.approxPolyDP(curve, epsilon, closed, approxCurve=None) -> retval
cv2.isContourConvex(contour) -> retval
의 경우 약분하면 이 남게 되어 비율이 상수로 떨어지지 않는다. 따라서 로 만들어 비율을 계산해준다.
length = cv2.arcLength(pts, True)
area = cv2.contourArea(pts)
ratio = 4. * math.pi * area / (length * lenght)
if ratio > 0.05:
setLabel(img, pts, 'CIR') # 원
def setLabel(img, pts, label):
(x, y, w, h) = cv2.boundingRect(pts)
pt1 = (x, y)
pt2 = (x + w, y + h)
cv2.rectangle(img, pt1, pt2, (0, 0, 255), 1)
cv2.putText(img, label, pt1, cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255))
img = cv2.imread('polygon.bmp', cv2.IMREAD_COLOR)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, img_bin = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
contours, _ = cv2.findContours(img_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for pts in contours:
if cv2.contourArea(pts) < 400:
continue
approx = cv2.approxPolyDP(pts, cv2.arcLength(pts, True)*0.02, True)
vtc = len(approx)
if vtc == 3:
setLabel(img, pts, 'TRI')
elif vtc == 4:
setLabel(img, pts, 'RECT')
else
length = cv2.arcLength(pts, True)
area = cv2.contourArea(pts)
ratio = 4. * math.pi * area / (length * length)
if ratio > 0.85:
setLabel(img, pts, 'CIR')