首页 > 解决方案 > 如何对两个对象使用相同的 OpenCv 函数?

问题描述

我正在尝试对两个对象使用相同的功能。

我可以让事情与单个对象一起工作,但是当我尝试加载两个时它不起作用。我已经转储print(self.needle_img)检查返回的内容,它正在显示none并给我错误,AttributeError: 'NoneType' object has no attribute 'shape'

def __init__(self, needle_img_path, method=cv.TM_CCOEFF_NORMED):

    # Set the method we're using when we load the image 
    self.method = method

    # load the image we're trying to match
    self.needle_img = cv.imread(needle_img_path, cv.IMREAD_UNCHANGED)

    print(self.needle_img)

    # Save the dimensions of the needle image
    self.needle_w = self.needle_img.shape[1]
    self.needle_h = self.needle_img.shape[0]

这就是我尝试传递多个对象的方式:

# set the window to capture object 
wincap = WindowCapture('Application')

# empty array
avoid = []

#fill the empty array with images
avoid_images = glob.glob(r"C:\Users\avoid\avoid*.jpg")

print(avoid_images)

# set the objects I want to find
search = Search('avoid_images')

print(avoid_images)确实正确返回了我期望的图像。

我不确定,但我认为我需要遍历多个图像,然后存储结果略有不同,而不是使用:

self.needle_w = self.needle_img.shape[1]
self.needle_h = self.needle_img.shape[0]

因为那是存储一张图像的尺寸,对吗?

我用谷歌搜索了很多,发现NoneType错误通常是 cv2.imread 或无效文件路径的问题,我确认文件路径是正确的,print(avoid_images)所以我认为问题一定是我如何尝试将这些传递到功能?

标签: pythonopencvimage-processing

解决方案


用户在这篇文章中回答:无法一次将多个图像传递给 OpenCv

@Jon 的解决方案是将字符串直接传递给imread调用,并将一个图像附加到另一个图像中.append

        # 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))

推荐阅读