Есть программа, хотел организовать нормальное распознавание координат, но что-то пошло не так...
import numpy as np
import cv2
#img = cv2.imread("output_3_2_rectangle.png")
img = cv2.imread("output_3_2_rectangle.png")
imgGrey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thrash = cv2.threshold(imgGrey, 240, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thrash, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
#cv2.imshow("img", img)
#cv2.line(img, (366, 109), (448, 158), (0, 0, 255), 5)
triangle = 0
square = 0
rectangle = 0
pentagon = 0
star = 0
polygon = 0
for contour in contours:
approx = cv2.approxPolyDP(contour, 0.01 * cv2.arcLength(contour, True), True)
x = approx.ravel()[0]
y = approx.ravel()[1] - 5
n = approx.ravel()
if len(approx) == 3:
triangle += 1
cv2.drawContours(img, [approx], 0, (0, 0, 0), 1)
cv2.putText(img, "Triangle", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0))
n = approx.ravel()
font = cv2.FONT_HERSHEY_COMPLEX
i = 0
for j in n:
if(i % 2 == 0):
x = n[i]
y = n[i + 1]
# Строка, содержащая координаты.
string = str(x) + " " + str(y)
if(i == 0):
# текст верхней координаты.
cv2.putText(img, "Arrow tip", (x, y), font, 0.5, (255, 0, 0))
else:
# текст по оставшимся координатам.
cv2.putText(img, string, (x, y), font, 0.5, (0, 255, 0))
i = i + 1
print(string)
elif len(approx) == 4:
x1, y1, w, h = cv2.boundingRect(approx)
aspectRatio = float(w)/h
print(aspectRatio)
if aspectRatio >= 0.95 and aspectRatio <= 1.05:
square += 1
cv2.drawContours(img, [approx], 0, (0, 0, 0), 1)
cv2.putText(img, "Square", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0))
else:
rectangle += 1
cv2.drawContours(img, [approx], 0, (0, 0, 0), 1)
cv2.putText(img, "Rectangle", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0))
elif len(approx) == 5:
pentagon += 1
#cv2.drawContours(img, [approx], 0, (0, 0, 0), 5)
cv2.putText(img, "Pentagon", (x, y),
cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0))
elif len(approx) == 10:
star += 1
#cv2.drawContours(img, [approx], 0, (0, 0, 0), 5)
cv2.putText(img, "Star", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0))
else:
polygon += 1
cv2.drawContours(img, [approx], 0, (0, 0, 0), 5)
cv2.putText(img, "Polygon", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0))
print(triangle)
print(square)
print(rectangle)
print(pentagon)
print(star)
print(polygon)
cv2.imshow("shapes", img)
cv2.imwrite("output_4.jpg", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Изначальное фото -
Конечное фото -