### Install and Run PyTurboJPEG Tests Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/configuration.md Commands to install PyTurboJPEG with test dependencies and execute the test suite using pytest. Useful for verifying the installation and development setup. ```bash # Install with test dependencies pip install -e ".[test]" # Run tests pytest tests/ # Run specific test pytest tests/test_turbojpeg.py::test_decode ``` -------------------------------- ### Install Dependencies for Testing Source: https://github.com/lilohuang/pyturbojpeg/blob/master/TESTING.md Install necessary system and Python dependencies before running tests. Ensure you have the TurboJPEG library installed on your system. ```bash # Install dependencies sudo apt-get install libturbojpeg # On Ubuntu/Debian # OR brew install jpeg-turbo # On macOS # Install Python dependencies pip install numpy pytest pytest-memray ``` -------------------------------- ### Install PyTurboJPEG on Windows Source: https://github.com/lilohuang/pyturbojpeg/blob/master/README.md First, download and install the libjpeg-turbo official installer. Then, install PyTurboJPEG using pip from its GitHub repository. Requires libjpeg-turbo 3.0+. ```bash pip install -U git+https://github.com/lilohuang/PyTurboJPEG.git ``` -------------------------------- ### Usage Patterns and Examples Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/MANIFEST.txt Illustrates common and advanced usage patterns for PyTurboJPEG with over 30 working code examples. ```APIDOC ## Usage Patterns and Examples This section provides practical examples of how to use PyTurboJPEG for various image processing tasks. ### Basic Image Processing Covers fundamental operations like loading, saving, and basic manipulation. ### Format Conversion Examples for converting between different image formats, including BGR/RGB, grayscale, and PIL images. ### Quality and Size Optimization Demonstrates techniques for optimizing JPEG quality and file size. ### Memory Efficiency Patterns for efficient memory usage, including pre-allocated buffers and in-place operations. ### High-Precision Imaging Examples for handling high-bit-depth images (12-bit medical, 16-bit archive). ### Streaming and Batch Processing Techniques for processing images in streams or batches. ### Transform Operations Examples for performing various image transformations like cropping and rotation. ### YUV Processing Handling of YUV color formats. ### Error Handling Patterns Practical examples of implementing error handling strategies. ### OpenCV Integration Examples showing integration with the OpenCV library. ### Performance Tuning Patterns for performance optimization, such as real-time video processing. ### ICC Color Management Examples for working with ICC color profiles. ### Total Examples Over 30 complete, working code examples are provided across these patterns. ``` -------------------------------- ### Install PyTurboJPEG on macOS Source: https://github.com/lilohuang/pyturbojpeg/blob/master/README.md Installs libjpeg-turbo using Homebrew and then installs PyTurboJPEG from its GitHub repository. Ensure libjpeg-turbo 3.0+ is installed. ```bash brew install jpeg-turbo pip install -U git+https://github.com/lilohuang/PyTurboJPEG.git ``` -------------------------------- ### Initialize TurboJPEG Source: https://github.com/lilohuang/pyturbojpeg/blob/master/README.md Instantiate the TurboJPEG class. You can use the default library installation or specify the path to the TurboJPEG shared library explicitly. ```python from turbojpeg import TurboJPEG # Use default library installation jpeg = TurboJPEG() # Or specify library path explicitly # jpeg = TurboJPEG(r'D:\turbojpeg.dll') # Windows # jpeg = TurboJPEG('/usr/lib64/libturbojpeg.so') # Linux # jpeg = TurboJPEG('/usr/local/lib/libturbojpeg.dylib') # macOS ``` -------------------------------- ### Platform-Specific TurboJPEG Initialization Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/errors.md Specify the path to the TurboJPEG library for different operating systems. Ensure the library is installed and accessible. ```python from turbojpeg import TurboJPEG # macOS jpeg = TurboJPEG('/usr/local/lib/libturbojpeg.dylib') # Linux jpeg = TurboJPEG('/usr/lib/x86_64-linux-gnu/libturbojpeg.so.0') # Windows jpeg = TurboJPEG(r'C:\libjpeg-turbo64\bin\turbojpeg.dll') # FreeBSD jpeg = TurboJPEG('/usr/local/lib/libturbojpeg.so.0') ``` -------------------------------- ### CroppingRegion Usage Example Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/types.md Shows how to use `CroppingRegion` to crop specific parts of an image using `jpeg.crop()` for a single region and `jpeg.crop_multiple()` for multiple regions. ```python from turbojpeg import TurboJPEG, CroppingRegion jpeg = TurboJPEG() # Crop a specific region with open('image.jpg', 'rb') as f: # Crop top-left 320×240 region starting at (8, 8) cropped = jpeg.crop(f.read(), x=8, y=8, w=320, h=240) # Multiple crops in one pass crops = jpeg.crop_multiple( jpeg_data, [ (0, 0, 320, 240), # Top-left (320, 0, 320, 240), # Top-right (0, 240, 640, 240) # Bottom ] ) ``` -------------------------------- ### Check PyTurboJPEG and System Versions Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/configuration.md Python script to display the installed versions of PyTurboJPEG, NumPy, Python, and indirectly, libjpeg-turbo. Helps in debugging compatibility issues. ```python import turbojpeg import numpy import sys print(f'PyTurboJPEG version: {turbojpeg.__version__}') print(f'NumPy version: {numpy.__version__}') print(f'Python version: {sys.version}') # Check libjpeg-turbo version (indirectly) jpeg = TurboJPEG() try: # Try 3.1+ features to detect version jpeg.get_icc_profile(b'') except NotImplementedError: print('libjpeg-turbo: 3.0') except: print('libjpeg-turbo: 3.1+') ``` -------------------------------- ### Specify TurboJPEG library path on macOS Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/configuration.md When installing via Homebrew, explicitly provide the path to the libturbojpeg.dylib library in the TurboJPEG constructor. ```bash brew install jpeg-turbo ``` ```python from turbojpeg import TurboJPEG jpeg = TurboJPEG('/opt/homebrew/opt/jpeg-turbo/lib/libturbojpeg.dylib') ``` -------------------------------- ### Handle OSError for Invalid Crop Parameters Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/errors.md Demonstrates how to catch and handle OSError when crop parameters are invalid, such as misaligned coordinates. It shows an example of attempting a crop with misaligned coordinates and then retrying with aligned coordinates. ```python from turbojpeg import TurboJPEG jpeg = TurboJPEG() with open('image.jpg', 'rb') as f: jpeg_data = f.read() # OSError: Invalid crop request try: # Crop with misaligned coordinates cropped = jpeg.crop(jpeg_data, x=5, y=5, w=320, h=240) except OSError as e: print(f'Invalid crop parameters: {e}') # Use aligned coordinates or preserve=False cropped = jpeg.crop(jpeg_data, x=8, y=8, w=320, h=240) ``` -------------------------------- ### ScalingFactor Usage Example Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/types.md Demonstrates how to use `ScalingFactor` with the `TurboJPEG` class to decode images at specific scaled resolutions. It checks for supported scaling factors before decoding. ```python from turbojpeg import TurboJPEG jpeg = TurboJPEG() # Check available scaling factors print('Available scaling factors:', jpeg.scaling_factors) # Decode with 1/4 scaling if (1, 4) in jpeg.scaling_factors: img = jpeg.decode(jpeg_data, scaling_factor=(1, 4)) else: print('1/4 scaling not supported') # Use a 2/3 scale factor for 66.67% size if (2, 3) in jpeg.scaling_factors: img = jpeg.decode(jpeg_data, scaling_factor=(2, 3)) ``` -------------------------------- ### Configuration Options Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/MANIFEST.txt Details on how to configure PyTurboJPEG, including library paths, encoding/decoding options, and platform-specific settings. ```APIDOC ## Configuration Options This document covers the configuration aspects of PyTurboJPEG. ### Initialization Parameters - **lib_path**: Path to the libjpeg-turbo library. ### Auto-detection Behavior How the library automatically detects and loads the TurboJPEG library. ### Encoding Options - **quality**: JPEG quality level (0-100). - **subsampling**: Chroma subsampling mode. - **lossless**: Enable lossless compression. - **ICC**: Embed ICC color profile. ### Decoding Options - **pixel_format**: Desired output pixel format. - **scaling**: Scaling factor for decompression. - **flags**: Decompression flags. ### Transform Options - **preserve**: Preserve image metadata. - **gray**: Convert to grayscale. - **copynone**: Do not copy metadata. ### Version Requirements Matrix detailing version compatibility between PyTurboJPEG and libjpeg-turbo. ### Platform-Specific Setup Instructions for setting up PyTurboJPEG on Linux, macOS, Windows, FreeBSD, and NetBSD. ### Performance Tuning Recommendations for optimizing performance. ### Default Library Paths Default paths for the TurboJPEG library on various platforms. ``` -------------------------------- ### Initialize TurboJPEG with Library Path Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/configuration.md Instantiate the TurboJPEG class, optionally providing an explicit path to the libjpeg-turbo shared library. If not provided, the library attempts to auto-detect the path. ```python from turbojpeg import TurboJPEG jpeg = TurboJPEG(lib_path='/path/to/libturbojpeg.so') ``` -------------------------------- ### TurboJPEG Constructor: __init__ Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/api-reference.md Initializes a TurboJPEG instance and loads the libjpeg-turbo library. Allows for auto-detection or explicit specification of the library path. ```APIDOC ## TurboJPEG Class ### Constructor: `__init__` ```python def __init__(self, lib_path=None) ``` Initializes a TurboJPEG instance and loads the libjpeg-turbo library. **Parameters:** - `lib_path` (str, Optional): Explicit path to libjpeg-turbo library. If None, auto-detects based on platform. **Returns:** TurboJPEG instance **Raises:** - `RuntimeError` if libjpeg-turbo 3.0+ is not found or library cannot be loaded. **Example:** ```python from turbojpeg import TurboJPEG # Auto-detect library jpeg = TurboJPEG() # Explicitly specify library path jpeg = TurboJPEG('/usr/lib/libturbojpeg.so.0') # Linux jpeg = TurboJPEG('/usr/local/lib/libturbojpeg.dylib') # macOS jpeg = TurboJPEG(r'C:\libjpeg-turbo64\bin\turbojpeg.dll') # Windows ``` ``` -------------------------------- ### Import Main Class Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/module-reference.md Import the main TurboJPEG class for use. ```python from turbojpeg import TurboJPEG ``` -------------------------------- ### Import Pixel Format Constants Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/module-reference.md Import constants for pixel formats like BGR, Grayscale, and RGB. ```python from turbojpeg import TJPF_BGR, TJPF_GRAY, TJPF_RGB ``` -------------------------------- ### Get Supported JPEG Scaling Factors Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/api-reference.md Retrieves a frozenset of valid scaling factor tuples supported by the libjpeg-turbo library. Used to determine supported downscaling ratios for decoding. ```python from turbojpeg import TurboJPEG jpeg = TurboJPEG() print(jpeg.scaling_factors) # Output: frozenset({(1, 1), (1, 2), (1, 4), (1, 8), (2, 3), ...}) # Decode with scaling if supported if (1, 4) in jpeg.scaling_factors: img = jpeg.decode(jpeg_data, scaling_factor=(1, 4)) ``` -------------------------------- ### Import Subsampling Constants Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/module-reference.md Import constants for chroma subsampling options. ```python from turbojpf import TJSAMP_422, TJSAMP_420, TJSAMP_GRAY ``` -------------------------------- ### Define TransformStruct for JPEG Operations Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/types.md This structure defines a lossless JPEG transform operation, including cropping region, operation type, options, background fill parameters, and a custom filter. It is an internal structure, with public API methods handling its setup. ```python class TransformStruct(Structure): _fields_ = [ ("r", CroppingRegion), ("op", c_int), ("options", c_int), ("data", POINTER(BackgroundStruct)), ("customFilter", CUSTOMFILTER) ] ``` -------------------------------- ### Import All Public APIs Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/module-reference.md Import all public APIs from the turbojpeg module at once. ```python from turbojpeg import * ``` -------------------------------- ### Multi-Method Fallback for Image Decoding Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/errors.md Try decoding with TurboJPEG, then OpenCV, and finally PIL as fallbacks. This ensures decoding success by attempting multiple libraries. ```python from turbojpeg import TurboJPEG import cv2 from PIL import Image def decode_image(image_data): """Try multiple decoders in order of preference.""" # Try TurboJPEG first (fastest) try: jpeg = TurboJPEG() return jpeg.decode(image_data) except Exception as e: print(f'TurboJPEG failed: {e}') # Fall back to OpenCV try: import cv2 import numpy as np nparr = np.frombuffer(image_data, np.uint8) return cv2.imdecode(nparr, cv2.IMREAD_COLOR) except Exception as e: print(f'OpenCV failed: {e}') # Final fallback to PIL try: from PIL import Image from io import BytesIO return np.array(Image.open(BytesIO(image_data))) except Exception as e: print(f'PIL failed: {e}') raise ``` -------------------------------- ### In-Place JPEG Encoding and Decoding Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/configuration.md Demonstrates how to perform in-place memory operations for JPEG encoding and decoding by pre-allocating input and output buffers. Reusing buffers reduces memory allocations and can improve performance. ```python from turbojpeg import TurboJPEG import numpy as np jpeg = TurboJPEG() # Pre-allocate input image img = np.empty((480, 640, 3), dtype=np.uint8) # Pre-allocate output JPEG buffer buffer = bytearray(jpeg.buffer_size(img)) # Encode in-place (reuse buffers) result, n_bytes = jpeg.encode(img, dst=buffer) print(f'Actual JPEG size: {n_bytes} bytes') # Pre-allocate decode output decoded = np.empty((480, 640, 3), dtype=np.uint8) # Decode in-place result = jpeg.decode(jpeg_data, dst=decoded) assert result is decoded # Same object ``` -------------------------------- ### Module Reference Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/MANIFEST.txt An overview of the PyTurboJPEG module structure, exported symbols, and internal organization. ```APIDOC ## Module Reference This document provides a reference for the PyTurboJPEG module structure. ### Module Overview General information about the module and its import patterns. ### Exported Symbols - **Classes**: `TurboJPEG` (1) - **Types**: 5 distinct types defined. - **Constants**: Over 60 constants organized by category. ### TurboJPEG Class Methods Reference to the 19 public methods and 1 property of the `TurboJPEG` class. ### Constant Definitions All defined constants are listed and categorized. ### Internal Function References References to internal functions used within the module. ### Module Dependencies Key dependencies include `ctypes`, `numpy`, and `platform`. ### Code Organization Information on the file structure and logical organization of the module's code. ### Stability and Compatibility Notes on module stability and version compatibility. ### Metadata Includes author, version, and license information. ``` -------------------------------- ### Default Library Paths Configuration Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/module-reference.md A dictionary mapping operating system names to lists of default TurboJPEG library paths. This is used for locating the necessary shared libraries on different platforms. ```python DEFAULT_LIB_PATHS = { 'Darwin': [...], # macOS 'Linux': [...], # Linux 'FreeBSD': [...], # FreeBSD 'NetBSD': [...], # NetBSD 'Windows': [...] # Windows } ``` -------------------------------- ### RuntimeError Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/errors.md Raised during initialization if the libjpeg-turbo library cannot be loaded or is incompatible. ```APIDOC ## RuntimeError ### Description Raised during initialization if libjpeg-turbo cannot be loaded or is incompatible. ### Raised by: - `TurboJPEG.__init__()` - constructor ### Trigger Conditions: - libjpeg-turbo library not found - Loaded library is libjpeg-turbo 2.x (requires 3.0+) - Library path is invalid or inaccessible - Library cannot be loaded due to missing dependencies ### Example: ```python from turbojpeg import TurboJPEG try: jpeg = TurboJPEG() except RuntimeError as e: if 'libjpeg-turbo 3.0 or later' in str(e): print('Please upgrade libjpeg-turbo to 3.0 or later') # Provide installation instructions to user else: print(f'Failed to initialize TurboJPEG: {e}') # Fallback to PIL, OpenCV, or other library ``` ``` -------------------------------- ### Compare JPEG Quality vs. File Size Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/usage-patterns.md Encodes a random image at various quality levels (50-95) and prints the resulting file size in MB. Demonstrates the trade-off between compression quality and file size. ```python from turbojpeg import TurboJPEG import numpy as np jpeg = TurboJPEG() img = np.random.randint(0, 256, (1080, 1920, 3), dtype=np.uint8) quality_levels = [50, 75, 85, 90, 95] for quality in quality_levels: data = jpeg.encode(img, quality=quality) size_mb = len(data) / 1024 / 1024 print(f'Quality {quality}: {size_mb:.2f} MB') # Output: # Quality 50: 0.42 MB # Quality 75: 0.68 MB # Quality 85: 0.82 MB # Quality 90: 1.12 MB # Quality 95: 1.58 MB ``` -------------------------------- ### Check PyTurboJPEG Feature Support Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/configuration.md Demonstrates how to check for specific feature availability, such as ICC profile support, by attempting to use the feature and catching a NotImplementedError. This is useful for ensuring compatibility with older libjpeg-turbo versions. ```python from turbojpeg import TurboJPEG jpeg = TurboJPEG() # Try to use a feature, catch NotImplementedError if unavailable try: icc = jpeg.get_icc_profile(jpeg_data) except NotImplementedError: print('ICC profile support requires libjpeg-turbo 3.1+') ``` -------------------------------- ### Encode Images with Different Quality Settings Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/configuration.md Demonstrates encoding images with varying quality levels for different use cases, from thumbnails to archive-quality images. Lossless compression can also be enabled. ```python from turbojpeg import TurboJPEG import numpy as np jpeg = TurboJPEG() img = np.random.randint(0, 256, (480, 640, 3), dtype=np.uint8) # Thumbnails: quality 50 jpeg_thumb = jpeg.encode(img, quality=50) # Web: quality 75-80 jpeg_web = jpeg.encode(img, quality=75) # Archive: quality 90-95 jpeg_archive = jpeg.encode(img, quality=95) # Maximum quality (lossless) jpeg_lossless = jpeg.encode(img, lossless=True) ``` -------------------------------- ### Handle Initialization Failures with RuntimeError Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/errors.md Catch RuntimeError during TurboJPEG initialization if the libjpeg-turbo library cannot be loaded or is incompatible. This typically occurs if the library is missing or an older version is detected. ```python from turbojpeg import TurboJPEG try: jpeg = TurboJPEG() except RuntimeError as e: if 'libjpeg-turbo 3.0 or later' in str(e): print('Please upgrade libjpeg-turbo to 3.0 or later') # Provide installation instructions to user else: print(f'Failed to initialize TurboJPEG: {e}') # Fallback to PIL, OpenCV, or other library ``` -------------------------------- ### Initialization Constants (Internal) Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/module-reference.md Internal constants used for initializing the TurboJPEG library for different modes. ```APIDOC ## Initialization Constants (Internal): - **TJINIT_COMPRESS**: 0 - Compression mode - **TJINIT_DECOMPRESS**: 1 - Decompression mode - **TJINIT_TRANSFORM**: 2 - Transform mode ``` -------------------------------- ### Generate memory flamegraph for a specific test Source: https://github.com/lilohuang/pyturbojpeg/blob/master/TESTING.md Execute this command to profile a specific test case with memray and generate a detailed memory flamegraph. This is useful for pinpointing memory usage issues within a particular test. ```bash pytest --memray tests/test_turbojpeg.py::TestMemoryManagement::test_encode_decode_stress_1000_cycles ``` -------------------------------- ### Import Type Aliases Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/module-reference.md Import type aliases for ScalingFactor and CroppingRegion. ```python from turbojpeg import ScalingFactor, CroppingRegion ``` -------------------------------- ### Import Flag Constants Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/module-reference.md Import constants for JPEG compression/decompression flags. ```python from turbojpeg import TJFLAG_PROGRESSIVE, TJFLAG_FASTUPSAMPLE ``` -------------------------------- ### Specify TurboJPEG library path on Windows Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/configuration.md Explicitly provide the path to the turbojpeg.dll library, specifying either the 64-bit or 32-bit version as needed. ```python from turbojpeg import TurboJPEG # 64-bit jpeg = TurboJPEG(r'C:\libjpeg-turbo64\bin\turbojpeg.dll') # 32-bit jpeg = TurboJPEG(r'C:\libjpeg-turbo\bin\turbojpeg.dll') ``` -------------------------------- ### Control Image Transforms with TJXOPT Constants Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/constants.md Use bitwise OR to combine TJXOPT constants for controlling transform behavior like cropping, grayscale conversion, and optimization. Ensure perfect transformation or trim partial blocks as needed. ```python from turbojpeg import TurboJPEG, TJXOPT_CROP, TJXOPT_GRAY, TJXOPT_COPYNONE jpeg = TurboJPEG() # Crop without EXIF cropped = jpeg.crop(jpeg_data, 0, 0, 320, 240, copynone=True) # Multiple crops with optimization crops = jpeg.crop_multiple(jpeg_data, [(0, 0, 320, 240), (320, 0, 320, 240)]) ``` -------------------------------- ### Generate Test Coverage Report Source: https://github.com/lilohuang/pyturbojpeg/blob/master/TESTING.md Create an HTML report detailing code coverage by the tests. This helps identify which parts of the codebase are exercised by the test suite. ```bash pytest tests/test_turbojpeg.py --cov=turbojpeg --cov-report=html ``` -------------------------------- ### Error Handling Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/MANIFEST.txt Information on exceptions raised by PyTurboJPEG, their causes, and recommended handling patterns. ```APIDOC ## Error Handling This section details the error handling mechanisms in PyTurboJPEG. ### Exception Types - **IOError**: For input/output related errors. - **RuntimeError**: For general runtime issues. - **ValueError**: For invalid argument values. - **TypeError**: For incorrect data types. - **NotImplementedError**: For features not yet implemented. - **OSError**: For operating system related errors. ### Trigger Conditions Descriptions of conditions that lead to each exception type. ### Error Messages and Resolutions Guidance on understanding error messages and resolving common issues. ### Error Conditions Tables Tables summarizing error conditions for decode, encode, transform, and initialization operations. ### Initialization Error Solutions Specific solutions for errors encountered during library initialization. ### Error Handling Patterns - **Fallback**: Strategies for gracefully handling errors by falling back to alternative methods. - **Validation**: Patterns for validating input data to prevent errors. - **Multi-method Fallback**: Advanced fallback strategies. ### Safe Decoding Techniques for safe decoding with fallback mechanisms. ``` -------------------------------- ### Handle EXIF Orientation with TurboJPEG Source: https://github.com/lilohuang/pyturbojpeg/blob/master/README.md Applies image transformations based on the EXIF Orientation tag. Requires OpenCV and exifread libraries. ```python import cv2 import numpy as np import exifread from turbojpeg import TurboJPEG def transpose_image(image, orientation): """Transpose image based on EXIF Orientation tag. See: https://www.exif.org/Exif2-2.PDF """ if orientation is None: return image val = orientation.values[0] if val == 1: return image elif val == 2: return np.fliplr(image) elif val == 3: return np.rot90(image, 2) elif val == 4: return np.flipud(image) elif val == 5: return np.rot90(np.flipud(image), -1) elif val == 6: return np.rot90(image, -1) elif val == 7: return np.rot90(np.flipud(image)) elif val == 8: return np.rot90(image) jpeg = TurboJPEG() with open('foobar.jpg', 'rb') as f: # Parse EXIF orientation orientation = exifread.process_file(f).get('Image Orientation', None) # Decode image f.seek(0) image = jpeg.decode(f.read()) # Apply orientation transformation transposed_image = transpose_image(image, orientation) cv2.imshow('transposed_image', transposed_image) cv2.waitKey(0) ``` -------------------------------- ### Constants Reference Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/MANIFEST.txt PyTurboJPEG defines numerous constants for pixel formats, subsampling, color spaces, precision, flags, transform operations, and parameters. ```APIDOC ## Constants Reference This document outlines the various constants provided by PyTurboJPEG, categorized for clarity. ### Pixel Formats (TJPF_*) Constants representing different pixel formats (e.g., `TJPF_RGB`, `TJPF_BGR`). ### Subsampling Formats (TJSAMP_*) Constants for JPEG chroma subsampling modes (e.g., `TJSAMP_444`, `TJSAMP_420`). ### Color Spaces (TJCS_*) Constants defining color spaces (e.g., `TJCS_RGB`, `TJCS_YCbCr`). ### Precision (TJPRECISION_*) Constants for JPEG precision (e.g., `TJPRECISION_8`, `TJPRECISION_12`). ### Decompression Flags (TJFLAG_*) Flags to control decompression behavior (e.g., `TJFLAG_FASTDCT`, `TJFLAG_ACCURATEDCT`). ### Transform Operations (TJXOP_*) Operations that can be performed during image transforms (e.g., `TJXOP_CROP`, `TJXOP_TRANSPOSE`). ### Transform Options (TJXOPT_*) Options for image transformations (e.g., `TJXOPT_CROP`, `TJXOPT_GRAY`). ### Initialization Types (TJINIT_*) Types of initialization for the TurboJPEG instance (e.g., `TJINIT_DYNAMIC`, `TJINIT_STATIC`). ### Error Codes (TJERR_*) Error codes returned by the underlying TurboJPEG library. ### TJ3 Parameters (TJPARAM_*) Parameters specific to the TJ3 API for fine-grained control. ### Usage Examples Examples demonstrating the usage of these constants are available in `constants.md`. ``` -------------------------------- ### Optimize JPEG File Size with Chroma Subsampling Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/usage-patterns.md Encodes an image using different chroma subsampling formats (4:4:4, 4:2:2, 4:2:0) and prints the resulting byte sizes. Demonstrates how subsampling affects file size. ```python from turbojpeg import TurboJPEG, TJSAMP_420, TJSAMP_422, TJSAMP_444 import numpy as np jpeg = TurboJPEG() img = np.random.randint(0, 256, (480, 640, 3), dtype=np.uint8) # Maximum quality (4:4:4) max_q = jpeg.encode(img, jpeg_subsample=TJSAMP_444) print(f'4:4:4: {len(max_q)} bytes') # Balanced (4:2:2) balanced = jpeg.encode(img, jpeg_subsample=TJSAMP_422) print(f'4:2:2: {len(balanced)} bytes') # Smaller file (4:2:0) small = jpeg.encode(img, jpeg_subsample=TJSAMP_420) print(f'4:2:0: {len(small)} bytes') ``` -------------------------------- ### Optimize Huffman Tables Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/usage-patterns.md Optimizes the Huffman tables of a JPEG image without any loss in quality, potentially reducing file size. ```python from turbojpeg import TurboJPEG jpeg = TurboJPEG() with open('image.jpg', 'rb') as f: jpeg_data = f.read() # Optimize without quality loss optimized = jpeg.optimize(jpeg_data) # Typically smaller, identical pixels print(f'Original: {len(jpeg_data)} bytes') print(f'Optimized: {len(optimized)} bytes') ``` -------------------------------- ### Run All Pytest Tests Source: https://github.com/lilohuang/pyturbojpeg/blob/master/TESTING.md Execute all tests within the project. This is useful for a comprehensive check of the library's functionality. ```bash pytest tests/test_turbojpeg.py -v # Or run all tests in the tests directory pytest tests/ -v ``` -------------------------------- ### Basic Try-Catch for JPEG Decoding Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/errors.md Implement a basic try-catch block to handle potential IOErrors or ValueErrors during JPEG decoding. Logs errors and returns None on failure. ```python from turbojpeg import TurboJPEG import logging jpeg = TurboJPEG() logger = logging.getLogger(__name__) def safe_decode(jpeg_data): """Safely decode JPEG with error handling.""" try: return jpeg.decode(jpeg_data) except IOError as e: logger.error(f'JPEG decoding failed: {e}') return None except ValueError as e: logger.error(f'Invalid parameters: {e}') return None ``` -------------------------------- ### Perform Multiple JPEG Crops Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/api-reference.md Performs multiple crop and/or extension operations on a JPEG image in a single pass. The `crop_parameters` should be a list of (x, y, w, h) tuples. Adjust `background_luminance` for extensions. ```python from turbojpeg import TurboJPEG jpeg = TurboJPEG() with open('image.jpg', 'rb') as f: # Perform 3 crop operations in one pass crops = jpeg.crop_multiple( f.read(), [ (0, 0, 320, 240), # Top-left 320×240 (320, 0, 320, 240), # Top-right 320×240 (0, 240, 640, 240) # Bottom half 640×240 ] ) for i, cropped_data in enumerate(crops): with open(f'crop_{i}.jpg', 'wb') as f: f.write(cropped_data) ``` -------------------------------- ### Multiple Lossless Crops Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/usage-patterns.md Applies multiple lossless crops to a JPEG image, defined by a list of parameters, and saves each cropped region as a separate JPEG file. ```python from turbojpeg import TurboJPEG jpeg = TurboJPEG() with open('image.jpg', 'rb') as f: jpeg_data = f.read() # Define 4 crop regions (2×2 grid) crop_params = [ (0, 0, 320, 240), # Top-left (320, 0, 320, 240), # Top-right (0, 240, 320, 240), # Bottom-left (320, 240, 320, 240) # Bottom-right ] cropped_images = jpeg.crop_multiple(jpeg_data, crop_params) for i, crop_data in enumerate(cropped_images): with open(f'crop_{i}.jpg', 'wb') as f: f.write(crop_data) ``` -------------------------------- ### Batch Encode Images Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/usage-patterns.md Encodes all PNG images in a directory to JPEG format, saving them to an output directory. Requires PIL for image loading. ```python from turbojpeg import TurboJPEG import numpy as np from pathlib import Path jpeg = TurboJPEG() input_dir = Path('images/') output_dir = Path('encoded/') output_dir.mkdir(exist_ok=True) # Process directory of images for img_file in input_dir.glob('*.png'): # Load with PIL from PIL import Image img = np.array(Image.open(img_file)) # Encode jpeg_data = jpeg.encode(img, quality=85) # Save output_path = output_dir / img_file.with_suffix('.jpg').name with open(output_path, 'wb') as f: f.write(jpeg_data) print(f'Encoded {img_file.name}') ``` -------------------------------- ### optimize Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/api-reference.md Losslessly optimizes Huffman tables of a JPEG image, reducing file size without quality loss. Equivalent to `jpegtran -optimize`. ```APIDOC ## optimize ### Description Losslessly optimizes Huffman tables of a JPEG image (equivalent to `jpegtran -optimize`). Reduces file size without quality loss. ### Method `optimize(self, jpeg_buf, copynone=False)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **jpeg_buf** (bytes) - Required - JPEG image data. - **copynone** (bool) - Optional - If True, do not copy EXIF data to output. Defaults to False. ### Request Example ```python from turbojpeg import TurboJPEG jpeg = TurboJPEG() with open('input.jpg', 'rb') as f: optimized = jpeg.optimize(f.read()) with open('optimized.jpg', 'wb') as f: f.write(optimized) print(f'Original size: {len(input_data)}, Optimized: {len(optimized)}') ``` ### Response #### Success Response (200) - **bytes** - Optimized JPEG data, typically smaller. #### Response Example None provided in source. ``` -------------------------------- ### Decode JPEG Data with Speed/Quality Flags Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/configuration.md Shows how to decode JPEG data, with options to use flags for faster decompression at a slight cost to quality, or to scale the output image during decoding. ```python from turbojpeg import TurboJPEG, TJFLAG_FASTUPSAMPLE, TJFLAG_FASTDCT jpeg = TurboJPEG() # Accurate (default, slightly slower) img_accurate = jpeg.decode(jpeg_data) # Fast (lower quality, 2-5% speed gain) img_fast = jpeg.decode(jpeg_data, flags=TJFLAG_FASTUPSAMPLE | TJFLAG_FASTDCT) # With scaling for reduced memory img_quarter = jpeg.decode(jpeg_data, scaling_factor=(1, 4)) ``` -------------------------------- ### Run pytest with memray memory tracking Source: https://github.com/lilohuang/pyturbojpeg/blob/master/TESTING.md Use this command to run all tests with memray memory tracking enabled. This helps in identifying memory leaks during test execution. ```bash pytest tests/test_turbojpeg.py::TestMemoryManagement -v ``` -------------------------------- ### Data Types and Structures Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/MANIFEST.txt Defines the custom data types, structures, and callback signatures used within PyTurboJPEG. ```APIDOC ## Data Types and Structures This section describes the key data structures and type definitions used in PyTurboJPEG. ### ScalingFactor Represents a scaling factor with `numerator` and `denominator` components. ### CroppingRegion Defines a region for cropping with `x`, `y`, `width`, and `height` attributes. ### BackgroundStruct An internal structure used for background processing. ### TransformStruct An internal structure used for transform operations. ### CUSTOMFILTER Callback Defines the signature for custom filter callbacks used during compression/decompression. ### Type Aliases and Signatures Includes type aliases and callable signatures for various functions and methods. ### Pixel Size Mappings Mappings between pixel formats and their sizes in bytes. ### MCU Block Dimensions Dimensions of Minimum Coded Units (MCUs) based on subsampling modes. ### Array Return Types Specifications for array return types, particularly `numpy.ndarray`. ``` -------------------------------- ### Specify Pixel Formats for Decoding and Encoding Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/constants.md Use these constants to define the desired pixel format when decoding images or specifying the input format for encoding. Common formats include RGB, BGR (OpenCV default), and grayscale. ```python from turbojpeg import TurboJPEG, TJPF_BGR, TJPF_GRAY, TJPF_RGB jpeg = TurboJPEG() # Decode to BGR (OpenCV format) img_bgr = jpeg.decode(jpeg_data, pixel_format=TJPF_BGR) # Decode to grayscale img_gray = jpeg.decode(jpeg_data, pixel_format=TJPF_GRAY) # Encode from RGB img_rgb = numpy.random.randint(0, 256, (480, 640, 3), dtype=numpy.uint8) jpeg_data = jpeg.encode(img_rgb, pixel_format=TJPF_RGB) ``` -------------------------------- ### Capture Camera Frames and Encode to JPEG Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/usage-patterns.md Continuously capture frames from a camera, encode them into JPEG format, and save them periodically. Ensure proper release of the camera capture object. ```python from turbojpeg import TurboJPEG import cv2 jpeg = TurboJPEG() cap = cv2.VideoCapture(0) frame_count = 0 try: while True: ret, frame = cap.read() if not ret: break # Encode to JPEG jpeg_data = jpeg.encode(frame, quality=80) # Save or transmit frame_count += 1 if frame_count % 30 == 0: with open(f'frame_{frame_count}.jpg', 'wb') as f: f.write(jpeg_data) finally: cap.release() ``` -------------------------------- ### NotImplementedError Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/errors.md Raised when attempting to use features not available in the currently loaded libjpeg-turbo version. ```APIDOC ## NotImplementedError ### Description Raised when using features not available in the loaded libjpeg-turbo version. ### Raised by: - `get_icc_profile()` - tj3GetICCProfile not available (requires 3.1+) - `encode()` with `icc_profile` parameter - tj3SetICCProfile not available (requires 3.1+) - `set_icc_profile()` - tj3SetICCProfile not available (requires 3.1+) ### Trigger Conditions: - Using ICC profile features with libjpeg-turbo < 3.1 - Using 12/16-bit precision with libjpeg-turbo < 3.0 ### Example: ```python from turbojpeg import TurboJPEG jpeg = TurboJPEG() # NotImplementedError: ICC profile support requires libjpeg-turbo 3.1+ try: icc = jpeg.get_icc_profile(jpeg_data) except NotImplementedError as e: print('ICC profile support requires libjpeg-turbo 3.1 or later') print(f'Details: {e}') ``` ``` -------------------------------- ### Run a Single Specific Test with Pytest Source: https://github.com/lilohuang/pyturbojpeg/blob/master/TESTING.md Execute a single, specific test case. This is ideal for rapid testing during development or when addressing a particular bug. ```bash # Run a single test pytest tests/test_turbojpeg.py::TestDecode::test_decode_basic -v ``` -------------------------------- ### Module Metadata Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/module-reference.md Contains author and version information for the PyTurboJPEG module. This metadata is crucial for package management and identifying the library's version. ```python __author__ = 'Lilo Huang ' __version__ = '2.4.0' ``` -------------------------------- ### Specify TurboJPEG library path on Linux Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/configuration.md Override the default library search path using the LD_LIBRARY_PATH environment variable or explicitly provide the path to the TurboJPEG library when initializing the TurboJPEG object. ```bash # Override library search path export LD_LIBRARY_PATH=/opt/libjpeg-turbo/lib64:$LD_LIBRARY_PATH ``` ```python from turbojpeg import TurboJPEG jpeg = TurboJPEG('/opt/libjpeg-turbo/lib64/libturbojpeg.so') ``` -------------------------------- ### Calculate JPEG Buffer Size Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/configuration.md Calculates the required buffer size for JPEG encoding using the `buffer_size` method. It shows how to determine the size for both worst-case scenarios (e.g., TJSAMP_444) and typical cases (e.g., TJSAMP_422), which is crucial for pre-allocating memory efficiently. ```python from turbojpeg import TurboJPEG import numpy as np jpeg = TurboJPEG() imag = np.random.randint(0, 256, (1920, 1080, 3), dtype=np.uint8) # Calculate buffer size for worst case (high compression ratio) buffer_size = jpeg.buffer_size(img, jpeg_subsample=TJSAMP_444) print(f'Worst case buffer size: {buffer_size / 1024 / 1024:.1f} MB') # Typical case (4:2:2 subsampling) buffer_size_typical = jpeg.buffer_size(img, jpeg_subsample=TJSAMP_422) print(f'Typical buffer size: {buffer_size_typical / 1024 / 1024:.1f} MB') ``` -------------------------------- ### Read JPEG Image Header Properties Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/usage-patterns.md Extracts and prints the width, height, subsampling format, and colorspace of a JPEG image. Requires 'image.jpg' to be a valid JPEG file. ```python from turbojpeg import TurboJPEG jpeg = TurboJPEG() with open('image.jpg', 'rb') as f: width, height, subsample, colorspace = jpeg.decode_header(f.read()) print(f'Image: {width}×{height}') print(f'Subsampling: {subsample}') print(f'Colorspace: {colorspace}') ``` -------------------------------- ### Type Definitions (ctypes Structures) Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/module-reference.md Structures used for defining scaling factors, cropping regions, and internal parameters. ```APIDOC ## Type Definitions: ### Structure: ScalingFactor - **Description**: Scaling factor with numerator/denominator. - **Location**: turbojpeg.py:201 ### Structure: CroppingRegion - **Description**: Rectangular crop region definition. - **Location**: turbojpeg.py:198 ### Structure: BackgroundStruct - **Description**: Internal: background fill parameters. - **Location**: turbojpeg.py:214 ### Structure: TransformStruct - **Description**: Internal: JPEG transform operation. - **Location**: turbojpeg.py:232 ### CFunctionType: CUSTOMFILTER - **Description**: Internal: custom MCU filter callback. - **Location**: turbojpeg.py:204 ``` -------------------------------- ### Default Library Paths for PyTurboJPEG Source: https://github.com/lilohuang/pyturbojpeg/blob/master/_autodocs/configuration.md Defines default paths for the libturbojpeg library across different operating systems. This dictionary is used by the library to locate the native TurboJPEG implementation. ```python DEFAULT_LIB_PATHS = { 'Darwin': [ '/usr/local/lib/libturbojpeg.dylib', '/usr/local/opt/jpeg-turbo/lib/libturbojpeg.dylib', '/opt/libjpeg-turbo/lib64/libturbojpeg.dylib', '/opt/homebrew/opt/jpeg-turbo/lib/libturbojpeg.dylib' ], 'Linux': [ '/usr/local/lib/libturbojpeg.so.0', '/usr/lib/x86_64-linux-gnu/libturbojpeg.so.0', '/usr/lib/aarch64-linux-gnu/libturbojpeg.so.0', '/usr/lib/libturbojpeg.so.0', '/usr/lib64/libturbojpeg.so.0', '/opt/libjpeg-turbo/lib64/libturbojpeg.so' ], 'FreeBSD': [ '/usr/local/lib/libturbojpeg.so.0', '/usr/local/lib/libturbojpeg.so' ], 'NetBSD': [ '/usr/pkg/lib/libturbojpeg.so.0', '/usr/pkg/lib/libturbojpeg.so' ], 'Windows': [ 'C:/libjpeg-turbo64/bin/turbojpeg.dll' ] } ```