【问题标题】:make pixels of certain area of an image blank or fill that area with any color使图像的某些区域的像素为空白或用任何颜色填充该区域
【发布时间】:2018-09-06 16:53:47
【问题描述】:

我以为我可以自己做!

所以,我一直在做我的一个项目,我需要在图像中找到一个/多个对象(目前,我正在使用简单的模板匹配)。

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

例如,我有这张图片(我想在其中找到the coke bottle cane):-

运行对象检测脚本后,我有:-

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

现在,我要做的是移除这个矩形区域,使其透明或填充任何颜色!

我尝试了很多东西,仍在尝试但没有运气。到目前为止,这是我所拥有的:

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"])

如果有人可以给出提示或一段代码,那也是一样的。我会很高兴的,谢谢。

【问题讨论】:

  • 如果您没有好的代码也没关系,只要确保它可读且正确格式并显示给我们,我们都必须从某个地方开始。 (还要确保只显示重要的内容)
  • @NickA 添加了代码和我想要放置代码的注释!

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


【解决方案1】:

您可以使用 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 传递。

【讨论】:

  • 我添加了一些代码,你能检查一下并告诉我该怎么做吗?
猜你喜欢
  • 2018-06-06
  • 1970-01-01
  • 1970-01-01
  • 2012-02-06
  • 2016-10-01
  • 1970-01-01
  • 2016-05-12
  • 2011-04-24
相关资源
最近更新 更多