capture_images_without_showing.py 1.6 KB

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