gpt4 book ai didi

python - Python OpenCV用于模板匹配

转载 作者:行者123 更新时间:2023-12-02 17:21:37 26 4
gpt4 key购买 nike

我有一个使用openCV的小python脚本,该脚本在图像中进行模板匹配,并很好地返回一个边界框,如下所示。该脚本的大小也不变,这使其更强大。

给定返回的边界框,如何用其他模板将替换为并保存更改后的图像?

这是original templatemain image

enter image description here

现在,我想简单地将精确的框替换为下面调整后的版本的template2,然后保存新图像。我怎样才能做到这一点?

enter image description here

这是我的简单代码:

# USAGE
# python match.py --template cod_logo.png --images images

# import the necessary packages
import numpy as np
import argparse
import imutils
import glob
import cv2

# construct the argument parser and parse the arguments
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 dir where template will be matched")
ap.add_argument("-v", "--visualize",
help="Flag 0 or 1 indicating whether or not to visualize each iteration")
args = vars(ap.parse_args())

# load the image image, convert it to grayscale, and detect edges
template = cv2.imread(args["template"])
template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
template = cv2.Canny(template, 50, 200)
(tH, tW) = template.shape[:2]
cv2.imshow("Template", template)

# loop over the images to find the template in
for imagePath in glob.glob(args["images"] + "/*.*"):
# load the image, convert it to grayscale, and initialize the
# bookkeeping variable to keep track of the matched region
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
found = None

# loop over the scales of the image
for scale in np.linspace(0.2, 1.0, 20)[::-1]:
# resize the image according to the scale, and keep track
# of the ratio of the resizing
resized = imutils.resize(gray, width = int(gray.shape[1] * scale))
r = gray.shape[1] / float(resized.shape[1])

# if the resized image is smaller than the template, then break
# from the loop
if resized.shape[0] < tH or resized.shape[1] < tW:
break

# detect edges in the resized, grayscale image and apply template
# matching to find the template in the image
edged = cv2.Canny(resized, 50, 200)
result = cv2.matchTemplate(edged, template, cv2.TM_CCOEFF)
(_, maxVal, _, maxLoc) = cv2.minMaxLoc(result)

# check to see if the iteration should be visualized
if args.get("visualize", False):
# draw a bounding box around the detected region
clone = np.dstack([edged, edged, edged])
cv2.rectangle(clone, (maxLoc[0], maxLoc[1]),
(maxLoc[0] + tW, maxLoc[1] + tH), (0, 0, 255), 2)
cv2.imshow("Visualize", clone)
cv2.waitKey(0)

# if we have found a new maximum correlation value, then ipdate
# the bookkeeping variable
if found is None or maxVal > found[0]:
found = (maxVal, maxLoc, r)

# unpack the bookkeeping varaible and compute the (x, y) coordinates
# of the bounding box based on the resized ratio
(_, maxLoc, r) = found
(startX, startY) = (int(maxLoc[0] * r), int(maxLoc[1] * r))
(endX, endY) = (int((maxLoc[0] + tW) * r), int((maxLoc[1] + tH) * r))

# draw a bounding box around the detected result and display the image
cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 255), 2)
cv2.imshow("Image", image)
cv2.waitKey(0)

最佳答案

我做了一些改变...
1]我没有使用参数解析器
2] tepmlate2是反恐精英。
3] Image2是反击在COD顶部的图像。

STEPS : Extracting roi (region of interest) , then resizing the newimage accordingly ... , then operlapping roi with new resized image,placing roi back on the image2.

Advantage => you can change the opacity of the roi and template bychanging alpha and beta in addWeighted.

# USAGE
# python match.py --template cod_logo.png --images images

# import the necessary packages
import numpy as np
import argparse
import imutils
import glob
import cv2

#New template
template2 = cv2.imread("template2.png")

# construct the argument parser and parse the arguments
# 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 dir where template will be matched")
# ap.add_argument("-v", "--visualize",
# help="Flag 0 or 1 indicating whether or not to visualize each iteration")
# args = vars(ap.parse_args())

# load the image image, convert it to grayscale, and detect edges
template = cv2.imread("template.png")
template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
template = cv2.Canny(template, 50, 200)
(tH, tW) = template.shape\[:2\]
cv2.imshow("Template", template)

# loop over the images to find the template in
#for imagePath in glob.glob(args\["images"\] + "/*.*"):
# load the image, convert it to grayscale, and initialize the
# bookkeeping variable to keep track of the matched region
image = cv2.imread("mainImage.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
found = None

# loop over the scales of the image
for scale in np.linspace(0.2, 1.0, 20)\[::-1\]:
# resize the image according to the scale, and keep track
# of the ratio of the resizing
resized = imutils.resize(gray, width = int(gray.shape\[1\] * scale))
r = gray.shape\[1\] / float(resized.shape\[1\])

# if the resized image is smaller than the template, then break
# from the loop
if resized.shape\[0\] < tH or resized.shape\[1\] < tW:
break

# detect edges in the resized, grayscale image and apply template
# matching to find the template in the image
edged = cv2.Canny(resized, 50, 200)
result = cv2.matchTemplate(edged, template, cv2.TM_CCOEFF)
(_, maxVal, _, maxLoc) = cv2.minMaxLoc(result)

# check to see if the iteration should be visualized
'''
if args.get("visualize", False):
# draw a bounding box around the detected region
clone = np.dstack(\[edged, edged, edged\])
cv2.rectangle(clone, (maxLoc\[0\], maxLoc\[1\]),
(maxLoc\[0\] + tW, maxLoc\[1\] + tH), (0, 0, 255), 2)
cv2.imshow("Visualize", clone)
cv2.waitKey(0)'''

# if we have found a new maximum correlation value, then ipdate
# the bookkeeping variable
if found is None or maxVal > found\[0\]:
found = (maxVal, maxLoc, r)

# unpack the bookkeeping varaible and compute the (x, y) coordinates
# of the bounding box based on the resized ratio
(_, maxLoc, r) = found
(startX, startY) = (int(maxLoc\[0\] * r), int(maxLoc\[1\] * r))
(endX, endY) = (int((maxLoc\[0\] + tW) * r), int((maxLoc\[1\] + tH) * r))

#MY CODE
image2 = image.copy()
resizedTemplate = cv2.resize(template2, (endX-startX, endY-startY), interpolation = cv2.INTER_AREA)
roi = image2[startY:endY, startX:endX]
img = cv2.addWeighted(resizedTemplate, 1, roi, 0, 0)
image2[startY:endY, startX:endX] = img


# draw a bounding box around the detected result and display the image
cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 128), 2)
cv2.imshow("Image", image)
cv2.imshow("Image2", image2)
#cv2.imshow("resizedTemplate", resizedTemplate)
cv2.waitKey(0)
results

关于python - Python OpenCV用于模板匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61980609/

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