1. Install imageio
In useimageio
Before, you need to make sure that the library is installed. It can be installed through the following command:
pip install imageio
If you need to support additional formats (such as reading videos or special image formats), you may need to install plugins, such asimageio[ffmpeg]
:
pip install imageio[ffmpeg]
2. Basic functions
1. Read and write images
imageio
Supports a variety of image formats, including PNG, JPEG, BMP, TIFF, etc.
- Read the image:
import imageio.v3 as iio # Read image filesimage = ('') print(type(image)) # <class ''> print() # image dimensions (height, width, channels)
- Write to the image:
# Save the image to the file('', image)
2. Display the image
Images can be displayed in conjunction with other visual libraries (such as Matplotlib):
import as plt (image) ('off') # Hide coordinate axes()
3. Process video files
imageio
Provides convenient video reading and writing functions.
- Read video frames:
video_reader = ('example.mp4') for frame in video_reader: print() # Shape of each frame break # View only the first frame
- Write to video file:
frames = [image, image] # Sample frame list('output.mp4', frames, fps=30)
4. Plug-in support
imageio
The powerful functions of are derived from its plug-in architecture. By installing different plugins, the supported formats can be extended. For example:
- Install
imageio[ffmpeg]
To support video formats such as MP4. - use
imageio[openexr]
Supports EXR images.
5. Advanced functions
1. Reading and generating dynamic GIFs
- Read GIF:
gif = ('', plugin='pillow') print() # Multi-frame image
- Generate GIFs:
frames = [image, image] # Sample frame list('', frames, loop=1)
2. Image format conversion
By reading and saving, format conversion can be easily implemented:
image = ('') ('', image)
3. High resolution image processing
For super large images, memory-friendly streaming can be used:
with ('large_image.tiff', 'r') as file: for block in file.iter_blocks(size=(1024, 1024)): print() # Shape of each block
6. Frequently Asked Questions and Solutions
Plugin error was encountered while reading video
Make sure it is installedffmpeg
support:
pip install imageio[ffmpeg]
The colors are inconsistent when saving the image
useimageio.v3
When versioned, the color channel order is RGB, while some old plugins may default to BGR. Please make sure the color channels are handled correctly:
import numpy as np rgb_image = (image, axis=-1) # Convert BGR to RGB('', rgb_image)
7. Basic summary
imageio
It is an all-rounder who handles images and videos, especially suitable for scenarios where functions need to be quickly implemented. Its simple interface and powerful plug-in support allow users to easily manipulate images and video files. From basic reading and writing to advanced dynamic GIF generation and large-picture streaming,imageio
Provides powerful functions.
8. Advanced practical cases
Here are some based onimageio
The practical scenarios include image batch processing, video frame extraction and editing, and dynamic visualization cases.
Case 1: Batch processing of images (such as batch scaling or format conversion)
When processing large batches of images,imageio
Provides an efficient method.
Target: Convert all image files in one directory to PNG format and resize to 224x224.
import os import imageio.v3 as iio from PIL import Image def process_images(input_dir, output_dir, size=(224, 224)): if not (output_dir): (output_dir) for filename in (input_dir): if (('.jpg', '.jpeg', '.png', '.bmp', '.tiff')): file_path = (input_dir, filename) # Read the image image = (file_path) # Use PIL to adjust the size image_resized = (image).resize(size) # Save as PNG format output_path = (output_dir, (filename)[0] + '.png') (output_path, image_resized) print(f"Processed: {output_path}") # Example usageprocess_images('input_images', 'output_images')
Case 2: Video frame extraction and synthesis
In computer vision projects, it is often necessary to extract frames of videos, process them before recombining them into videos.
Target: Extract each frame of the video into an image, apply grayscale processing and re-synthesize the video.
import imageio.v3 as iio import numpy as np def process_video(input_video, output_video): # Extract frames frames = list((input_video)) print(f"Total frames extracted: {len(frames)}") #Grayscale processing gray_frames = [(frame, axis=-1).astype(np.uint8) for frame in frames] # Synthesize new videos (output_video, gray_frames, fps=30) print(f"Processed video saved as: {output_video}") # Example usageprocess_video('input_video.mp4', 'output_video.mp4')
Case 3: Generate dynamic images (GIF animation)
Dynamic images (GIFs) are often used to show the inference results or data changes of machine learning models.
Target: Create a dynamic GIF to show the process of gradually blurring the image.
import imageio.v3 as iio from import gaussian_filter def create_blur_gif(input_image, output_gif, steps=10): # Read the input image image = (input_image) frames = [] for sigma in range(steps): # Add frames of different levels of blur blurred = gaussian_filter(image, sigma=sigma) (blurred) # Save as GIF (output_gif, frames, loop=1, duration=0.2) print(f"Blur animation saved as: {output_gif}") # Example usagecreate_blur_gif('', 'blur_animation.gif')
Case 4: Processing super-large image files
In the fields of remote sensing, medical imaging, etc., super-large image files are often encountered. Through block processing, memory usage can be saved.
Target: Apply brightness enhancement operations to each block of a super-large image.
import imageio.v3 as iio import numpy as np def process_large_image(input_file, output_file, block_size=(1024, 1024)): with (input_file, "r") as reader, (output_file, "w") as writer: writer.init_from_file(reader) # Initialize the format of the output image for block in reader.iter_blocks(size=block_size): # Enhanced brightness (multiply by 1.2, but not more than 255) processed_block = (block * 1.2, 0, 255).astype(np.uint8) (processed_block) print(f"Processed large image saved as: {output_file}") # Example usageprocess_large_image('large_image.tiff', 'enhanced_image.tiff')
Case 5: Real-time video processing and display
By combiningimageio
andOpenCV
, can realize real-time video processing and display, and is suitable for monitoring, real-time detection and other scenarios.
Target: Capture the video stream in real time, add timestamps and display.
import imageio.v3 as iio import cv2 from datetime import datetime def process_live_video(output_video): # Turn on the camera cap = (0) writer = (output_video, "w", plugin="FFMPEG", fps=30) while (): ret, frame = () if not ret: break # Add a timestamp timestamp = ().strftime('%Y-%m-%d %H:%M:%S') (frame, timestamp, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) # Show video ('Live Video', frame) # Write frame (frame) # Press the 'q' key to exit if (1) & 0xFF == ord('q'): break () () () print(f"Live video saved as: {output_video}") # Example usageprocess_live_video('live_output.mp4')
Summary and prospect
From the above cases, we can see that the functions of imageio can cover a variety of tasks, from basic image processing to complex video editing. Its simple and easy-to-use interface and powerful plug-in support can effectively meet the needs of actual projects.
In future applications, imageio can be used to preprocess data with deep learning frameworks (such as TensorFlow, PyTorch); or to process ultra-large data sets with large-scale distributed systems to tap into more potential.
The above is the detailed explanation of Python's operation of using the imageio library to process images and videos. For more information about Python's imageio processing images and videos, please follow my other related articles!