gpt4 book ai didi

python - Image in Image with cvMatchTemplate - 但是怎么做呢?

转载 作者:太空狗 更新时间:2023-10-29 21:27:00 26 4
gpt4 key购买 nike

我想找出某个子图像出现在源图像的哪个位置(例如源图像:http://i.pictr.com/6xg895m69q.png,子图像:http://i.pictr.com/jdaz9zwzej.png)。据我所知,有必要转换数组以使它们对 OpenCV “可读”,这是我尝试过的方法,但由于某种原因,它不起作用。到目前为止,这是我的代码:

 from PIL import Image
import numpy
from pylab import *
import cv2
import cv

image = cv2.imread('source_img.jpg')
template = cv2.imread('template_img.jpg')

im = cv.fromarray(image)
templ = cv.fromarray(template)
result = numpy.zeros(shape=(1,10)) ##create a matrix with 0s
a = cv.fromarray(result)
cv.MatchTemplate(im, templ, a, cv.CV_TM_CCORR)
print result
print image

我的目标是将子图像的坐标写入结果数组(数组的其余部分应保持值 0(我知道我的代码到目前为止不会这样做)。这是错误消息,我执行代码时得到:

OpenCV Error: Assertion failed (result.size() == cv::Size(std::abs(img.cols - templ.cols) + 1, std::abs(img.rows - templ.rows) + 1) && result.type() == CV_32F) in cvMatchTemplate, file /opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_graphics_opencv/opencv/work/OpenCV-2.4.3/modules/imgproc/src/templmatch.cpp, line 376 Traceback (most recent call last): File "/Users/strongbow/imagerecognition.py", line 27, in cv.MatchTemplate(im, templ, a, cv.CV_TM_CCORR) cv2.error: result.size() == cv::Size(std::abs(img.cols - templ.cols) + 1, std::abs(img.rows - templ.rows) + 1) && result.type() == CV_32F

我是 OpenCV 的新手,真的不知道如何处理这个错误消息。有没有人知道该怎么做?

最佳答案

import sys
import cv2
import numpy

img = cv2.imread(sys.argv[1])
template = cv2.imread(sys.argv[2])
th, tw = template.shape[:2]

result = cv2.matchTemplate(img, template, cv2.TM_CCORR_NORMED)
threshold = 0.99
loc = numpy.where(result >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img, pt, (pt[0] + tw, pt[1] + th), 0, 2)

cv2.imwrite(sys.argv[3], img)

enter image description here

关于python - Image in Image with cvMatchTemplate - 但是怎么做呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14486353/

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