OpenCV Python 删除图像中的某些对象

OpenCV Python Remove certain objects in an image

我将 python 与 opencv 和 numpy 结合使用,通过围绕星形模板绘制一个矩形来检测天文中的星星,例如这颗 1 images. Using template matching I have got it to detect stars with a threshold (click the 2) 2。我的下一个目标是从根本上“移除”图像中的星星。

为此,我尝试使用不同的方法对图像进行模糊处理,cv2.blur 等,但它并没有产生我想要的效果。我的下一个想法是从星星周围的像素中获取 rgb 数据,将它们取平均,然后用选定的颜色给星星上色。这是最好的选择吗?我该怎么做?

我的代码如下。

import cv2
import numpy as np
import time

start = time.time()
threshold = 0.4
image = cv2.imread('lag.jpg')
imageG = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#cv2.imshow('original', image)
#cv2.imshow('greyscale', imageG)

template = cv2.imread('template.jpg', 0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(imageG,template,cv2.TM_CCOEFF_NORMED)
loc = np.where( res >= threshold)

for pt in zip(*loc[::-1]):
    a = cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (0,0,255), 1)


cv2.imshow('lag.jpg', image)
end = time.time()
final = end - start
print(final)
cv2.waitKey(0)
cv2.destroyAllWindows()

您可以创建一个遮罩,并使用 cv2.inpaint 使用区域边界附近的像素替换所选的“遮罩区域”。

因为你没有 post 'template.jpg',我创建了以下一个:


  • 通过在零图像上绘制填充矩形来构建蒙版:

     mask = np.zeros_like(imageG)
     for pt in zip(*loc[::-1]):
         #a = cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (0,0,255), 1)
         cv2.rectangle(mask, (pt[0]+3, pt[1]+3), (pt[0]+w-3, pt[1]+h-3), 255, -1)  # Reduce the size of the rectangle by 3 pixels from each side.
    

    注意:我使用 cv2.rectangle 来保留您的原始代码,但我认为圆圈可能更适合您的情况。

  • 使用inpaint去除遮罩区域:

     image = cv2.inpaint(image, mask, 2, cv2.INPAINT_NS)
    

    您可以调整参数。


完整代码如下:

import cv2
import numpy as np
import time

start = time.time()
threshold = 0.4
image = cv2.imread('lag.jpg')
imageG = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

#template = cv2.imread('template.jpg', 0)
template = cv2.imread('template.png', 0)
w, h = template.shape[::-1]
res = cv2.matchTemplate(imageG,template,cv2.TM_CCOEFF_NORMED)
loc = np.where( res >= threshold)


mask = np.zeros_like(imageG)
for pt in zip(*loc[::-1]):
    #a = cv2.rectangle(image, pt, (pt[0] + w, pt[1] + h), (0,0,255), 1)
    cv2.rectangle(mask, (pt[0]+3, pt[1]+3), (pt[0]+w-3, pt[1]+h-3), 255, -1)  # Reduce the size of the rectangle by 3 pixels from each side


image = cv2.inpaint(image, mask, 2, cv2.INPAINT_NS)

cv2.imshow('lag.jpg', image)
cv2.imshow('mask', mask)
end = time.time()
final = end - start
print(final)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果:

mask:

image(在inpaint之后):

原图(对比):


您可以使用较少尺寸的矩形(或圆形)改进解决方案 - 使用较大的矩形来覆盖较大的星星。