多张图片读入后组成一个矩阵。怎么读取图片,可以让其读入的形式是:ndarray(a,b,c)分别的含义:a为多少张图片,b*c为图片大小

  • 不显示通道数:

    要将多张图片读取为一个 NumPy 数组(ndarray),其中 a 表示图片数量,bc 分别表示每张图片的高度和宽度(不显示通道数),你可以使用 Python 中的 PIL(Pillow)库和 NumPy 库。下面是一个示例代码,展示了如何实现这一点:

    代码示例

import numpy as np

from PIL import Image

import os

def load_images_from_folder(folder):

images = []

for filename in os.listdir(folder):

img_path = os.path.join(folder, filename)

img = Image.open(img_path).convert('L') # 转为灰度图像,只有一个通道

images.append(np.array(img))

如果你想保持所有图片的尺寸一致,可以在这里对它们进行裁剪或缩放

例如:

img = img.resize((desired_width, desired_height))

return np.array(images)

指定图片所在的文件夹路径

folder_path = 'path/to/your/images/'

image_array = load_images_from_folder(folder_path)

print(image_array.shape) # 输出.shape 应该是 (a, b, c)

说明

  1. 导入库 :你需要确保已经安装了 PillowNumPy 库,可以使用以下命令安装:

  2. pip install Pillow numpy

  3. 图片读取

    • os.listdir(folder) 列出文件夹中的所有文件名。
    • Image.open(img_path).convert('L') 读取每张图片并将其转换为灰度图像(单通道)。
    • np.array(img) 将图片转换为 NumPy 数组。
  4. 返回结果 :所有图片以数组形式返回,并且形状为 (a, b, c),其中 a 是图片数量,bc 是图片的高度和宽度。

  5. 调整图片大小:如果图片尺寸不一,可以在读取时添加尺寸调整的代码,以确保所有图片的形状一致。

  • 显示通道数:

    要将多张图片读取为一个 NumPy ndarray,并且使其形状为 (a, b, c),其中 a 是图片的数量,bc 是每张图片的尺寸(高度和宽度),你可以使用 OpenCVPIL 库来读取图片,并将它们转换成 ndarray。

    下面是使用这两个库的例子:

    使用 OpenCV

import cv2

import numpy as np

import os

读取图片函数

def load_images_from_folder(folder):

images = []

for filename in os.listdir(folder):

img = cv2.imread(os.path.join(folder, filename))

if img is not None:

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 将 BGR 转换为 RGB

images.append(img)

return np.array(images)

使用示例

folder_path = 'path/to/your/images'

images_array = load_images_from_folder(folder_path)

print(images_array.shape) # 输出形状: (数量, 高度, 宽度, 通道数)

使用 PIL

from PIL import Image

import numpy as np

import os

读取图片函数

def load_images_from_folder(folder):

images = []

for filename in os.listdir(folder):

img = Image.open(os.path.join(folder, filename))

img = img.convert('RGB') # 转换为 RGB 模式

images.append(np.array(img))

return np.array(images)

使用示例

folder_path = 'path/to/your/images'

images_array = load_images_from_folder(folder_path)

print(images_array.shape) # 输出形状: (数量, 高度, 宽度, 通道数)

注意事项

  • 如果你希望输出的 ndarray 形状为 (a, b, c),你需要对最后的输出进行调整,通常你可以选择丢弃通道信息,形状可能转为 (a, b, c, 3),表示 RGB 通道。
  • 确保所有的图片都是同样的尺寸(高、宽),否则最终的 ndarray 会因为尺寸不一致而无法正确创建。
相关推荐
太妃糖耶9 小时前
URP-利用矩阵在Shader中实现物体的平移和缩放
unity·矩阵
优美的赫蒂1 天前
理解欧拉公式
线性代数·算法·数学建模
岩中竹1 天前
力扣热题100题解(c++)—矩阵
数据结构·c++·程序人生·算法·leetcode·矩阵
byxdaz1 天前
矩阵运算和线性代数操作开源库
矩阵
User_芊芊君子1 天前
【C语言经典算法实战】:从“移动距离”问题看矩阵坐标计算
c语言·算法·矩阵
weixin_428498491 天前
使用HYPRE库并行装配IJ稀疏矩阵
线性代数·矩阵
THe CHallEnge of THe BrAve2 天前
工业相机中CCM使能参数-色彩校正矩阵
数码相机·线性代数·矩阵
小美爱刷题2 天前
力扣DAY63-67 | 热100 | 二分:搜索插入位置、搜索二维矩阵、排序数组查找元素、搜索旋转排序数组、搜索最小值
算法·leetcode·矩阵
NorthFish北海有鱼2 天前
python三维矩阵的维度
python·矩阵·numpy
该怎么办呢3 天前
webgl入门实例-11模型矩阵 (Model Matrix)基本概念
线性代数·矩阵·webgl