How to Read Images for Machine Learning Models?

image proc
Title: AI Vision
Source: Tredence website

In computer vision and machine learning, the journey from a stored image file to a tensor ready for neural network training involves several critical steps. Understanding how to read, process, and prepare images is fundamental to building effective machine learning models.

  • Master reading grayscale and colored images with various libraries
  • Explore downsampling, upsampling, and colored-to-grayscale conversion techniques
  • Understand how to visualize image vectors and manipulate arrays
  • Learn preprocessing techniques including normalization, reshaping, and data augmentation
  • Implement proper train/test/validation splits for robust model evaluation

By the end of this article, you’ll understand the complete pipeline from reading raw images to preparing them for state-of-the-art models like ResNet, VGG, and other pretrained architectures.

Introduction: Images in Machine Learning

Images serve as the primary input for Computer Vision algorithms and must be read, decoded, and preprocessed according to their file type to fit the specific requirements of the models they will train. Different image formats carry unique characteristics some prioritize quality while others optimize for file size. The preprocessing pipeline adapts these raw images into standardized arrays that neural networks can process effectively.

image
Title: The Image Classification Challenge
Source: Russakovsky et al., 2014

Image Formats: Understanding the Fundamentals

Moreover, digital images come in various formats, each with distinct advantages and trade-offs. Understanding these differences is crucial for selecting the appropriate format and library for your machine learning tasks.

Common Image Formats Comparison

BMP (Bitmap)

BMP is the simplest file type, requiring minimal processing to store an image. It uses uncompressed or lossless compression, resulting in large files with high memory demands. Generally an artifact of older systems, BMP files are often converted to more efficient formats before use in modern applications.

JPG/JPEG

The JPEG (Joint Photographic Experts Group) compression scheme is lossy, potentially removing image details during storage. While typically imperceptible to humans, this lossiness can affect mathematical relationships important for machine learning. JPEGs are widely accepted for natural images and used extensively in large datasets where memory efficiency is critical.

PNG (Portable Network Graphics)

PNG’s primary advantage is transparency support through an additional alpha channel (RGBA instead of RGB). It employs lossless compression, making it less memory-efficient than JPEG but ideal for applications requiring masks or transparencies.

TIFF (Tagged Image File Format)

Additionally, TIFF supports extensive metadata and multiple channels beyond standard RGB. TIFF images offer high quality with flexible compression options. This format is valuable in scientific applications, and it can handle more than three channels, which is useful for hyperspectral imaging and other specialized domains.

Medical Imaging: DICOM Format

DICOM (Digital Imaging and Communications in Medicine) enables standardized communication of medical images with comprehensive metadata including patient details and imaging system specifications. While supporting 2D slices, multiple slices can create 3D reconstructions. DICOM files are typically large but can be converted to NIFTI format for more efficient processing.

Temporal and 3D Data

Similarly, 3D volumes or temporal sequences (like video frames) are often represented as sequences of 2D images. These can be stored in standard image formats or specialized containers like Point Cloud Data or HDF5. Tools like ImageJ facilitate conversions between these representations.

Library Selection: Tools for Reading Images

Furthermore, Python offers several powerful libraries for image reading and manipulation. Each has distinct advantages:

Pillow (PIL)

Pillow provides excellent support for many formats including PNG, JPG, BMP, and TIFF. While computationally slower than OpenCV, it offers a clean API and broad format compatibility.

Python
from PIL import Image
import numpy as np

# Reading an image
im = Image.open('image.jpg')

# Convert to numpy array
im_array = np.array(im)

# Display properties
print(f"Image size: {im.size}")
print(f"Image mode: {im.mode}")
print(f"Array shape: {im_array.shape}")

OpenCV

OpenCV is computationally optimized for real-time processing and handles many codecs and formats. Important note: OpenCV loads images in BGR (Blue-Green-Red) format rather than RGB, which requires conversion for compatibility with most other libraries.

Python
import cv2
import numpy as np

# Reading an image
im = cv2.imread('image.jpg')

# Convert BGR to RGB for matplotlib display
im_rgb = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)

# Convert to grayscale
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

print(f"Image shape: {im.shape}")
print(f"Grayscale shape: {im_gray.shape}")

Scikit-image

However, scikit-image offers broad support for image processing tasks but is generally less computationally efficient than OpenCV. It excels in research settings where ease of use matters more than raw speed.

