使图像中特定区域的像素变为空白或填充该区域任意颜色。

4

我以为我可以自己完成这个项目!

因此,我一直在开发自己的项目,需要在图像中找到一个/多个对象(目前,我正在使用简单的模板匹配)。

当找到一个对象时,我想要删除该区域的像素并使其透明或填充任何颜色。

例如,我有这张图片(我想要找到可乐瓶藤):

image_before

运行对象检测脚本后,我得到了:

After_image

您可以看到红色矩形内的匹配对象!

现在,我想做的是删除这个矩形区域并将其变成透明或填充任何颜色!

我已经尝试了很多方法,仍在尝试,但没有成功。这是我到目前为止的进展:

import numpy as np
import argparse
import imutils
import glob
import cv2
from matplotlib import pyplot as plt


ap = argparse.ArgumentParser()
ap.add_argument("-t", "--template", required=True, help="Path to template image")
ap.add_argument("-i", "--images", required=True,
    help="Path to images where template will be matched")
ap.add_argument("-v", "--visualize",
    help="Flag indicating whether or not to visualize each iteration")
args = vars(ap.parse_args())

def match_and_count(template, image):
    img_rgb = cv2.imread(image)
    img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
    template = cv2.imread(template,0)
    w, h = template.shape[::-1]

    res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
    threshold = 0.8
    loc = np.where( res >= threshold)

    f = set()
    sensitivity = 100

    for pt in zip(*loc[::-1]):
        cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
        # I want to make each rectangle transparent here
        f.add((round(pt[0]/sensitivity), round(pt[1]/sensitivity)))

    cv2.imwrite('multiple_objects.jpg',img_rgb)

    print("Occurence of Object: %s" % len(f))

match_and_count(args["template"], args["images"])

如果有人能够给出一个提示或一段代码,实现同样的功能。我将非常感激,谢谢。

如果你的代码不是很好也没关系,只要确保它易于阅读并正确格式化,并向我们展示它,我们都曾经从头开始。 (同时确保只显示重要内容) - Nick stands with Ukraine
1
@NickA添加了代码并在我想放置代码的地方添加了注释! - the.salman.a
1个回答

6
您可以使用numpy切片语法来裁剪框,并将其替换为新的颜色,如下所示:
replacement_color = np.array([20, 125, 89]) # any random color

for pt in zip(*loc[::-1]):
     # cv2.rectangle(...)
     img[pt[1]:pt[1] + h, pt[0]:pt[0]+w] = replacement_color

或者,您也可以使用cv2.rectangle API来获得与以下代码相同的结果:

replacement_color = np.array([20, 125, 89]) # any random color

for pt in zip(*loc[::-1]):
     cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), replacement_color, -1)

你只需要将line_width参数设为-1即可。

我添加了一些代码,您能检查并让我知道我应该做什么吗? - the.salman.a

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接