我已经痴迷地阅读了好几天了,但我只学了几个星期的python和openCv,我对这个完全不知所措。
我有一个类函数,可以在"针"周围绘制矩形。在"干草堆"上找到的图像的形象。干草堆是我实时捕获的一个应用程序窗口。
class Search:
def __init__(self, needle_img_path, method=cv.TM_CCOEFF_NORMED):
# set the method used to load the image
self.method = method
# load the needle image
self.needle_img = cv.imread(needle_img_path, cv.IMREAD_UNCHANGED)
# Save the dimensions of the needle image
self.needle_w = self.needle_img.shape[1]
self.needle_h = self.needle_img.shape[0]
这就是我如何将单个图像传递到上面的函数。
# the window to capture
wincap = WindowCapture('X')
# set the needle image
images = x.jpg
# perform the search
search = Search(images)
当我尝试直接传递更多图像images = ("x.jpg","y.jpg")
我得到错误:
self.needle_img = cv.imread(needle_img_path, cv.IMREAD_UNCHANGED)
TypeError: Can't convert object of type 'tuple' to 'str' for 'filename'
当我尝试将图像存储在数组images = [cv.imread(file) for file in glob.glob('localpath')]
时我得到错误:
self.needle_img = cv.imread(needle_img_path, cv.IMREAD_UNCHANGED)
TypeError: Can't convert object of type 'list' to 'str' for 'filename'
当我将print(images)
放置在一个成功加载的图像images = x.jpg
下面时,它返回x.jpg
,所以我认为它期待一个字符串而不是一个数组,但我不确定如何做到这一点。
如果参数作为元组传递,则需要遍历图像路径列表。如果它作为字符串传递,您将希望直接将其传递给imread
调用。
考虑做以下修改:
import cv2 as cv
class Search:
def __init__(self, needle_img_path, method=cv.TM_CCOEFF_NORMED):
# set the method used to load the image
self.method = method
self.needle_imgs = []
# load the needle image
if type(needle_img_path) is str:
self.needle_imgs.append(cv.imread(needle_img_path, cv.IMREAD_UNCHANGED))
elif type(needle_img_path) is list or tuple:
for img in needle_img_path:
self.needle_imgs.append(cv.imread(img, cv.IMREAD_UNCHANGED))
def do_something_with_images(self):
for img in self.needle_imgs:
print(img.shape)
# set the needle image
images = ("C:\Test\x.jpg", "C:\Test\y.jpg")
# perform the search
search = Search(images)
# Do something to each individual image
search.do_something_with_images()