Python
from skimage import io
import matplotlib.pyplot as plt

# Reading an image
im = io.imread('image.jpg')

# Display the image
plt.figure(figsize=(8, 8))
plt.imshow(im)
plt.axis('off')
plt.show()

print(f"Image shape: {im.shape}")
print(f"Data type: {im.dtype}")
print(f"Min value: {im.min()}, Max value: {im.max()}")

ImageIO

Additionally, ImageIO offers a lightweight architecture that is useful for large images. It provides a simple interface for reading various formats without heavy dependencies.

Python
import imageio
import numpy as np

# Reading an image
im = imageio.imread('image.jpg')

# Reading a multi-page TIFF
frames = imageio.mimread('multipage.tiff')

print(f"Number of frames: {len(frames)}")
print(f"Shape of first frame: {frames[0].shape}")

Reading Specialized Formats

TIFF Files: Handling High-Depth Data

The tifffile library provides the most straightforward method for reading TIFF images. TIFF files can store extensive metadata, and Pillow enables extraction of this information.

Python
import tifffile
from PIL import Image
from PIL.TiffTags import TAGS

# Simplest way to read TIFF files
im = tifffile.imread('image.tiff')

# Using Pillow for metadata extraction
im_pil = Image.open('image.tiff')
metadata = {TAGS[key]: im_pil.tag[key] for key in im_pil.tag_v2}

print("Metadata:", metadata)
print(f"Image data type: {im.dtype}")
print(f"Image range: {im.min()} to {im.max()}")

Important: TIFF pixel values aren’t limited to 8-bit (0-255). In scientific applications, they often use 16-bit or even 32-bit values. Proper visualization may require linear or logarithmic scaling.

Python
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import numpy as np

def display_tiff_scientific(im):
    """Display TIFF with logarithmic scaling for scientific data"""
    plt.figure(figsize=(10, 8))
    plt.imshow(im, cmap='inferno', 
               norm=LogNorm(vmin=1, vmax=np.max(im)))
    plt.colorbar(label='Intensity (log scale)')
    plt.title('Scientific TIFF Image Display')
    plt.show()

# Usage
display_tiff_scientific(tifffile.imread('scientific_image.tiff'))

DICOM Medical Images

Python
import pydicom
import matplotlib.pyplot as plt
import numpy as np

# Reading a DICOM file
dcm = pydicom.dcmread('medical_image.dcm')

# Access pixel data
pixel_array = dcm.pixel_array

# Display with proper windowing
plt.figure(figsize=(10, 10))
plt.imshow(pixel_array, cmap='gray')
plt.colorbar(label='HU Values')
plt.title('DICOM Medical Image')
plt.show()

# Access metadata
print(f"Patient ID: {dcm.PatientID}")
print(f"Study Date: {dcm.StudyDate}")
print(f"Modality: {dcm.Modality}")
print(f"Slice Thickness: {getattr(dcm, 'SliceThickness', 'N/A')}")

Reading Temporal Data: Videos and 3D Sequences

Reading Videos

Python
import cv2
import numpy as np

def read_video(video_path):
    """Read video file and return as numpy array"""
    cap = cv2.VideoCapture(video_path)
    
    # Get video properties
    frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    
    print(f"Video: {frame_count} frames, {frame_width}x{frame_height}, {fps} FPS")
    
    # Allocate buffer
    frames = []
    ret = True
    
    while ret:
        ret, frame = cap.read()
        if ret:
            # Convert BGR to RGB
            frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            frames.append(frame_rgb)
    
    cap.release()
    
    # Convert to numpy array: (num_frames, height, width, channels)
    video_array = np.array(frames)
    print(f"Video array shape: {video_array.shape}")
    
    return video_array

# Usage
video = read_video('video.mp4')

Reading HDF5 Files

Python
import h5py
import numpy as np

def read_h5_images(h5_path, dataset_name='images'):
    """Read images from HDF5 file"""
    with h5py.File(h5_path, 'r') as f:
        # Get dataset
        dataset = f[dataset_name]
        
        # Read metadata
        print(f"Dataset shape: {dataset.shape}")
        print(f"Dataset dtype: {dataset.dtype}")
        
        # Read all data
        images = np.array(dataset)
        
    return images

# Usage
images = read_h5_images('images.h5')

Image Preprocessing: Preparing Data for Models

