capture_images.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import cv2
  2. import os
  3. import sys
  4. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
  5. from default_config import *
  6. visualization = True
  7. CHESS_BOARD_DIM = (9, 6)
  8. criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
  9. # checking if images dir is exist not, if not then create images directory
  10. image_dir_path = f"CAMERA_CALIBRATION/images/{set_resolution}"
  11. if not os.path.exists(image_dir_path):
  12. os.makedirs(image_dir_path)
  13. def detect_checker_board(image, grayImage, criteria, boardDimension):
  14. ret, corners = cv2.findChessboardCorners(grayImage, boardDimension)
  15. if ret == True:
  16. corners1 = cv2.cornerSubPix(grayImage, corners, (3, 3), (-1, -1), criteria)
  17. image = cv2.drawChessboardCorners(image, boardDimension, corners1, ret)
  18. return image, ret
  19. cap = cv2.VideoCapture(0)
  20. # Thay đổi độ phân giải phù hợp với yêu cầu ban đầu
  21. new_height = RESOLUTION_STANDARDS[set_resolution]
  22. new_width, new_height = change_resolution(cap,new_height)
  23. print(f'Resolution camera {new_width}x{new_height}')
  24. n = 0 # image_counter
  25. while True:
  26. _, frame = cap.read()
  27. copyFrame = frame.copy()
  28. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  29. image, board_detected = detect_checker_board(frame, gray, criteria, CHESS_BOARD_DIM)
  30. if visualization:
  31. cv2.putText(
  32. frame,
  33. f"saved_img : {n}",
  34. (30, 40),
  35. cv2.FONT_HERSHEY_PLAIN,
  36. 1.4,
  37. (0, 255, 0),
  38. 2,
  39. cv2.LINE_AA,
  40. )
  41. cv2.imshow("frame", frame)
  42. cv2.imshow("copyFrame", copyFrame)
  43. key = cv2.waitKey(1)
  44. if key == ord("q"):
  45. break
  46. if key == ord("s") and board_detected == True:
  47. # storing the checker board image
  48. cv2.imwrite(f"{image_dir_path}/image{n}.png", copyFrame)
  49. print(f"saved image number {n}")
  50. n += 1 # incrementing the image counter
  51. cap.release()
  52. cv2.destroyAllWindows()
  53. print("Total saved Images:", n)