視場角定相機內參
import numpy as np
import cv2
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3Ddef calculate_camera_intrinsics(image_width=640, image_height=480, fov=55, is_horizontal=True):"""計算相機內參矩陣參數:image_width: 圖像寬度(像素)image_height: 圖像高度(像素)fov: 視野角(度)is_horizontal: 是否為水平視野角返回:K: 相機內參矩陣focal_length: 焦距(像素)"""# 將FOV從度轉換為弧度fov_rad = np.radians(fov)# 計算焦距if is_horizontal:focal_length = (image_width / 2) / np.tan(fov_rad / 2)else:focal_length = (image_height / 2) / np.tan(fov_rad / 2)# 主點(通常位于圖像中心)cx = image_width / 2cy = image_height / 2# 構建相機內參矩陣K = np.array([[focal_length, 0, cx], [0, focal_length, cy], [0, 0, 1]], dtype=np.float32)return K, focal_lengthdef visualize_camera_model(K, image_size, title="相機模型可視化"):"""可視化相機模型和視野"""fig = plt.figure(figsize=(10, 8))ax = fig.add_subplot(111, projection='3d')# 相機位置camera_pos = np.array([0, 0, 0])# 圖像平面尺寸width, height = image_size# 焦距fx = K[0, 0]fy = K[1, 1]cx = K[0, 2]cy = K[1, 2]# 假設圖像平面在z=f處z = fx# 計算圖像平面四個角點的3D坐標top_left = np.array([(0 - cx) * z / fx, (0 - cy) * z / fy, z])top_right = np.array([(width - cx) * z / fx, (0 - cy) * z / fy, z])bottom_left = np.array([(0 - cx) * z / fx, (height - cy) * z / fy, z])bottom_right = np.array([(width - cx) * z / fx, (height - cy) * z / fy, z])# 繪制相機位置ax.scatter(camera_pos[0], camera_pos[1], camera_pos[2], c='r', marker='o', s=100, label='相機位置')# 繪制從相機到圖像平面四角的視線for corner in [top_left, top_right, bottom_left, bottom_right]:ax.plot([camera_pos[0], corner[0]], [camera_pos[1], corner[1]], [camera_pos[2], corner[2]], 'b-', alpha=0.5)# 繪制圖像平面x = np.array([top_left[0], top_right[0], bottom_right[0], bottom_left[0], top_left[0]])y = np.array([top_left[1], top_right[1], bottom_right[1], bottom_left[1], top_left[1]])z = np.array([top_left[2], top_right[2], bottom_right[2], bottom_left[2], top_left[2]])ax.plot(x, y, z, 'g-', alpha=0.8)# 設置坐標軸范圍max_range = max(width, height, fx) * 0.5ax.set_xlim([-max_range, max_range])ax.set_ylim([-max_range, max_range])ax.set_zlim([0, max_range * 2])# 設置坐標軸標簽ax.set_xlabel('X軸')ax.set_ylabel('Y軸')ax.set_zlabel('Z軸')# 設置視角ax.view_init(elev=20, azim=30)# 添加標題和圖例ax.set_title(title)ax.legend()plt.tight_layout()plt.show()def visualize_camera_model_opencv(K, image_size, title="相機模型可視化"):"""使用OpenCV可視化相機模型和視野"""# 創建空白圖像width, height = image_sizecanvas = np.ones((height, width, 3), dtype=np.uint8) * 255# 焦距和主點fx = K[0, 0]fy = K[1, 1]cx = K[0, 2]cy = K[1, 2]# 相機位置(圖像中心)camera_center = (int(cx), int(cy))# 計算視野邊界點fov_scale = min(width, height) * 0.4 # 視野顯示比例# 計算四個方向的視野邊界點points = [(int(cx), int(cy - fov_scale)), # 上(int(cx + fov_scale), int(cy)), # 右(int(cx), int(cy + fov_scale)), # 下(int(cx - fov_scale), int(cy)), # 左]# 繪制視野范圍(矩形)cv2.rectangle(canvas, (points[3][0], points[0][1]), (points[1][0], points[2][1]), (0, 255, 0), 2)# 繪制主點cv2.circle(canvas, camera_center, 5, (0, 0, 255), -1)cv2.putText(canvas, "主點", (camera_center[0] + 10, camera_center[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)# 繪制坐標軸axis_length = 100cv2.arrowedLine(canvas, camera_center, (camera_center[0] + axis_length, camera_center[1]), (255, 0, 0), 2) # X軸(藍色)cv2.arrowedLine(canvas, camera_center, (camera_center[0], camera_center[1] + axis_length), (0, 0, 255), 2) # Y軸(紅色)# 添加焦距信息cv2.putText(canvas, f"fx: {fx:.2f}", (20, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2)cv2.putText(canvas, f"fy: {fy:.2f}", (20, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2)# 添加標題cv2.putText(canvas, title, (20, height - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2)# 顯示圖像cv2.imshow(title, canvas)cv2.waitKey(0)cv2.destroyAllWindows()
def main():# 圖像尺寸image_width = 640image_height = 480# FOV(度)fov = 55# 計算相機內參(假設為水平FOV)K, focal_length = calculate_camera_intrinsics(image_width=image_width, image_height=image_height, fov=fov, is_horizontal=True)# 打印結果print(f"圖像尺寸: {image_width}x{image_height} 像素")print(f"視野角(FOV): {fov} 度")print(f"焦距: {focal_length:.2f} 像素")print("\n相機內參矩陣:")print(K)# 可視化相機模型visualize_camera_model(K, (image_width, image_height))# visualize_camera_model_opencv(K, (image_width, image_height), title="相機模型可視化")# 如果是垂直FOV,也可以計算K_vertical, _ = calculate_camera_intrinsics(image_width=image_width, image_height=image_height, fov=fov, is_horizontal=False)print("\n如果這是垂直FOV,相機內參矩陣為:")print(K_vertical)if __name__ == "__main__":main()
?