Preprocessing transforms raw images into formats suitable for machine learning models. This section covers essential transformations including resizing, reshaping, normalization, and colorspace conversion. For a deeper dive, see image preprocessing for deep learning. Additionally, use consistent steps so batches remain comparable across training runs.

Resizing: Downsampling and Upsampling

Resizing adapts images to model input requirements. Downsampling reduces image size while upsampling increases it. Consequently, the chosen method significantly impacts feature preservation.

Python
import cv2
import numpy as np

# Example: Downsampling
def downsample_systematic(image, factor=2):
    """Simple pixel dropping - fast but can introduce aliasing"""
    return image[::factor, ::factor, ...]

def downsample_interpolation(image, new_size):
    """Using interpolation - preserves edges better"""
    # INTER_AREA: Best for downsampling (prevents aliasing)
    downsampled = cv2.resize(image, new_size, 
                            interpolation=cv2.INTER_AREA)
    return downsampled

def upsample_interpolation(image, new_size):
    """Upsampling with interpolation"""
    # INTER_LINEAR: Good balance of speed and quality
    # INTER_CUBIC: Better quality but slower
    upsampled = cv2.resize(image, new_size, 
                          interpolation=cv2.INTER_CUBIC)
    return upsampled

# Load image
im = cv2.imread('image.jpg')

