簡體   English   中英

使圖像的某個區域的像素為空白或用任何顏色填充該區域

[英]make pixels of certain area of an image blank or fill that area with any color

我以為自己可以做到!

所以,我一直在研究我的一個項目,我需要在圖像中找到一個/多個對象(目前,我正在使用簡單的模板匹配)。

當找到一個對象時,我想刪除該區域的像素並使該區域透明或用任何顏色填充它。

例如,我有這個圖像(我想找到the coke bottle cane ): -

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM