【问题标题】:How to convert images in directory to np array如何将目录中的图像转换为 np 数组
【发布时间】:2020-05-11 05:41:07
【问题描述】:

我有图片存储在目录中:

from pathlib import Path
from PIL import Image
import os, shutil
from os import listdir
## Image Resizing
from PIL import Image

# load and display an image with Matplotlib
from matplotlib import image
from matplotlib import pyplot


# Image folder
images_dir = Path('C:\\Users\\HP\\Desktop\\XXXXXXXXXXXXXXXXX\\images').expanduser()
images_dir

dim = (400, 300)

# Resizing all the images to same dimension
X_image_train = []
for fname in listdir(images_dir):
    fpath = os.path.join(images_dir, fname)
    im = Image.open(fpath)
    im_resized = im.resize(dim)
    X_image_train.append(im_resized)

## Converting the image to numpy array
X_image_array=[]
for x in range(len(X_image_train)):
    X_image=np.array(X_image_train[x],dtype='uint8')
    X_image_array.append(X_image)

# Checking the size of a single image
X_image_array[0].shape
> (300, 400, 3)

 # Checking the size of a single image
    X_image_array[15].shape
    > (300, 400, 3)

我想将 'X_image_array' 转换为具有以下暗淡的张量:

(2000,300, 400, 3)

其中 2000 是“图像”文件夹中的样本数。

这里需要帮助吗?

【问题讨论】:

    标签: python image-processing image-resizing numpy-ndarray


    【解决方案1】:

    你可以使用np.stack()函数

    np.stack(X_image_array) 
    

    【讨论】:

    • 不工作,出现这个错误:ValueError: all the input array must have the same number of dimensions
    • 因此您的图像具有不同的形状。为什么要在 numpy 数组中包含不同形状的图像?
    • 我正在使用 im_resized = im.resize(dim) 将它们调整为 (400,300) 以使它们具有相同的形状。很困惑为什么我会收到这个错误。
    • 为了检查是否有未正确调整大小的图像,我在循环中添加了assert X_image.shape == (300,400,3), "img %s has shape %r" % (fname, X_image.shape)。我得到了错误:AssertionError: img 653142_Katabatik_Fisherman.jpg has shape (300, 400).... 有没有办法将所有图像强制为 (300,400,3) 形状,因为上面的代码没有正确调整它的大小。
    • 可能是灰色图像。检查
    猜你喜欢
    • 2018-08-28
    • 2020-10-18
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 2021-04-22
    相关资源
    最近更新 更多