So i want to do calibration with the below image :enter image description here and i encounter this error : ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], camera_matrix, None, flags=cv2.CALIB_USE_INTRINSIC_GUESS) cv2.error: OpenCV(4.8.1) D:\a\opencv-python\opencv-python\opencv\modules\calib3d\src\calibration.cpp:3752: error: (-215:Assertion failed) nimages > 0 in function 'cv::calibrateCameraRO'
and my ret in this line of code ret, corners = cv2.findChessboardCorners(gray, (5,5), None) is always False so i changed the (5*5) and put it different number.
and this is my code :
import numpy as np
import cv2
import glob
import scipy.io
# Termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# Prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((6*7, 3), np.float32)
objp[:, :2] = np.mgrid[0:7, 0:6].T.reshape(-1, 2)
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d point in real-world space
imgpoints = [] # 2d points in image plane.
images = glob.glob('4/Cube_images/*.jpg')
for fname in images:
img = cv2.imread(fname)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find the chessboard corners
ret, corners = cv2.findChessboardCorners(gray, (5,5), None)
print(ret)
# If found, add object points, image points (after refining them)
if ret == True:
objpoints.append(objp)
print(objpoints)
corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
imgpoints.append(corners2)
print(imgpoints)
# Draw and display the corners
img = cv2.drawChessboardCorners(img, (5, 5), corners2, ret)
cv2.imshow('img', img)
cv2.waitKey(500)
cv2.destroyAllWindows()
# Estimate initial camera matrix using the aspect ratio
aspect_ratio = 1 # You might need to adjust this based on your camera
focal_length = 1 # Some initial guess for the focal length
# Estimate principal point (center) of the image
center = (0,0)
camera_matrix = np.array([[focal_length, 0, center[0]],
[0, focal_length, center[1]],
[0, 0, 1]])
# Camera calibration
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], camera_matrix, None, flags=cv2.CALIB_USE_INTRINSIC_GUESS)
# Extract focal length from the camera matrix
focal_length_x = mtx[0, 0]
focal_length_y = mtx[1, 1]
# Print the camera matrix and distortion coefficients
print("Camera Matrix:")
print(mtx)
print("\nDistortion Coefficients:")
print(dist)
print("\nFocal Length (fx):", focal_length_x)
print("Focal Length (fy):", focal_length_y)
mean_error = 0
tot_error = 0
for i in range(len(objpoints)):
imgpoints2, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist)
error = cv2.norm(imgpoints[i], imgpoints2, cv2.NORM_L2) / len(imgpoints2)
tot_error += error
a = tot_error/len(objpoints)
print(a)```
i have to do the calibration and find the focal length and fix this issue.