How do I use the same OpenCv function with two objects?

I’m trying to use the same function with two objects.

I can get things to work with a single object but when I try and load in two it doesn’t work. I’ve dumped print(self.needle_img) to check what’s being returned and it’s showing none and giving me the error, 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]

And this is how I’ve tried to pass the multiple objects in:

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

# empty array
avoid = []

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

print(avoid_images)

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

print(avoid_images) does correctly return the images I’d expect.

I’m not sure but I think I need to loop through multiple images and then store the results slightly differently rather than using:

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

Because that’s storing the dimensions of one image right?

I’ve googled quite a bit and found out that NoneType errors are generally issues with cv2.imread or invalid file paths, I confirmed the file paths were correct with print(avoid_images) so the issue must be I think with how I’m trying to pass those into the function?

Answer

Answered by user in this post: Unable to pass multiple images to OpenCv at once

The solution from @Jon was passing the string directly to the imread call and appending one image into the other with .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))

Leave a Reply

Your email address will not be published. Required fields are marked *