Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cv2 as cv
- squares = 0
- circles = 0
- img = cv.imread("shapes1.png")
- # img = cv.imread("shapes2.png")
- img_grey = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
- _, threshold = cv.threshold(img_grey, 230, 255, cv.THRESH_BINARY)
- contours, _ = cv.findContours(threshold, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
- cv.imshow("Base image", img)
- for contour in contours:
- area = cv.contourArea(contour)
- if area > 100 and area < 100000: # area < 100000 beacuse picture is square
- approx = cv.approxPolyDP(contour, 0.01 * cv.arcLength(contour, True), True)
- cv.drawContours(img, [approx], 0, (0, 20, 20), 2)
- x = approx.ravel()[0]
- y = approx.ravel()[1] - 5
- if len(approx) == 4:
- x1, y1, w, h = cv.boundingRect(approx)
- aspectRatio = float(w) / h
- if aspectRatio >= 0.95 and aspectRatio <= 1.05:
- squares += 1
- else:
- circles += 1
- cv.putText(
- img,
- "Number of circles: " + str(circles),
- (20, 50),
- cv.FONT_HERSHEY_SIMPLEX,
- 1,
- (0, 0, 0),
- )
- cv.putText(
- img,
- "Number of squares: " + str(squares),
- (20, 100),
- cv.FONT_HERSHEY_SIMPLEX,
- 1,
- (0, 0, 0),
- )
- cv.imshow("Detected shapes", img)
- cv.waitKey(0)
- cv.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement