import cv2

cam = cv2.VideoCapture(0)

CHECKERBOARD = (5,8)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)

img_counter = 0

while True:
	ret, frame = cam.read()
	if not ret:
		print("failed to grab frame")
		break
		
	frame = cv2.resize(frame, (640,480))

	gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
	ret, corners = cv2.findChessboardCorners(frame, CHECKERBOARD)

	cv2.imshow("test", frame)

	if ret == True:
		print(corners)
		fnn = cv2.drawChessboardCorners(frame, CHECKERBOARD, corners, ret)
		cv2.imshow("result", fnn)

	k = cv2.waitKey(1)
	if k%256 == 27:
		# ESC pressed
		print("Escape hit, closing...")
		break
	elif k%256 == 32:
		# SPACE pressed
		img_name = "opencv_frame_{}.png".format(img_counter)
		cv2.imwrite(img_name, frame)
		print("{} written!".format(img_name))
		img_counter += 1

cam.release()

cv2.destroyAllWindows()
