I am trying to read 3058 images from a folder. I want my picture to be read as np array with size (3158, 480, 640, 3) dtype as uint8. I store all image to a list (image_list). After changing the list to array, I get an array (3158, ). Below is my code
import numpy as np import cv2 as cv DIR = mydir takenFrames = 6 counter = 0 for filename in glob.glob(DIR + '/*.png'): counter += 1 # if counter >= no frames, open image, add img and img_label to list. if (counter >= takenFrames): im = cv.imread(filename) #im.shape is 480, 640 image_list.append(im) #im = np.resize(im, (-1, 490, 640, 3)) image_list = np.array(image_list, dtype='uint8').reshape(-1, 480, 640, 3) / 255.0 Whenever I try to do this, I get the following error as below
image_list = np.array(image_list, dtype='uint8').reshape(-1, 480, 640, 3) / 255.0 Traceback (most recent call last):
File "", line 1, in image_list = np.array(image_list, dtype='uint8').reshape(-1, 480, 640, 3) / 255.0
ValueError: setting an array element with a sequence.
I tried accessing an image from a single folder and the below line of code works x = np.array([np.array(Image.open(file)) for file in filename]) #x.shape = (55, 480, 640, 3)
I tried to store x in an empty numpy array whenever I access a different folder and read the images to get all the 3058 images as
data = np.array([]) #I tried to append numpy array as if(data.size == 0): data = im else: data = np.append(data, im, axis = 0) but that doesn't work either
41 Answer
I just figured this out. Some of the images have different shape that is the reason. I solved it by changing the image shape before appending the list.
import numpy as np import cv2 as cv DIR = mydir takenFrames = 6 counter = 0 for filename in glob.glob(DIR + '/*.png'): counter += 1 # if counter >= no frames, open image, add img and img label to list. if (counter >= takenFrames): im = cv.imread(filename) #some images are of size (480, 640, 3) whereas some are (490, 640, 3). I resized all images to (480, 640, 3) im = np.resize(im, (480, 640, 3)) image_list.append(im) labels.append(label) #converting image_list to numpy array changes my list to (3058, 480, 640, 3) import numpy as np image_list = np.asarray(image_list)