capture_images_without_showing.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import cv2
  2. import os
  3. import sys
  4. import time
  5. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
  6. from default_config import *
  7. CHESS_BOARD_DIM = (9, 6)
  8. criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
  9. image_dir_path = f"CAMERA_CALIBRATION/images/{set_resolution}"
  10. os.makedirs(image_dir_path, exist_ok=True)
  11. def detect_checker_board(image, grayImage, criteria, boardDimension):
  12. ret, corners = cv2.findChessboardCorners(grayImage, boardDimension)
  13. if ret:
  14. corners1 = cv2.cornerSubPix(grayImage, corners, (3, 3), (-1, -1), criteria)
  15. image = cv2.drawChessboardCorners(image, boardDimension, corners1, ret)
  16. return image, ret
  17. cap = cv2.VideoCapture(0)
  18. # Thay đổi độ phân giải video theo cài đặt ở file default_config.py
  19. new_height = RESOLUTION_STANDARDS[set_resolution]
  20. new_width, new_height = change_resolution(cap, new_height)
  21. print(f'Resolution camera {new_width}x{new_height}')
  22. n = 0 # image counter
  23. MAX_IMAGES = 20 # Limit for automatic saving
  24. while True:
  25. ret, frame = cap.read()
  26. if not ret:
  27. break
  28. copyFrame = frame.copy()
  29. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  30. _, board_detected = detect_checker_board(frame, gray, criteria, CHESS_BOARD_DIM)
  31. if board_detected:
  32. save_path = f"{image_dir_path}/image{n}.png"
  33. cv2.imwrite(save_path, copyFrame)
  34. print(f"[INFO] Saved image {n} at {save_path}")
  35. n += 1
  36. if n >= MAX_IMAGES:
  37. break
  38. time.sleep(5)
  39. cap.release()
  40. print("Total saved images:", n)