1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| import cv2 import numpy as np
def calculate_centroid(image_path, threshold=128): """ 使用一阶矩计算光斑质心 参数: image_path: 输入图像路径 threshold: 降噪阈值Q,默认为128 返回: centroid_x, centroid_y: 质心坐标 processed_image: 处理后的图像 """ image = cv2.imread(image_path) if image is None: raise ValueError("无法读取图像,请检查图像路径")
height, width = image.shape[:2] print(f"图像分辨率: {width} x {height}")
b, g, r = cv2.split(image.astype(np.float32))
gray_image = 0.3 * r + 0.59 * g + 0.11 * b gray_image = gray_image.astype(np.uint8)
mask = gray_image > threshold processed_image = np.zeros_like(gray_image, dtype=np.float32) processed_image[mask] = gray_image[mask]
x_coords, y_coords = np.meshgrid(np.arange(width), np.arange(height))
sum_intensity = np.sum(processed_image)
if sum_intensity == 0: raise ValueError("没有找到足够亮的光斑,请调整阈值")
centroid_x = np.sum(x_coords * processed_image) / sum_intensity centroid_y = np.sum(y_coords * processed_image) / sum_intensity
return centroid_x, centroid_y, processed_image.astype(np.uint8)
def visualize_results(original_image, processed_image, centroid_x, centroid_y): """ 可视化处理结果 """ result_image = original_image.copy() center = (int(centroid_x), int(centroid_y))
cv2.circle(result_image, center, 5, (0, 0, 255), -1) cv2.circle(result_image, center, 10, (0, 0, 255), 2) cv2.putText(result_image, f'Centroid: ({centroid_x:.2f}, {centroid_y:.2f})', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
cv2.imshow('Original Image', original_image) cv2.imshow('Processed Image', processed_image) cv2.imshow('Result with Centroid', result_image)
print(f"质心坐标: ({centroid_x:.2f}, {centroid_y:.2f})")
cv2.waitKey(0) cv2.destroyAllWindows()
return result_image
if __name__ == "__main__": image_path = "gaussian_spot.png"
threshold_input = input("请输入阈值 (默认128,直接回车使用默认值): ").strip() if threshold_input: try: threshold = int(threshold_input) except ValueError: print("输入阈值无效,使用默认值128") threshold = 128 else: threshold = 128
try: original_image = cv2.imread(image_path) if original_image is None: raise ValueError(f"无法读取图像: {image_path}")
centroid_x, centroid_y, processed_image = calculate_centroid(image_path, threshold=threshold)
result_image = visualize_results(original_image, processed_image, centroid_x, centroid_y)
save_choice = input("是否保存结果图像? (y/n): ").strip().lower() if save_choice == 'y' or save_choice == 'yes': output_path = "Centriod_result.png" cv2.imwrite(output_path, result_image) print(f"结果图像已保存为: {output_path}")
except Exception as e: print(f"处理过程中出现错误: {e}")
|