I've been reading fairly obsessively for days now, but I'm only a few weeks into learning python and openCv and I'm at a total loss with this.
I have a class function that draws rectangles around a "needle" image found on a "haystack" image. The haystack is an application window I'm capturing in real-time.
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]
This is how I'm passing a single image into the above function.
# the window to capture
wincap = WindowCapture('X')
# set the needle image
images = x.jpg
# perform the search
search = Search(images)
When I try passing more images in directly images = ("x.jpg","y.jpg")
I get the error:
self.needle_img = cv.imread(needle_img_path, cv.IMREAD_UNCHANGED)
TypeError: Can't convert object of type 'tuple' to 'str' for 'filename'
And when I try storing the the images in an array images = [cv.imread(file) for file in glob.glob('localpath')]
I get the error:
self.needle_img = cv.imread(needle_img_path, cv.IMREAD_UNCHANGED)
TypeError: Can't convert object of type 'list' to 'str' for 'filename'
When I place print(images)
below a single successfully loaded image images = x.jpg
it returns x.jpg
so I think it's expecting a string and not an array but I'm not sure how to do that.
If your argument is passed as a tuple, you'll need to iterate over the list of image paths. If it's passed as a string, you'll want to pass that directly to the imread
call.
Consider making the following modification:
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.