Aka*_*llu 1 python opencv image-processing python-3.x
我想删除图像的黑色和红色圆圈,而又不影响图像内部的红色方块(因为红色圆圈和红色方块的像素值相同)。
我尝试使用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)
Run Code Online (Sandbox Code Playgroud)
有什么建议么?提前致谢。
编辑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()
Run Code Online (Sandbox Code Playgroud)
非白色内容mask
如下所示:
开口后的修改蒙版mod
如下:
两者的区别是要删除的部分(erase
):
最后,所有遮罩的像素均设置为白色:
希望有帮助!