Hi, I need the code about detecting shapes and colours of the shapes in the photo and the colors of the shapes. Now I coded in the PyCharm, but I can't get correct result from the my program because image's contours are not flat completely. So it says "Ellipse" for about the some triangles. I tried Median Blur, bilateral blur image smoothing methods. And I can't get correct result. Anyone can help to me? Thanks..
import cv2 import numpy as np font1= cv2.FONT_HERSHEY_PLAIN img_filter = cv2.imread("C:\\Users\\yusuf\\PycharmProjects\\OpenCV\\venv\\soru1.jpg") img=cv2.medianBlur(img_filter,1) cv2.imshow("img_filter",img_filter) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) _,threshold = cv2.threshold(gray,240,255,cv2.THRESH_BINARY) contours,_ = cv2.findContours(threshold,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) for cnt in contours:epsilon = 0.001*cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt,epsilon,True) x = approx.ravel()[0] y = approx.ravel()[1]
centres = [] for i in range(len(contours)): moments = cv2.moments(contours[i])
centres.append((int(moments['m10']/moments['m00']), int(moments['m01']/moments['m00']))) cv2.circle(img, centres[-1], 3, -1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) _, threshold = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) ucgen_sayaci=0 dortgen_sayaci=0 daire_sayaci=0
for cnt in contours: approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True) cv2.drawContours(img, [approx], 0, (0), 5) x = approx.ravel()[0] y = approx.ravel()[1] if len(approx) == 3: ucgen_sayaci = ucgen_sayaci + 1 cv2.putText(img, "Triangle", (x, y), font1, 1, (0)) elif len(approx) == 4: dortgen_sayaci = dortgen_sayaci + 1 cv2.putText(img, "Rectangle", (x, y), font1, 1, (0)) else: daire_sayaci = daire_sayaci + 1 cv2.putText(img, "Circle", (x, y), font1, 1, (0))
print("Ucgen Sayisi:",ucgen_sayaci) print("Dortgen Sayisi:",dortgen_sayaci) print("Daire Sayisi:",daire_sayaci) cv2.imwrite('output.png',img)
cv2.imshow("IMG",img) cv2.imshow("IMG1",img_filter)
cv2.waitKey(0) cv2.destroyAllWindows()