要将检测到的小点标注为绿色,我们需要修改cv2.drawKeypoints
函数的颜色参数。以下是完整的代码修改方案:
修改后的代码实现
python复制import cv2 import numpy as np from matplotlib import pyplot as plt def extract_dots_green(image_path, min_dot_size=2, max_dot_size=10, output_path=None): """ 提取图像中的小点并用绿色标注 参数: image_path: 输入图像路径 min_dot_size: 最小点直径(像素) max_dot_size: 最大点直径(像素) output_path: 输出图像路径(可选) 返回: 包含绿色标记小点的图像 """ # 1. 加载图像 img = cv2.imread(image_path) if img is None: raise ValueError("无法加载图像,请检查路径") # 2. 转换为灰度图 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 3. 图像预处理 clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) enhanced = clahe.apply(gray) blurred = cv2.GaussianBlur(enhanced, (5, 5), 0) # 4. 设置斑点检测参数 params = cv2.SimpleBlobDetector_Params() # 调整这些参数以获得最佳效果 params.minThreshold = 50 params.maxThreshold = 200 params.filterByArea = True params.minArea = np.pi * (min_dot_size/2)**2 params.maxArea = np.pi * (max_dot_size/2)**2 params.filterByCircularity = True params.minCircularity = 0.7 params.filterByConvexity = True params.minConvexity = 0.8 params.filterByInertia = True params.minInertiaRatio = 0.5 # 5. 创建检测器并检测小点 detector = cv2.SimpleBlobDetector_create(params) keypoints = detector.detect(blurred) # 6. 用绿色标注小点 - 修改在这里! # (0,255,0)是绿色的BGR值 img_with_green_dots = cv2.drawKeypoints(img, keypoints, np.array([]), (0, 255, 0), # 绿色 cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # 7. 显示结果 plt.figure(figsize=(12, 6)) plt.subplot(121), plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.title(' 原始图像'), plt.xticks([]), plt.yticks([]) plt.subplot(122), plt.imshow(cv2.cvtColor(img_with_green_dots, cv2.COLOR_BGR2RGB)) plt.title(' 绿色标注的小点'), plt.xticks([]), plt.yticks([]) plt.tight_layout() plt.show() # 8. 保存结果 if output_path: cv2.imwrite(output_path, img_with_green_dots) return img_with_green_dots # 使用示例 if __name__ == "__main__": input_image = "document_with_dots.jpg" output_image = "green_dots_detected.png" # 调整这些参数以获得最佳效果 min_dot_size = 2 # 最小点直径(像素) max_dot_size = 10 # 最大点直径(像素) result_image = extract_dots_green(input_image, min_dot_size, max_dot_size, output_image) print(f"处理完成,结果已保存到 {output_image}")
关键修改点说明
颜色参数修改:
python复制# 原代码使用红色(0,0,255)cv2.drawKeypoints(..., (0, 0, 255), ...)# 修改为绿色(0,255,0)cv2.drawKeypoints(..., (0, 255, 0), ...)
- OpenCV使用BGR格式而非RGB,所以绿色是(0,255,0)
标记样式保留:
- 保留了
DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS
标志,这会绘制带有大小的圆形标记如果只需要简单点标记,可以改用cv2.DRAW_MATCHES_FLAGS_DEFAULT