Oi
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.7 KiB

  1. # Python code to find the co-ordinates of
  2. # the contours detected in an image.
  3. import numpy as np
  4. import cv2
  5. # Reading image
  6. font = cv2.FONT_HERSHEY_COMPLEX
  7. img2 = cv2.imread('card.jpg', cv2.IMREAD_COLOR)
  8. # Reading same image in another
  9. # variable and converting to gray scale.
  10. img = cv2.imread('card.jpg', cv2.IMREAD_GRAYSCALE)
  11. # Converting image to a binary image
  12. # ( black and white only image).
  13. _, threshold = cv2.threshold(img, 110, 255, cv2.THRESH_BINARY)
  14. # Detecting contours in image.
  15. contours, _= cv2.findContours(threshold, cv2.RETR_TREE,
  16. cv2.CHAIN_APPROX_SIMPLE)
  17. # Going through every contours found in the image.
  18. for cnt in contours :
  19. approx = cv2.approxPolyDP(cnt, 0.009 * cv2.arcLength(cnt, True), True)
  20. # draws boundary of contours.
  21. cv2.drawContours(img2, [approx], 0, (0, 0, 255), 5)
  22. # Used to flatted the array containing
  23. # the co-ordinates of the vertices.
  24. n = approx.ravel()
  25. i = 0
  26. for j in n :
  27. if(i % 2 == 0):
  28. x = n[i]
  29. y = n[i + 1]
  30. # String containing the co-ordinates.
  31. string = str(x) + " " + str(y)
  32. if(i == 0):
  33. # text on topmost co-ordinate.
  34. cv2.putText(img2, "Arrow tip", (x, y),
  35. font, 0.5, (255, 0, 0))
  36. else:
  37. # text on remaining co-ordinates.
  38. cv2.putText(img2, string, (x, y),
  39. font, 0.5, (0, 255, 0))
  40. i = i + 1
  41. # Showing the final image.
  42. cv2.imshow('image2', img2)
  43. # Exiting the window if 'q' is pressed on the keyboard.
  44. if cv2.waitKey(0) & 0xFF == ord('q'):
  45. cv2.destroyAllWindows()