如何在Python中将3D图像存入4D数组及批量读取RGB图像构建4D数组
The Problem Recap
需读取笔记本电脑C:\folder_test路径下的256×512尺寸RGB图像,此类图像对应形状为(256,512,3)的3D数组,第三维度代表R、G、B三通道。现要读取45张该类图像,整合为形状为(45,256,512,3)的4D数组,其中第一维度为图像数量,后三维为图像自身维度。
Let's work through this problem step by step using two popular Python toolkits for image and array handling. Both methods will get you the 4D array you need—pick the one that fits your workflow best!
Method 1: Pillow + NumPy
Pillow is super intuitive for basic image operations, and NumPy is the go-to for array stacking. Here's how to put them together:
Import the necessary tools
from PIL import Image import numpy as np import osSet up your folder path
Use a raw string (prefix withr) to avoid Windows backslash issues:folder_path = r'C:\folder_test'Gather all target image files
Filter for common image extensions to avoid reading non-image files:image_files = [f for f in os.listdir(folder_path) if f.lower().endswith(('.png', '.jpg', '.jpeg'))] # Double-check we have exactly 45 images (adjust if your count varies) assert len(image_files) == 45, f"Expected 45 images, found {len(image_files)} instead"Read images and build the 4D array
# Start with an empty list to store each 3D image array image_arrays = [] for img_file in image_files: # Get the full path to the image img_full_path = os.path.join(folder_path, img_file) # Open the image and convert it to a numpy array img = Image.open(img_full_path) img_array = np.array(img) # Make sure the image has the correct dimensions assert img_array.shape == (256, 512, 3), f"Image {img_file} has wrong shape: {img_array.shape}" # Add the 3D array to our list image_arrays.append(img_array) # Stack all 3D arrays into a single 4D array (axis=0 adds the "number of images" dimension) final_4d_array = np.stack(image_arrays, axis=0) # Confirm the final shape is what we want print(f"Final 4D array shape: {final_4d_array.shape}") # Should output (45, 256, 512, 3)
Method 2: OpenCV + NumPy
OpenCV is great if you need more advanced image processing later on, but note it reads images in BGR order by default—we'll convert to RGB to match your requirement.
Import libraries
import cv2 import numpy as np import osSet up folder path and collect images
Same as Method 1:folder_path = r'C:\folder_test' image_files = [f for f in os.listdir(folder_path) if f.lower().endswith(('.png', '.jpg', '.jpeg'))] assert len(image_files) == 45, f"Expected 45 images, found {len(image_files)} instead"Read and process images
image_arrays = [] for img_file in image_files: img_full_path = os.path.join(folder_path, img_file) # Read the image (OpenCV returns BGR format) img_bgr = cv2.imread(img_full_path) # Convert to RGB to match your channel order requirement img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) # Validate the image shape assert img_rgb.shape == (256, 512, 3), f"Image {img_file} has wrong shape: {img_rgb.shape}" image_arrays.append(img_rgb) # Convert the list of 3D arrays to a 4D array final_4d_array = np.array(image_arrays) print(f"Final 4D array shape: {final_4d_array.shape}") # (45, 256, 512, 3)
Quick Tips
- File Order:
os.listdirdoesn't guarantee images are read in sequence (likeimg_01.jpgtoimg_45.jpg). If order matters, sort theimage_fileslist withimage_files.sort(). - Shape Checks: The
assertstatements are optional but helpful for catching mismatched image sizes early—remove them if you're 100% sure all images are the correct dimensions. - Memory: 45 images of 256×512×3 take up ~17MB (as 8-bit integers), so no need to worry about memory constraints here.
内容的提问来源于stack exchange,提问作者mohammad norouzifard

