【问题标题】:How to delete the outer circles in an image without affecting the rest of the image?如何在不影响图像其余部分的情况下删除图像中的外圈?
【发布时间】:2019-11-04 21:57:25
【问题描述】:

我有一张类似于下图的图片。

我想同时删除图像的黑色和红色圆圈,而不影响图像内部的红色方块(因为红色圆圈和红色方块具有相同的像素值)。

我尝试使用cv2.HoughCircles 检测红色圆圈并尝试将其转换为黑色,但红色圆圈的某些部分保持不变,如图所示。

这是我使用的代码。

import numpy as np
import cv2

image = cv2.imread("13-14.png")
output = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.3, 145)

if circles is not None:
    circles = np.round(circles[0, :]).astype("int")

    for (x, y, r) in circles:
        cv2.circle(output, (x, y), r, (0, 0 , 0), 4)

cv2.imshow("output", np.hstack([image, output]))
cv2.waitKey(0)

有什么建议吗?提前致谢。

编辑 1

我正在寻找的示例输出是这种图像(彩色或灰度)。

【问题讨论】:

    标签: python python-3.x opencv image-processing


    【解决方案1】:

    由于正方形似乎“明显”大于圆形的厚度,因此使用一些矩形内核(以保持正方形的形状)的简单形态开口应该在这里起作用。

    这将是我的解决方案:

    import cv2
    from skimage import io          # Only needed for web grabbing images; for local images, use cv2.imread(...)
    
    # Read provided example image
    image = cv2.cvtColor(io.imread('https://i.stack.imgur.com/QfUOF.png'), cv2.COLOR_RGB2BGR)
    
    # Mask non-white content
    _, mask = cv2.threshold(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY), 252, 255, cv2.THRESH_BINARY_INV)
    
    # Apply morphological opening with 5x5 rectangular kernel to get rid of the circles
    mod = cv2.morphologyEx(mask, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)))
    
    # Obtain mask of parts to be erased from the difference of both masks
    erase = mask - mod
    
    # Set corresponding pixels in image to white
    image[erase == 255] = (255, 255, 255)
    
    cv2.imshow('mask', mask)
    cv2.imshow('mod', mod)
    cv2.imshow('erase', erase)
    cv2.imshow('image', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    非白人内容mask如下所示:

    mod打开后修改后的面具是这样的:

    两者的区别是要擦除的部分(erase):

    最后,所有被遮罩的像素都设置为白色:

    希望有帮助!

    【讨论】:

    • @HansHirse 谢谢。这正好解决了我的问题!
    【解决方案2】:

    从左上角填充,先用黑色填充,然后用白色填充,然后用红色填充:

    碰巧的是,我使用 ImageMagick 进行了如下操作,但您可以使用 Python 包进行相同操作:

    magick circles.png \
       -fill black -draw "color 0,0 floodfill" \
       -fill white -draw "color 0,0 floodfill" \
       -fill red   -draw "color 0,0 floodfill" result.png
    

    【讨论】:

    • 以及如何摆脱红色背景,因为它连接到红色方块之一?一开始我也有同样的想法,但遇到了这个问题。
    • @HansHirse 是的,我可能最终也会做一些形态学,以侵蚀红色使其不接触。
    • 您好,@Mark Setchell 谢谢您的回复。能否请您告诉我 python 包到底是什么以及如何安装它(是否有可用的 pip 安装程序)?
    • 你可以使用OpenCV,或者skimage或者Wand,我相信他们都提供"flood fill " 功能。
    猜你喜欢
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多