将图像添加到数组,返回 Python 中的图像数量和图像尺寸

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

如何将我已转换为 (95,95) 数组的这些图像添加到一个数组中,该数组给出了我拥有的图像数量(在我的例子中为 10)和这些图像的尺寸(95, 95)? 我想要的输出是一个数组 <10,95,95>.

到目前为止,这是我的代码,谢谢! 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)

我们可以将图像附加到列表中,并使用 numpy.stack.

将最终列表转换为 NumPy 数组
  • 从一个空列表开始:

     images_list = []
    
  • 在循环中,在 img = cv2.resize 之后,将调整后的图像追加到列表中:

     images_list.append(img)
    
  • 循环结束后,将列表转换为3D NumPy数组:

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

images.shape(10, 95, 95).
images.shape[0]是图片的数量。
images.shape[1:] 是图像尺寸 (95, 95).
使用 images[i] 访问索引 i.

中的图像

代码示例:

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).
# 
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()