Home > Blockchain >  Adding Images to an array that gives back number of images and dimension of images in Python
Adding Images to an array that gives back number of images and dimension of images in Python

Time:04-20

How can I add these images which I have converted to a (95,95) array into an array that gives me the number of images I have (in my case 10) and the dimensions of those images (95,95)? My desired output would be an array <10,95,95>.

This is my code so far, thank you! code:

import cv2
import os
from matplotlib import pyplot as plt


# https://www.ocr2edit.com/convert-to-txt
x_train = "C:/Users/cuevas26/ae/crater_images_test"
categories = ["crater"]

#for category in categories:
path = x_train
for img in os.listdir(path):
    img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE)
    imgs = cv2.resize(img_array, (95, 95))
    plt.imshow(imgs, cmap="gray")
    plt.show()

    print(type(imgs))
    print(imgs.shape)

CodePudding user response:

We may append the images to a list, and convert the final list into NumPy array using numpy.stack.

  • Start with an empty list:

     images_list = []
    
  • In the loop, after img = cv2.resize, append the resized image to the list:

     images_list.append(img)
    
  • After the end of the loop, convert the list into 3D NumPy array:

     images = np.stack(images_list, axis=0)
    

images.shape is (10, 95, 95).
images.shape[0] is the number of images.
images.shape[1:] is the image dimensions (95, 95).
Use images[i] for accessing the image in index i.


Code sample:

import cv2
import os
from matplotlib import pyplot as plt
import numpy as np


# https://www.ocr2edit.com/convert-to-txt
x_train = "C:/Users/cuevas26/ae/crater_images_test"

images_list = []  # List of images - start with an empty list

# For category in categories:
path = x_train
for img in os.listdir(path):
    img_array = cv2.imread(os.path.join(path, img), cv2.IMREAD_GRAYSCALE)
    img = cv2.resize(img_array, (95, 95))
    images_list.append(img)  # Append the new image into a list

# Convert the list to of 2D arrays into 3D NumPy array (the first index is the index of the image).
# https://stackoverflow.com/questions/27516849/how-to-convert-list-of-numpy-arrays-into-single-numpy-array
images = np.stack(images_list, axis=0)

print(type(images))  # <class 'numpy.ndarray'>
print(images.shape)  # (10, 95, 95)

n_images = images.shape[0]

# Show the images (using cv2.imshow instead of matplotlib)
for i in range(n_images):
    cv2.imshow('img', images[i])
    cv2.waitKey(1000)  # Wait 1 second

cv2.destroyAllWindows()
  • Related