rectangle.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import cv2
  2. import numpy as np
  3. # define a video capture object
  4. vid = cv2.VideoCapture(0)
  5. while(True):
  6. # Capture the video frame
  7. # by frame
  8. ret, frame = vid.read()
  9. # Convert to grayscale.
  10. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  11. gray_blurred = cv2.blur(gray, (3, 3))
  12. ret, thresh = cv2.threshold(gray_blurred, 50,255,00)
  13. contours, hierarchy = cv2.findContours(thresh, 1, 2)
  14. if contours is not None:
  15. for cnt in contours:
  16. #x1,y1 = cnt[0][0]
  17. approx = cv2.approxPolyDP(cnt, 0.1*cv2.arcLength(cnt, True), True)
  18. if len(approx) == 4:
  19. x, y, w, h = cv2.boundingRect(approx)
  20. if (w > 40):
  21. if (w < 200):
  22. rect = cv2.minAreaRect(approx)
  23. box = cv2.boxPoints(rect)
  24. box = np.intp(box)
  25. frame = cv2.drawContours(frame,[box],0,(0,0,255),2)
  26. # Display the resulting frame
  27. cv2.imshow('frame', frame)
  28. #cv2.imshow('frame', thresh)
  29. # the 'q' button is set as the
  30. # quitting button you may use any
  31. # desired button of your choice
  32. if cv2.waitKey(1) & 0xFF == ord('q'):
  33. break
  34. # After the loop release the cap object
  35. vid.release()
  36. # Destroy all the windows
  37. cv2.destroyAllWindows()