IO Module
The io module provides functions for reading, writing, and displaying images with enhanced error handling and automatic color space conversion.
Input/Output operations for image handling.
This module provides functions and classes for reading, writing, and displaying images with automatic color space conversion and enhanced error handling.
- Functions:
is_ascii: Check if a string contains only ASCII characters. imdecode: Decode an image from a buffer. imread: Read an image from a file. imwrite: Write an image to a file. imshow: Display an image in a window. wait_key: Wait for a keyboard event. destroy_windows: Destroy all windows. destroy_window: Destroy a specific window.
- Classes:
Window: Manage a single display window. Windows: Manage multiple display windows.
- cv3.io.imread(img_path, flag=1)[source]
Read an image from a file.
- Parameters:
img_path (str or Path) – Path to the image file.
flag (int or str, optional) – Flag specifying the color type of the loaded image. Can be one of: ‘color’, ‘gray’, ‘alpha’, ‘unchanged’ or OpenCV flags. Defaults to cv2.IMREAD_COLOR.
- Returns:
Loaded image.
- Return type:
numpy.ndarray
- Raises:
IsADirectoryError – If img_path is a directory.
FileNotFoundError – If img_path does not exist.
OSError – If the image file cannot be read.
Note
This function automatically handles RGB/BGR color space conversion based on the opt.RGB setting. When opt.RGB is True (default), the image is converted from BGR to RGB.
Example
>>> import cv3 >>> # Read a color image >>> img = cv3.imread('image.jpg') >>> # Read a grayscale image >>> img = cv3.imread('image.jpg', 'gray') >>> # Read an image with alpha channel >>> img = cv3.imread('image.png', 'unchanged')
- cv3.io.imdecode(buf, flag)[source]
Decode an image from a buffer.
- Parameters:
buf (numpy.ndarray) – Buffer containing the image data.
flag (int or str) – Flag specifying the color type of the decoded image. Can be one of: ‘color’, ‘gray’, ‘alpha’, ‘unchanged’ or OpenCV flags.
- Returns:
Decoded image.
- Return type:
numpy.ndarray
Example
>>> import cv3 >>> import numpy as np >>> # Read image file as bytes >>> with open('image.jpg', 'rb') as f: ... buf = np.frombuffer(f.read(), dtype=np.uint8) >>> # Decode image >>> img = cv3.imdecode(buf, 'color')
- cv3.io.imwrite(img_path, img, mkdir=False, ascii=True)[source]
Write an image to a file.
- Parameters:
img_path (str or Path) – Path to the image file to write.
img (numpy.ndarray) – Image to write.
mkdir (bool, optional) – If True, create parent directories if they don’t exist. Defaults to False.
ascii (bool, optional) – If True, use ASCII filename handling. If False, use non-ASCII filename handling with numpy’s tofile method. Defaults to True.
- Raises:
OSError – If the image cannot be written to the file.
Note
This function automatically handles RGB/BGR color space conversion based on the opt.RGB setting. When opt.RGB is True (default), the image is converted from RGB to BGR before writing.
When ascii=False, the function uses numpy’s tofile method to handle non-ASCII filenames, which is useful for international characters in filenames.
Example
>>> import cv3 >>> import numpy as np >>> # Create a simple image >>> img = np.zeros((100, 100, 3), dtype=np.uint8) >>> img[:, :] = [255, 0, 0] # Blue image (BGR) >>> # Write image to file >>> cv3.imwrite('output.jpg', img) >>> # Write image with automatic directory creation >>> cv3.imwrite('output_dir/output.jpg', img, mkdir=True)
- cv3.io.imshow(window_name, img)[source]
Display an image in a window.
- Parameters:
window_name (str) – Name of the window to display the image in.
img (numpy.ndarray) – Image to display.
Note
This function automatically handles RGB/BGR color space conversion based on the opt.RGB setting. When opt.RGB is True (default), the image is converted from RGB to BGR before displaying.
Example
>>> import cv3 >>> import numpy as np >>> # Create a simple image >>> img = np.zeros((100, 100, 3), dtype=np.uint8) >>> img[:, :] = [255, 0, 0] # Blue image (BGR) >>> # Display the image >>> cv3.imshow('My Image', img) >>> cv3.waitKey(0)
- class cv3.io.Window(window_name=None, pos=None, flag=1)[source]
Bases:
objectA class to manage a single display window.
This class provides a convenient way to create and manage OpenCV windows with additional features like automatic naming and context manager support.
- window_name
The name of the window.
- Type:
str
- __init__(window_name=None, pos=None, flag=1)[source]
Initialize a Window object.
- Parameters:
window_name (str, optional) – Name of the window. If None, a name will be automatically generated. Defaults to None.
pos (tuple, optional) – Starting position of the window as (x, y). Defaults to None.
flag (int, optional) – Window flag. Defaults to cv2.WINDOW_AUTOSIZE.
Example
>>> import cv3 >>> import numpy as np >>> # Create a window with automatic naming >>> window = cv3.Window() >>> # Create a window with a specific name and position >>> window = cv3.Window('My Window', pos=(100, 100))
- imshow(img)[source]
Display an image in this window.
- Parameters:
img (numpy.ndarray) – Image to display.
Note
This function automatically handles RGB/BGR color space conversion based on the opt.RGB setting. When opt.RGB is True (default), the image is converted from RGB to BGR before displaying.
Example
>>> import cv3 >>> import numpy as np >>> # Create a window >>> window = cv3.Window('My Window') >>> # Create an image >>> img = np.zeros((100, 100, 3), dtype=np.uint8) >>> img[:, :] = [255, 0, 0] # Blue image (BGR) >>> # Display the image >>> window.imshow(img)
- move(x, y)[source]
Move the window to a new position.
- Parameters:
x (int) – New x-coordinate of the window.
y (int) – New y-coordinate of the window.
Example
>>> import cv3 >>> # Create a window >>> window = cv3.Window('My Window') >>> # Move the window to position (200, 200) >>> window.move(200, 200)
- close()[source]
Close this window and free associated resources.
Example
>>> import cv3 >>> # Create a window >>> window = cv3.Window('My Window') >>> # Close the window >>> window.close()
- static wait_key(t)[source]
Wait for a keyboard event.
This is a static method that calls the module-level wait_key function.
- Parameters:
t (int) – Delay in milliseconds. If 0, it waits indefinitely for a key stroke.
- Returns:
The code of the pressed key, or -1 if no key was pressed before the timeout.
- Return type:
int
Example
>>> import cv3 >>> # Create a window >>> window = cv3.Window('My Window') >>> # Wait for a key press for 1 second >>> key = window.wait_key(1000)
- class cv3.io.Windows(window_names, poses=None)[source]
Bases:
objectA class to manage multiple display windows.
This class provides a convenient way to create and manage multiple OpenCV windows with additional features like context manager support.
- windows
A dictionary mapping window names to Window objects.
- Type:
dict
- __init__(window_names, poses=None)[source]
Initialize a Windows object.
- Parameters:
window_names (list) – List of window names.
poses (list, optional) – List of positions for each window as (x, y) tuples. If None, windows will use default positions. Defaults to None.
Example
>>> import cv3 >>> # Create multiple windows >>> windows = cv3.Windows(['Window1', 'Window2']) >>> # Create multiple windows with specific positions >>> windows = cv3.Windows(['Window1', 'Window2'], poses=[(100, 100), (200, 200)])
- __getitem__(name)[source]
Get a specific window by name.
- Parameters:
name (str) – Name of the window to retrieve.
- Returns:
The requested window object.
- Return type:
Example
>>> import cv3 >>> # Create multiple windows >>> windows = cv3.Windows(['Window1', 'Window2']) >>> # Access a specific window >>> window1 = windows['Window1']
- close()[source]
Close all windows and free associated resources.
Example
>>> import cv3 >>> # Create multiple windows >>> windows = cv3.Windows(['Window1', 'Window2']) >>> # Close all windows >>> windows.close()
- static wait_key(t)[source]
Wait for a keyboard event.
This is a static method that calls the module-level wait_key function.
- Parameters:
t (int) – Delay in milliseconds. If 0, it waits indefinitely for a key stroke.
- Returns:
The code of the pressed key, or -1 if no key was pressed before the timeout.
- Return type:
int
Example
>>> import cv3 >>> # Create multiple windows >>> windows = cv3.Windows(['Window1', 'Window2']) >>> # Wait for a key press for 1 second >>> key = windows.wait_key(1000)
- __enter__()[source]
Enter the runtime context for the windows.
- Returns:
This windows instance.
- Return type:
Example
>>> import cv3 >>> # Use windows as a context manager >>> with cv3.Windows(['Window1', 'Window2']) as windows: ... # All windows are automatically closed when exiting the context ... pass
- cv3.io.wait_key(t)[source]
Wait for a keyboard event.
- Parameters:
t (int) – Delay in milliseconds. If 0, it waits indefinitely for a key stroke.
- Returns:
The code of the pressed key, or -1 if no key was pressed before the timeout.
- Return type:
int
Note
This function is a wrapper around cv2.waitKey() that masks the return value with 0xFF to ensure consistent behavior across different platforms.
Example
>>> import cv3 >>> # Wait for a key press for 1 second >>> key = cv3.wait_key(1000) >>> if key != -1: ... print(f'Key pressed: {key}')
- cv3.io.waitKey(t)
Alias for
wait_key().
- cv3.io.destroy_windows()[source]
Destroy all windows.
This function destroys all windows that were created with imshow or Window.
Note
This is a wrapper around cv2.destroyAllWindows().
Example
>>> import cv3 >>> # Create and display an image >>> import numpy as np >>> img = np.zeros((100, 100, 3), dtype=np.uint8) >>> cv3.imshow('Window1', img) >>> cv3.imshow('Window2', img) >>> # Destroy all windows >>> cv3.destroy_windows()
- cv3.io.destroyAllWindows()
Alias for
destroy_windows().
- cv3.io.destroy_window(winname: str)[source]
Destroy a specific window.
- Parameters:
winname (str) – Name of the window to destroy.
Note
This is a wrapper around cv2.destroyWindow().
Example
>>> import cv3 >>> # Create and display an image >>> import numpy as np >>> img = np.zeros((100, 100, 3), dtype=np.uint8) >>> cv3.imshow('My Window', img) >>> # Destroy the specific window >>> cv3.destroy_window('My Window')
- cv3.io.destroyWindow(winname: str)
Alias for
destroy_window().
|
Read an image from a file. |
|
Write an image to a file. |
|
Display an image in a window. |
|
Decode an image from a buffer. |
|
Check if a string contains only ASCII characters. |
|
Wait for a keyboard event. |
|
Alias for |
Destroy all windows. |
|
Alias for |
|
|
Destroy a specific window. |
|
Alias for |
|
A class to manage a single display window. |
|
A class to manage multiple display windows. |