# Downsampling
half_size = (im.shape[1]//2, im.shape[0]//2)
downsampled = downsample_interpolation(im, half_size)

# Upsampling
double_size = (im.shape[1]*2, im.shape[0]*2)
upsampled = upsample_interpolation(im, double_size)

Reshaping: Adapting for Different Models

Different model architectures require different input shapes. For example, CNNs typically expect 2D or 3D image arrays, while LSTMs and transformers may require 1D flattened sequences.

Python
import numpy as np

# Example: Reshaping for different model types

# Original image shape: (height, width, channels)
h, w, c = 224, 224, 3
image = np.random.randn(h, w, c)

print(f"Original shape: {image.shape}")

# For CNN: Add batch dimension -> (batch, height, width, channels)
batch_size = 32
image_batch = np.tile(image, (batch_size, 1, 1, 1))
print(f"CNN batch shape: {image_batch.shape}")

# For LSTM/RNN: Flatten to 1D -> (sequence_length, features)
image_1d = image.flatten()
sequence_length = 100
image_sequence = image_1d[:sequence_length]
print(f"LSTM input shape: {image_sequence.shape}")

# For Vision Transformers: Divide into patches
patch_size = 16
num_patches_h = h // patch_size
num_patches_w = w // patch_size
patches = image.reshape(num_patches_h, patch_size, 
                       num_patches_w, patch_size, c)
patches = patches.swapaxes(1, 2).reshape(-1, patch_size, patch_size, c)
print(f"Patch shape: {patches.shape}")
print(f"Number of patches: {patches.shape[0]}")

Colorspace Conversion

Converting between color spaces enables model flexibility. Common conversions include RGB to grayscale, RGB to HSV, and grayscale to RGB for models expecting specific formats. Moreover, verify expected color order (RGB vs BGR) before converting.

Python
from PIL import Image
import cv2
import numpy as np

def convert_to_grayscale_pil(image_path):
    """Convert using PIL"""
    rgb_image = Image.open(image_path).convert('RGB')
    grayscale = rgb_image.convert('L')
    return np.array(grayscale)

def convert_to_grayscale_cv2(image):
    """Convert using OpenCV"""
    return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

def convert_to_hsv(image):
    """Convert RGB to HSV"""
    hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
    return hsv

def convert_to_lab(image):
    """Convert RGB to L*a*b* color space"""
    lab = cv2.cvtColor(image, cv2.COLOR_RGB2LAB)
    return lab

# Example usage
rgb_image = cv2.imread('image.jpg')
rgb_image = cv2.cvtColor(rgb_image, cv2.COLOR_BGR2RGB)

# Different conversions
gray = convert_to_grayscale_cv2(rgb_image)
hsv = convert_to_hsv(rgb_image)
lab = convert_to_lab(rgb_image)

print(f"RGB shape: {rgb_image.shape}")
print(f"Grayscale shape: {gray.shape}")
print(f"HSV shape: {hsv.shape}")
print(f"LAB shape: {lab.shape}")
Color Space Conversions: RGB, HSV, and LAB
Figure 8: Different Color Space Representations
Source: Ecihsp, Wikimedia Commons

Normalization: Preparing for Training

Normalization standardizes pixel values to specific ranges, improving training stability and convergence. Common approaches include min-max scaling and z-score normalization.

Python
import numpy as np

def normalize_min_max(image, min_val=0, max_val=1):
    """Min-max normalization to [min_val, max_val]"""
    image = image.astype(np.float32)
    image_min = image.min()
    image_max = image.max()
    
    # Avoid division by zero
    if image_max - image_min == 0:
        return image * max_val
    
    normalized = (image - image_min) / (image_max - image_min)
    return normalized * (max_val - min_val) + min_val

def normalize_zscore(image):
    """Z-score normalization: mean=0, std=1"""
    image = image.astype(np.float32)
    mean = image.mean()
    std = image.std()
    
    if std == 0:
        return image
    
    return (image - mean) / std

def normalize_for_pretrained(image, mean=[0.485, 0.456, 0.406], 
                            std=[0.229, 0.224, 0.225]):
    """Normalize for pretrained models (ImageNet statistics)"""
    image = image.astype(np.float32) / 255.0
    
    if len(image.shape) == 3 and image.shape[2] == 3:
        # RGB image
        for i in range(3):
            image[:, :, i] = (image[:, :, i] - mean[i]) / std[i]
    
    return image

# Example usage
image = cv2.imread('image.jpg')
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Different normalization strategies
normalized_minmax = normalize_min_max(rgb_image)
normalized_zscore = normalize_zscore(rgb_image)
normalized_pretrained = normalize_for_pretrained(rgb_image)

print(f"Original range: [{rgb_image.min()}, {rgb_image.max()}]")
print(f"Min-max range: [{normalized_minmax.min()}, {normalized_minmax.max()}]")
print(f"Z-score mean: {normalized_zscore.mean():.6f}, std: {normalized_zscore.std():.6f}")

Creating Robust Train/Test/Validation Splits

Therefore, proper data splitting ensures model generalization and reduces overfitting. The goal is to evaluate models on unseen data, confirming genuine learning rather than memorization.

Python
import numpy as np
from sklearn.model_selection import train_test_split
def create_data_splits(data, labels=None, train_ratio=0.7, 
                      val_ratio=0.15, test_ratio=0.15, random_state=42):
    """
    Create train/validation/test splits
    
    Args:
        data: Image dataset (n_samples, height, width, channels)
        labels: Optional labels
        train_ratio: Proportion for training
        val_ratio: Proportion for validation
        test_ratio: Proportion for testing
        random_state: Random seed for reproducibility
    
    Returns:
        train, val, test splits
    """
    assert abs(train_ratio + val_ratio + test_ratio - 1.0) < 1e-6, \
        "Ratios must sum to 1.0"
    
    np.random.seed(random_state)
    
    # Shuffle indices
    n_samples = len(data)
    indices = np.random.permutation(n_samples)
    
    # Calculate split points
    n_train = int(n_samples * train_ratio)
    n_val = int(n_samples * val_ratio)
    
    # Split indices
    train_indices = indices[:n_train]
    val_indices = indices[n_train:n_train + n_val]
    test_indices = indices[n_train + n_val:]
    
    # Split data
    train_data = data[train_indices]
    val_data = data[val_indices]
    test_data = data[test_indices]
    
    if labels is not None:
        train_labels = labels[train_indices]
        val_labels = labels[val_indices]
        test_labels = labels[test_indices]
        return (train_data, train_labels), (val_data, val_labels), \
               (test_data, test_labels)
    
    return train_data, val_data, test_data
# Example: 100 images of size 256x256
data = np.random.randn(100, 256, 256, 3)
train, val, test = create_data_splits(data, 
                                     train_ratio=0.8, 
                                     val_ratio=0.1, 
                                     test_ratio=0.1)
print(f"Train size: {train.shape}")
print(f"Validation size: {val.shape}")
print(f"Test size: {test.shape}")

Advanced Preprocessing Techniques

Data Augmentation

In practice, data augmentation expands training datasets through transformations like rotation, flipping, and cropping, improving model robustness and reducing overfitting.

Python
import cv2
import numpy as np
from scipy.ndimage import rotate

def augment_image(image):
    """
    Apply multiple augmentations to an image
    """
    augmented_images = []
    
    # Horizontal flip
    flipped_h = cv2.flip(image, 1)
    augmented_images.append(flipped_h)
    
    # Vertical flip
    flipped_v = cv2.flip(image, 0)
    augmented_images.append(flipped_v)
    
    # Rotations
    for angle in [10, -10, 15, -15]:
        rotated = rotate(image, angle, reshape=False)
        augmented_images.append(rotated)
    
    # Brightness adjustment
    bright = np.clip(image * 1.2, 0, 255).astype(np.uint8)
    augmented_images.append(bright)
    
    dark = np.clip(image * 0.8, 0, 255).astype(np.uint8)
    augmented_images.append(dark)
    
    return augmented_images

# Usage
image = cv2.imread('image.jpg')
augmented = augment_image(image)
print(f"Generated {len(augmented)} augmented images")

Handling 3D/Temporal Data

Likewise, sequential or 3D data requires special handling for models like 3D CNNs or LSTM architectures designed for temporal sequences.

Python
import numpy as np
def prepare_3d_data(video_sequence, target_shape=(64, 224, 224, 3)):
    """
    Prepare 3D/temporal data for models
    
    Args:
        video_sequence: (num_frames, height, width, channels)
        target_shape: Desired shape
    
    Returns:
        Reshaped and normalized data
    """
    # Resize frames to target spatial dimensions
    num_frames, target_frames, target_h, target_w, target_c = target_shape
    frames = []
    
    for frame in video_sequence:
        resized = cv2.resize(frame, (target_w, target_h))
        frames.append(resized)
    
    # Pad or trim to target number of frames
    current_frames = len(frames)
    if current_frames < target_frames:
        # Pad with last frame
        last_frame = frames[-1]
        for _ in range(target_frames - current_frames):
            frames.append(last_frame)
    elif current_frames > target_frames:
        # Subsample
        indices = np.linspace(0, current_frames-1, target_frames).astype(int)
        frames = [frames[i] for i in indices]
    
    video_array = np.array(frames)
    
    # Normalize
    video_array = video_array.astype(np.float32) / 255.0
    
    return video_array
# Example usage
video = np.random.randn(100, 480, 640, 3)  # 100 frames
prepared = prepare_3d_data(video)
print(f"Prepared shape: {prepared.shape}")

Best Practices and Recommendations

  • Library Selection: Use OpenCV for production speed, Pillow for format compatibility, and scikit-image for research flexibility
  • Color Channel Order: Always verify RGB vs BGR ordering when switching between OpenCV and other libraries
  • Normalization Strategy: Match normalization to your model – use ImageNet statistics for pretrained models
  • Memory Management: For large datasets, use generators or batches to avoid loading all images into memory
  • Data Augmentation: Apply augmentation dynamically during training rather than preprocessing the entire dataset
  • Format Consistency: Standardize input formats across your pipeline to avoid unexpected shape mismatches

Conclusion

Overall, reading and preprocessing images for machine learning requires understanding multiple formats, libraries, and transformation techniques. From basic JPEG files to specialized DICOM medical images, each format needs appropriate handling. The preprocessing pipeline including resizing, normalization, and data augmentation transforms raw images into model-ready tensors.

Ultimately, successful image preparation balances computational efficiency with data quality, ensuring models receive well-formatted inputs. Whether working with standard computer vision tasks or specialized domains like medical imaging, a solid grasp of image reading and preprocessing forms the foundation of effective machine learning pipelines.

Videos

  • This video introduces the fundamental functions of OpenCV, an open-source computer vision library used in image processing and computer vision. (Runtime: 19 mins)
YouTube video
“Image Handling, Color Channels & Conversions – OpenCV Basics” by OpenCV Uiversity
  • This video discusses image augmentation and how various techniques, such as flipping images, adjusting brightness, color jitter, and random noise. (Runtime: 9 mins 30 seconds)
YouTube video
“Image Augmentation for Deep Learning” by A Data Odyssey on Youtube

References & Further Reading

  1. What is Computer Vision? What are the different Computer Vision tasks?
  2. Understanding CNN Architecture
  3. What is Image Classification? Guide to CNN models and Applications

Authors

Help us improve this post by suggesting in comments below:

– modifications to the text, and infographics
– video resources that offer clear explanations for this question
– code snippets and case studies relevant to this concept
– online blogs, and research publications that are a “must read” on this topic

Leave the first comment

Partner Ad
Find out all the ways that you can
Contribute