Concatenating images in a channel dimension from a for loop

Question:

I have a path file with 13 different images (.tiff format) and I want to concatenate all of them into an array of (13, 224, 224). I am getting the shape for all the 13 values but I still struggling to get them into the desired array. Is there a way to concatenate them from the for loop?

imgs = os.listdir(path)  #images list .tif
imgs.remove('metadata.json')

for i in imgs:
   image = cv2.imread(os.path.join(path, i))
   #print(image.shape)   # (h, w, 3)
   image = image[:, :, 0]
   #print(image.shape)  # (h, w)
   width = 224
   height = 224
   dimensions = (width, height)
   image = cv2.resize(image, dimensions,
                     interpolation=cv2.INTER_AREA)  # specifying the scaling factor, using INTER_AREA for shrinking
   min_value = np.min(image)  # min value: 720
   max_value = np.max(image)  # max value: 2564
   #image = ((image - min_value) / (max_value - min_value)) * 255
   image = np.uint8(image)
   image = np.expand_dims(image, axis=0)
   #image = np.concatenate(image, axis=0)

   print(image.shape)   #(1, 224, 224) for 13 images
Asked By: hugo

||

Answers:

Your problem is that you are overwriting the contents of image inside your loop. One way to solve this is to build a list of the images and then convert that to an array after the loop:

images = []
for i in imgs:
   image = cv2.imread(os.path.join(path, i))
   #
   # ...
   #
   image = np.uint8(image)
   # note, don't use `expand_dims` here
   images.append(image)

images = np.array(images)
Answered By: Nick