example.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import cv2
  2. import numpy as np
  3. import sys
  4. if __name__ == "__main__":
  5. if(len(sys.argv)) < 2:
  6. file_path = "sample.jpg"
  7. else:
  8. file_path = sys.argv[1]
  9. # read image
  10. src = cv2.imread(file_path, 1)
  11. # show source image
  12. cv2.imshow("Source", src)
  13. # convert image to gray scale
  14. gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
  15. # blur the image
  16. blur = cv2.blur(gray, (3, 3))
  17. # binary thresholding of the image
  18. ret, thresh = cv2.threshold(blur, 200, 255, cv2.THRESH_BINARY)
  19. # find contours
  20. im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, \
  21. cv2.CHAIN_APPROX_SIMPLE)
  22. # create hull array for convexHull points
  23. hull = []
  24. # calculate points for each contour
  25. for i in range(len(contours)):
  26. hull.append(cv2.convexHull(contours[i], False))
  27. # create an empty black image
  28. drawing = np.zeros((thresh.shape[0], thresh.shape[1], 3), np.uint8)
  29. # draw contours and hull points
  30. for i in range(len(contours)):
  31. color_contours = (0, 255, 0) # color for contours
  32. color = (255, 255, 255) # color for convex hull
  33. # draw contours
  34. cv2.drawContours(drawing, contours, i, color_contours, 2, 8, hierarchy)
  35. # draw convex hull
  36. cv2.drawContours(drawing, hull, i, color, 2, 8)
  37. cv2.imshow("Output", drawing)
  38. cv2.waitKey(0)
  39. cv2.destroyAllWindows()