gpt4 book ai didi

python - 使图像特定区域的像素空白或用任何颜色填充该区域

转载 作者:太空宇宙 更新时间:2023-11-03 15:46:50 25 4
gpt4 key购买 nike

我以为我可以自己做!

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

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

例如,我有这张图片(我想在其中找到可乐瓶手杖):-

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

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

最佳答案

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

关于python - 使图像特定区域的像素空白或用任何颜色填充该区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49527141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com