掘金 人工智能 05月14日 16:58
python 检测图片中的小点并标注为绿色
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文介绍了如何使用OpenCV在图像中检测并用绿色标注小点。通过修改`cv2.drawKeypoints`函数的颜色参数,将默认的红色标记改为绿色。文章详细阐述了实现步骤,包括加载图像、灰度转换、图像预处理、斑点检测参数设置、创建检测器、绿色标注以及结果显示与保存。此外,还提供了完整的Python代码示例,并解释了关键修改点,例如颜色参数的修改和标记样式的选择,方便读者理解和应用。

🟢**修改颜色参数:** 通过修改`cv2.drawKeypoints`函数的颜色参数,将小点的颜色从默认的红色`(0, 0, 255)`改为绿色`(0, 255, 0)`。需要注意的是,OpenCV 使用 BGR 格式,而非 RGB。

⚙️**斑点检测参数设置:** 为了准确检测小点,需要调整`cv2.SimpleBlobDetector_Params()`中的参数,例如`minThreshold`、`maxThreshold`、`filterByArea`、`minArea`、`maxArea`、`filterByCircularity`、`minCircularity`、`filterByConvexity`、`minConvexity`、`filterByInertia`和`minInertiaRatio`。这些参数决定了检测器对斑点大小、形状和凸度的敏感程度。

✨**图像预处理:** 在检测之前,对图像进行预处理可以提高检测效果。文章中使用了 CLAHE (Contrast Limited Adaptive Histogram Equalization) 增强图像对比度,并使用高斯模糊去除噪声。

🎨**标记样式选择:** `cv2.drawKeypoints`函数中的`DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS`标志用于绘制带有大小的圆形标记。如果只需要简单的点标记,可以改用`cv2.DRAW_MATCHES_FLAGS_DEFAULT`。

要将检测到的小点标注为绿色,我们需要修改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

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

OpenCV 图像处理 斑点检测 Python
相关文章