Advertisement
Guest User

Untitled

a guest
Apr 6th, 2020
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. import cv2 as cv
  2.  
  3. squares = 0
  4. circles = 0
  5. img = cv.imread("shapes1.png")
  6. # img = cv.imread("shapes2.png")
  7.  
  8. img_grey = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
  9. _, threshold = cv.threshold(img_grey, 230, 255, cv.THRESH_BINARY)
  10. contours, _ = cv.findContours(threshold, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
  11.  
  12. cv.imshow("Base image", img)
  13. for contour in contours:
  14.     area = cv.contourArea(contour)
  15.     if area > 100 and area < 100000:  # area < 100000 beacuse picture is square
  16.         approx = cv.approxPolyDP(contour, 0.01 * cv.arcLength(contour, True), True)
  17.         cv.drawContours(img, [approx], 0, (0, 20, 20), 2)
  18.         x = approx.ravel()[0]
  19.         y = approx.ravel()[1] - 5
  20.         if len(approx) == 4:
  21.             x1, y1, w, h = cv.boundingRect(approx)
  22.             aspectRatio = float(w) / h
  23.             if aspectRatio >= 0.95 and aspectRatio <= 1.05:
  24.                 squares += 1
  25.         else:
  26.             circles += 1
  27.  
  28. cv.putText(
  29.     img,
  30.     "Number of circles: " + str(circles),
  31.     (20, 50),
  32.     cv.FONT_HERSHEY_SIMPLEX,
  33.     1,
  34.     (0, 0, 0),
  35. )
  36. cv.putText(
  37.     img,
  38.     "Number of squares: " + str(squares),
  39.     (20, 100),
  40.     cv.FONT_HERSHEY_SIMPLEX,
  41.     1,
  42.     (0, 0, 0),
  43. )
  44.  
  45. cv.imshow("Detected shapes", img)
  46. cv.waitKey(0)
  47. cv.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement