You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将3D图像存入4D数组及批量读取RGB图像构建4D数组

How to Save Multiple 3D Images into a 4D Array in Python

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:

  1. Import the necessary tools

    from PIL import Image
    import numpy as np
    import os
    
  2. Set up your folder path
    Use a raw string (prefix with r) to avoid Windows backslash issues:

    folder_path = r'C:\folder_test'
    
  3. 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"
    
  4. 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.

  1. Import libraries

    import cv2
    import numpy as np
    import os
    
  2. Set 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"
    
  3. 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.listdir doesn't guarantee images are read in sequence (like img_01.jpg to img_45.jpg). If order matters, sort the image_files list with image_files.sort().
  • Shape Checks: The assert statements 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:49:52