Wie baue ich eine robuste Kamera -Kalibrierungsfunktion mit OpenCV mit findCirclesGrid und SimpleBlobdetektor auf?
Posted: 14 Apr 2025, 18:15
Ich arbeite an einer Kamera -Kalibrierungspipeline unter Verwendung von OpenCV, wobei das Muster ein Punktgitter (kreisförmiges Gitter) ist. Ich verwende cv2.findcirclesgrid () in Kombination mit einem CV2.simleblobdetektor zum Nachweis von Blob. schwarz). und fokale Längen. /> < /li>
Kann Kreisnetze unter verschiedenen Bedingungen zuverlässig erkennen. Bereiche.
Kann Kreisnetze unter verschiedenen Bedingungen zuverlässig erkennen. Bereiche.
Code: Select all
import cv2
import numpy as np
import matplotlib.pyplot as plt`
image = cv2.imread("/content/drive/MyDrive/image0000005.bmp") # Use your actual image path
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_inverted = cv2.bitwise_not(gray)
params = cv2.SimpleBlobDetector_Params()
params.filterByArea = True
params.filterByCircularity = True
params.maxArea = 70000;
params.minArea = 60000;
params.minThreshold = 5;
params.maxThreshold = 255;
params.thresholdStep = 50;
params.minCircularity = 0.8;
params.filterByInertia = False;
params.filterByConvexity = True;
params.minConvexity = 0.01
detector = cv2.SimpleBlobDetector_create(params)
def find_grid(gray_img):
pattern_size = (4,4) # Adjust to your pattern
found, centers = cv2.findCirclesGrid(
gray_img,
pattern_size,
flags=cv2.CALIB_CB_SYMMETRIC_GRID | cv2.CALIB_CB_CLUSTERING,
blobDetector=detector
)
return found, centers
found, centers = find_grid(inverted)
if not found:
print("Trying inverted image...")
found, centers = find_grid(inverted)
output = inverted.copy()
if found:
pattern_size = (4,4)
cv2.drawChessboardCorners(output, (4,4), centers, found)
print("✅ Circle grid detected!")
print("\n=== detected center ===")
print(centers)
objp = np.zeros((pattern_size[0] * pattern_size[1], 3), np.float32)
objp[:, :2] = np.mgrid[0:pattern_size[0], 0:pattern_size[1]].T.reshape(-1, 2) * 0.2
object_points = [objp] # 3D world coordinates
image_points = [centers] # 2D detected points
image_size = (image.shape[1], image.shape[0]) # (width, height)
ret, camera_matrix, dist_coeffs, _, _ = cv2.calibrateCamera(
object_points, image_points, image_size, None, None
)
print("\n=== 📸 Camera Calibration Results ===")
print("🔹 RMS Reprojection Error:", ret)
print("🔹 Camera Matrix:\n", camera_matrix)
print("🔹 Distortion Coefficients:\n", dist_coeffs)
else:
print("❌ Could not detect circle grid.")
fig, ax = plt.subplots(1, 2, figsize=(14, 6))
ax[0].imshow(cv2.cvtColor(inverted, cv2.COLOR_BGR2RGB))
ax[0].set_title("Original Grayscale")
ax[0].axis("off")
ax[1].imshow(cv2.cvtColor(output, cv2.COLOR_BGR2RGB))
ax[1].set_title("Detected Grid" if found else "Detection Failed")
ax[1].axis("off")
plt.tight_layout()
plt.show()