capture_images.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. # nếu tồn tại thư mục ảnh, xóa đi và tạo lại
  10. image_dir_path = f"camera_calibration/images/{set_resolution}"
  11. if os.path.exists(image_dir_path):
  12. import shutil
  13. shutil.rmtree(image_dir_path)
  14. os.makedirs(image_dir_path)
  15. def detect_checker_board(image, grayImage, criteria, boardDimension):
  16. ret, corners = cv2.findChessboardCorners(grayImage, boardDimension)
  17. if ret == True:
  18. corners1 = cv2.cornerSubPix(grayImage, corners, (3, 3), (-1, -1), criteria)
  19. image = cv2.drawChessboardCorners(image, boardDimension, corners1, ret)
  20. return image, ret
  21. cap = cv2.VideoCapture(0)
  22. # Thay đổi độ phân giải phù hợp với yêu cầu ban đầu
  23. new_height = RESOLUTION_STANDARDS[set_resolution]
  24. new_width, new_height = change_resolution(cap,new_height)
  25. print(f'Resolution camera {new_width}x{new_height}')
  26. n = 0 # image_counter
  27. while True:
  28. _, frame = cap.read()
  29. copyFrame = frame.copy()
  30. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  31. image, board_detected = detect_checker_board(frame, gray, criteria, CHESS_BOARD_DIM)
  32. if visualization:
  33. cv2.putText(
  34. frame,
  35. f"saved_img : {n}",
  36. (30, 40),
  37. cv2.FONT_HERSHEY_PLAIN,
  38. 1.4,
  39. (0, 255, 0),
  40. 2,
  41. cv2.LINE_AA,
  42. )
  43. cv2.imshow("frame", frame)
  44. cv2.imshow("copyFrame", copyFrame)
  45. key = cv2.waitKey(1)
  46. if key == ord("q"):
  47. break
  48. if key == ord("s") and board_detected == True:
  49. # storing the checker board image
  50. cv2.imwrite(f"{image_dir_path}/image{n}.png", copyFrame)
  51. print(f"saved image number {n}")
  52. n += 1 # incrementing the image counter
  53. cap.release()
  54. cv2.destroyAllWindows()
  55. print("Total saved Images:", n)