### Initial Development Environment Setup Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Run this script for the first-time setup of the development environment. It creates a virtual environment, installs dependencies, and builds rawpy in editable mode. ```bash bash scripts/setup_dev_env.sh ``` -------------------------------- ### Setup Development Environment with Specific Python Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Set up the development environment using a specific Python version (e.g., 3.12) on Ubuntu. This installs Python via deadsnakes PPA and performs the full setup. ```bash bash scripts/setup_dev_env.sh 3.12 ``` -------------------------------- ### Test Linux Wheel Installation Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Execute the script to test wheel installations on Linux after building them. ```bash .github/scripts/test-linux.sh ``` -------------------------------- ### Install CMake Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Command to install CMake within the virtual environment if it's missing during an editable install. ```bash pip install cmake ``` -------------------------------- ### Install rawpy from source on Linux/macOS Source: https://github.com/letmaik/rawpy/blob/main/README.md Installs rawpy from source after LibRaw has been installed. Requires numpy and cython to be installed first. ```sh git clone https://github.com/letmaik/rawpy cd rawpy pip install numpy cython pip install . ``` -------------------------------- ### Test macOS Wheel Installation Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Execute the script to test wheel installations on macOS after building them. ```bash .github/scripts/test-macos.sh ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Install necessary Python dependencies for development, including build, runtime, testing, and documentation tools. ```bash pip install -r dev-requirements.txt ``` -------------------------------- ### Verify Rawpy Installation Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Verify the installation by importing rawpy and printing its version and the underlying LibRaw library version. ```python import rawpy; print(rawpy.__version__); print(rawpy.libraw_version) ``` -------------------------------- ### Install in Development Mode (Linux) Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Install rawpy in editable mode on Linux after installing system LibRaw development files. ```bash sudo apt-get install libraw-dev pip install -e . ``` -------------------------------- ### Install C++ Compiler (Ubuntu/Debian) Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Command to install the g++ compiler on Ubuntu or Debian-based systems. ```bash sudo apt install g++ ``` -------------------------------- ### Reproduce CI tests with specific Python and NumPy versions Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md These commands guide you through setting up a specific Python version, building artifacts, and testing the sdist against a particular NumPy version, closely mimicking CI conditions. ```bash bash scripts/setup_python.sh 3.12 bash scripts/build_dist.sh bash scripts/test_dist.sh sdist 2.0.2 ``` -------------------------------- ### Test Windows Wheel Installation Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Execute the PowerShell script to test wheel installations on Windows after building them. ```powershell .github/scripts/test-windows.ps1 ``` -------------------------------- ### Install LibRaw from source on Linux/macOS Source: https://github.com/letmaik/rawpy/blob/main/README.md Builds and installs the LibRaw library from source. This is a prerequisite for installing rawpy from source on Linux if a system version is not available or outdated. For macOS, LibRaw is built as part of the rawpy build. ```sh git clone https://github.com/LibRaw/LibRaw.git libraw git clone https://github.com/LibRaw/LibRaw-cmake.git libraw-cmake cd libraw git checkout 0.20.0 cp -R ../libraw-cmake/* . cmake . sudo make install ``` -------------------------------- ### Test with a specific NumPy version (editable install) Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Switch to a specific NumPy version using `setup_numpy.sh`, activate your virtual environment, and then run pytest. This is useful for debugging issues related to NumPy compatibility. ```bash bash scripts/setup_numpy.sh 2.0.2 source .venv/bin/activate pytest test/test_mypy.py -v bash scripts/setup_numpy.sh 2.2.6 ``` -------------------------------- ### Install rawpy using pip Source: https://github.com/letmaik/rawpy/blob/main/README.md Installs the stable version of rawpy using pip. Binary wheels are provided for Linux, macOS, and Windows. ```sh pip install rawpy ``` -------------------------------- ### Low-level wheel build Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md This command replicates the low-level wheel building process used in CI. It builds wheels for the current project without installing dependencies from PyPI, using `--no-deps`. ```bash pip wheel . --wheel-dir dist --no-deps ``` -------------------------------- ### Test with a specific Python version (editable install) Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Set up your development environment for a specific Python version using `setup_dev_env.sh`, activate the environment, and then run pytest to test against that Python version. ```bash bash scripts/setup_dev_env.sh 3.12 source .venv/bin/activate pytest test/ -v ``` -------------------------------- ### Install in Development Mode (macOS/Windows) Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Install rawpy in editable mode. This process automatically builds LibRaw from source and compiles the Cython extension. ```bash pip install -e . ``` -------------------------------- ### Install rawpy pre-release using pip Source: https://github.com/letmaik/rawpy/blob/main/README.md Installs a pre-release version of rawpy, which is built against a recent LibRaw snapshot. Use this if you need the latest features or bug fixes. ```sh pip install --pre rawpy ``` -------------------------------- ### Install C++ Compiler (macOS) Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Command to install the C++ compiler (clang) on macOS using Xcode command line tools. ```bash xcode-select --install ``` -------------------------------- ### RawPy Class Source: https://github.com/letmaik/rawpy/blob/main/docs/api/index.md The main entry point to start working with RAW images. It returns a rawpy.RawPy object on which all further operations have to be performed. ```APIDOC ## RawPy Class ### Description The main entry point to start working with RAW images. It returns a `rawpy.RawPy` object on which all further operations have to be performed. ### Usage ```python import rawpy # Example of opening a RAW image with rawpy.imread('path/to/your/image.raw') as raw: # Perform operations on the raw object rgb = raw.postprocess() ``` ### Methods Refer to the [Classes](classes.md#rawpy) documentation for a full list of methods and attributes. ``` -------------------------------- ### Configure ldconfig on Linux Source: https://github.com/letmaik/rawpy/blob/main/README.md Adds the local library path to the system's library search path and updates the library cache. This is necessary on some Linux distributions if LibRaw was installed manually to '/usr/local/lib' and rawpy cannot be found. ```sh echo "/usr/local/lib" | sudo tee /etc/ld.so.conf.d/99local.conf sudo ldconfig ``` -------------------------------- ### Avoid Multiprocessing Deadlocks with Rawpy on Linux Source: https://github.com/letmaik/rawpy/blob/main/README.md When using Python's multiprocessing on Linux with rawpy, use the 'spawn' or 'forkserver' start method instead of the default 'fork' to prevent deadlocks caused by OpenMP interactions. This method must be set once within an 'if __name__ == "__main__":' guard. ```python import multiprocessing as mp import rawpy def process_raw(filename): with rawpy.imread(filename) as raw: rgb = raw.postprocess() return rgb if __name__ == '__main__': # Set the start method to 'spawn' before creating any processes mp.set_start_method('spawn') with mp.Pool(processes=4) as pool: results = pool.map(process_raw, ['image1.nef', 'image2.nef']) ``` -------------------------------- ### Build and Serve Documentation Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Commands to build Sphinx documentation and serve it locally using Python's http.server. Ensure the Cython extension is compiled before building docs. ```bash cd docs && sphinx-build -b html . _build/html ``` ```bash cd docs/_build/html && python -m http.server 8765 ``` -------------------------------- ### Serve and View Documentation Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Serve the built HTML documentation using Python's http.server and view it in a web browser. Access it at http://localhost:8765. ```bash cd docs/_build/html && python -m http.server 8765 ``` -------------------------------- ### Build Documentation Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Build the HTML documentation for the project using Sphinx. Navigate to the docs directory and run the build command. ```bash cd docs && sphinx-build -b html . _build/html ``` -------------------------------- ### Using AMAZE Demosaic Algorithm Source: https://context7.com/letmaik/rawpy/llms.txt Demonstrates how to use the AMAZE demosaic algorithm with rawpy. Requires GPL3. Raises NotSupportedError if AMAZE is unavailable. ```python try: rawpy.DemosaicAlgorithm.AMAZE.checkSupported() with rawpy.imread("photo.nef") as raw: rgb_amaze = raw.postprocess(demosaic_algorithm=rawpy.DemosaicAlgorithm.AMAZE) except rawpy.NotSupportedError as e: print(f"AMAZE not available: {e}") ``` -------------------------------- ### Build Documentation Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Build the Sphinx documentation. The output will be placed in the 'dist-docs/' directory. ```bash sphinx-build -b html docs dist-docs ``` -------------------------------- ### Build rawpy from source on Windows Source: https://github.com/letmaik/rawpy/blob/main/README.md Experimental instructions for building rawpy from source on Windows using PowerShell. Requires Visual Studio and Python. This is generally not needed as wheels are available on PyPI. ```powershell $env:PYTHON_VERSION = '3.12' $env:PYTHON_ARCH = 'x86_64' git clone https://github.com/letmaik/rawpy cd rawpy git submodule update --init .github/scripts/build-windows.ps1 ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Serve the generated HTML documentation locally using Python's built-in HTTP server. Access it via http://localhost:8000. ```bash python -m http.server --directory dist-docs 8000 ``` -------------------------------- ### Selecting Demosaic Algorithm Source: https://context7.com/letmaik/rawpy/llms.txt Lists available demosaic algorithms and demonstrates how to select a specific algorithm, such as DHT for high-quality, GPL-free processing, during image postprocessing. The `isSupported` attribute checks runtime compatibility. ```python import rawpy # List all available demosaic algorithms and check runtime support for algo in rawpy.DemosaicAlgorithm: supported = algo.isSupported status = "✓" if supported else ("?" if supported is None else "✗") print(f" {status} {algo.name} (value={algo.value})") # Use DHT (high-quality, built-in, no GPL required) with rawpy.imread("photo.nef") as raw: rgb_dht = raw.postprocess( demosaic_algorithm=rawpy.DemosaicAlgorithm.DHT, use_camera_wb=True, output_bps=16, ) ``` -------------------------------- ### Stream Build Output with tee Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Redirect build output to a file and display it simultaneously using 'tee'. Useful for inspecting build logs for errors. ```bash mkdir -p tmp bash scripts/build_dist.sh 2>&1 | tee tmp/build.log ``` ```bash grep -i error tmp/build.log ``` ```bash tail -30 tmp/build.log ``` -------------------------------- ### Test wheel with System Libraw Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Builds and tests the wheel package using a system-installed LibRaw library. Requires LibRaw >= 0.21. The env var is needed at both build and test time for wheels. ```bash RAWPY_USE_SYSTEM_LIBRAW=1 bash scripts/build_dist.sh && RAWPY_USE_SYSTEM_LIBRAW=1 bash scripts/test_dist.sh wheel ``` -------------------------------- ### Initialize Git Submodules Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Command to initialize and update git submodules, necessary for resolving 'libraw.h' not found errors. ```bash git submodule update --init --recursive ``` -------------------------------- ### NotSupportedError Source: https://github.com/letmaik/rawpy/blob/main/docs/api/exceptions.md `rawpy.NotSupportedError` is raised if a feature of LibRaw is used that was not enabled during the LibRaw library build, for example demosaic algorithms that are part of the GPL2/GPL3 packs. ```APIDOC ## NotSupportedError `rawpy.NotSupportedError` is raised if a feature of LibRaw is used that was not enabled during the LibRaw library build, for example demosaic algorithms that are part of the GPL2/GPL3 packs. ``` -------------------------------- ### Quick Sanity Check Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Run a quick sanity check script to verify the development environment and basic project functionality. ```bash bash scripts/dev_check.sh ``` -------------------------------- ### Load and Postprocess RAW Image (Default Parameters) Source: https://github.com/letmaik/rawpy/blob/main/README.md Loads a RAW file and saves the postprocessed image using default parameters. Ensure you have a RAW file named 'image.nef' in the same directory. ```python import rawpy import imageio.v3 as iio path = 'image.nef' with rawpy.imread(path) as raw: rgb = raw.postprocess() iio.imwrite('default.tiff', rgb) ``` -------------------------------- ### Accessing Camera Color Properties Source: https://context7.com/letmaik/rawpy/llms.txt Demonstrates how to access and print camera color metadata such as color description, number of colors, color matrices, and tone curves. Requires a RAW image file. ```python import rawpy import numpy as np with rawpy.imread("photo.nef") as raw: print("Color desc :", raw.color_desc) # b'RGBG' print("Num colors :", raw.num_colors) # 3 or 4 # 3×4 color matrix (camera RGB → sRGB) print("Color matrix:\n", raw.color_matrix) # 4×3 camera RGB → XYZ matrix (last row is zero for RGB cameras) print("RGB→XYZ:\n", raw.rgb_xyz_matrix) # Tone curve (length 65536, read from file for Nikon/Sony) tc = raw.tone_curve print(f"Tone curve range: {tc.min()} – {tc.max()}") # Check for stacked (Foveon/sRAW) vs flat (Bayer) sensor if raw.raw_type == rawpy.RawType.Flat: print("Bayer pattern:", raw.raw_pattern) else: print("Stacked/sRAW image") ``` -------------------------------- ### Test with System Libraw Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Build and test distribution packages using a system-installed LibRaw library. This requires LibRaw version 0.21 or newer. ```bash bash scripts/build_dist.sh && RAWPY_USE_SYSTEM_LIBRAW=1 bash scripts/test_dist.sh sdist ``` ```bash RAWPY_USE_SYSTEM_LIBRAW=1 bash scripts/build_dist.sh && RAWPY_USE_SYSTEM_LIBRAW=1 bash scripts/test_dist.sh wheel ``` -------------------------------- ### Build macOS Wheels Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Execute the script to build wheels for macOS. ```bash .github/scripts/build-macos.sh ``` -------------------------------- ### Create and Push Release Tag Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Create a Git tag for the release and push it to the remote repository, including all tags. ```bash git tag vX.Y.Z # e.g., v0.26.0 git push origin main --tags ``` -------------------------------- ### Configure postprocessing with rawpy.Params Source: https://context7.com/letmaik/rawpy/llms.txt Use `rawpy.Params` to create a reusable configuration object for postprocessing. This allows for consistent application of settings like demosaic algorithm, color space, and noise reduction across multiple images. ```python import rawpy # Build a reusable high-quality preset hq_params = rawpy.Params( demosaic_algorithm=rawpy.DemosaicAlgorithm.DHT, use_camera_wb=True, output_color=rawpy.ColorSpace.Adobe, output_bps=16, no_auto_bright=True, highlight_mode=rawpy.HighlightMode.Blend, median_filter_passes=1, fbdd_noise_reduction=rawpy.FBDDNoiseReductionMode.Light, chromatic_aberration=(0.999, 1.001), # slight red/blue scale correction ) files = ["frame1.nef", "frame2.nef", "frame3.nef"] import imageio.v3 as iio for path in files: with rawpy.imread(path) as raw: rgb = raw.postprocess(hq_params) iio.imwrite(path.replace(".nef", ".tiff"), rgb) ``` -------------------------------- ### Test sdist with System Libraw Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Builds and tests the sdist package using a system-installed LibRaw library. Requires LibRaw >= 0.21. Note: RAWPY_USE_SYSTEM_LIBRAW is only needed at install/test time for sdist. ```bash bash scripts/build_dist.sh && RAWPY_USE_SYSTEM_LIBRAW=1 bash scripts/test_dist.sh sdist ``` -------------------------------- ### Build Windows Wheels Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Execute the PowerShell script to build wheels for Windows. ```powershell .github/scripts/build-windows.ps1 ``` -------------------------------- ### Test Built wheel Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Tests the wheel package after it has been built. Use 'wheel' as the argument to specify the package type. ```bash bash scripts/test_dist.sh wheel ``` -------------------------------- ### Setting Output Color Space and Bit Depth Source: https://context7.com/letmaik/rawpy/llms.txt Shows how to specify the output color space (sRGB, Adobe RGB, ProPhoto RGB, XYZ) and bit depth (8 or 16) using rawpy.postprocess. ```python import rawpy import imageio.v3 as iio with rawpy.imread("photo.nef") as raw: # sRGB 8-bit (most compatible for web/display) rgb_srgb = raw.postprocess(use_camera_wb=True, output_color=rawpy.ColorSpace.sRGB) # Adobe RGB 16-bit for print workflows rgb_adobe = raw.postprocess( use_camera_wb=True, output_color=rawpy.ColorSpace.Adobe, output_bps=16, ) # ProPhoto RGB 16-bit for maximum gamut (e.g., Lightroom-compatible) rgb_prophoto = raw.postprocess( use_camera_wb=True, output_color=rawpy.ColorSpace.ProPhoto, output_bps=16, gamma=(1.8, 0), # ProPhoto uses 1.8 gamma ) # Linear XYZ for scientific analysis rgb_xyz = raw.postprocess( use_camera_wb=True, output_color=rawpy.ColorSpace.XYZ, output_bps=16, gamma=(1, 1), no_auto_bright=True, ) iio.imwrite("xyz_linear.tiff", rgb_xyz) ``` -------------------------------- ### Activate Virtual Environment Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Activate the project's virtual environment for subsequent development sessions. This command should be run in your terminal. ```bash source .venv/bin/activate ``` -------------------------------- ### Initialize Git Submodules Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Ensure all git submodules, including external libraries like LibRaw, are properly initialized and updated. This is a prerequisite for building Rawpy. ```bash git submodule update --init ``` -------------------------------- ### Build Distribution Packages Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Use this script to build both source distribution (sdist) and wheel packages for rawpy. This is essential for creating distributable artifacts. ```bash bash scripts/build_dist.sh ``` -------------------------------- ### Build without isolation for local development Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md For faster local development, build the package without isolation. This reuses the current virtual environment but may not perfectly reflect CI build conditions. ```bash pip install --no-build-isolation -e . ``` -------------------------------- ### Build Linux Wheels Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Execute the script to build wheels for Linux. This is typically done inside a manylinux container. ```bash .github/scripts/build-linux.sh ``` -------------------------------- ### Run Specific Test File Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Execute tests only from a specific file, such as 'test_basic.py'. ```bash pytest test/test_basic.py ``` -------------------------------- ### Build Distribution Artifacts Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Scripts to build source distributions (sdist) and wheels for the project. These are used to test the final packaged output. ```bash bash scripts/build_dist.sh ``` ```bash bash scripts/test_dist.sh sdist ``` ```bash bash scripts/test_dist.sh wheel ``` ```bash bash scripts/test_dist.sh sdist 2.0.2 ``` ```bash bash scripts/setup_python.sh 3.12 bash scripts/build_dist.sh bash scripts/test_dist.sh sdist ``` -------------------------------- ### Manage White Balance Settings with RawPy Source: https://context7.com/letmaik/rawpy/llms.txt Accesses and applies white balance multipliers. Exposes as-shot, daylight reference, and applied multipliers. Allows custom white balance settings during postprocessing. ```python import rawpy with rawpy.imread("photo.nef") as raw: print("Camera WB :", raw.camera_whitebalance) # [2.11, 1.0, 1.52, 1.0] print("Daylight WB:", raw.daylight_whitebalance) # [2.40, 1.0, 1.35, 1.0] # Run postprocess with camera white balance rgb = raw.postprocess(use_camera_wb=True) # Retrieve the multipliers actually used (available after postprocess) print("Applied WB :", raw.auto_whitebalance) # [2.11, 1.0, 1.52, 1.0] # Custom white balance: manually supply RGBG multipliers rgb_custom = raw.postprocess(user_wb=[2.0, 1.0, 1.8, 1.0]) ``` -------------------------------- ### Test Distribution Packages Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Test the built sdist or wheel packages. Specify 'sdist' or 'wheel' as the argument. Optionally, provide a specific numpy version to test against. ```bash bash scripts/test_dist.sh sdist ``` ```bash bash scripts/test_dist.sh wheel ``` ```bash bash scripts/test_dist.sh wheel 2.0.2 ``` -------------------------------- ### Open RAW file and postprocess with rawpy.imread Source: https://context7.com/letmaik/rawpy/llms.txt Use `rawpy.imread` as a context manager to open RAW files from paths or file-like objects. It returns a RawPy object ready for postprocessing. The `shot_select` parameter can be used for multi-image RAW files. ```python import rawpy import imageio.v3 as iio # Open from file path and postprocess with default settings with rawpy.imread("photo.nef") as raw: print(raw.raw_type) # RawType.Flat print(raw.sizes) # ImageSizes(raw_height=2844, raw_width=4284, ...) rgb = raw.postprocess() # ndarray of shape (h, w, 3), dtype uint8 iio.imwrite("output.tiff", rgb) # Open from a file-like object (e.g., bytes from network/cloud storage) with open("photo.cr2", "rb") as f: with rawpy.imread(f) as raw: rgb = raw.postprocess() # Select the second image from a Dual-Pixel RAW with rawpy.imread("dualp.nef", shot_select=1) as raw: rgb = raw.postprocess() iio.imwrite("second_shot.tiff", rgb) ``` -------------------------------- ### rawpy.imread Source: https://context7.com/letmaik/rawpy/llms.txt Opens a RAW file from a path or file-like object and returns a RawPy object ready for postprocessing. It should be used as a context manager. ```APIDOC ## rawpy.imread(pathOrFile, shot_select=0) — Open a RAW file as a RawPy object Convenience function that constructs a `RawPy` instance, opens the given file path or file-like object, and returns it ready for postprocessing. It is the standard entry point for all rawpy workflows and should be used as a context manager to ensure resources are released. ### Parameters #### Path Parameters - **pathOrFile** (string or file-like object) - Required - The path to the RAW file or a file-like object. - **shot_select** (int) - Optional - Defaults to 0. Selects which image to process from multi-image files (e.g., Dual-Pixel RAW). ### Request Example ```python import rawpy import imageio.v3 as iio # Open from file path and postprocess with default settings with rawpy.imread("photo.nef") as raw: print(raw.raw_type) # RawType.Flat print(raw.sizes) # ImageSizes(raw_height=2844, raw_width=4284, ...) rgb = raw.postprocess() # ndarray of shape (h, w, 3), dtype uint8 iio.imwrite("output.tiff", rgb) # Open from a file-like object (e.g., bytes from network/cloud storage) with open("photo.cr2", "rb") as f: with rawpy.imread(f) as raw: rgb = raw.postprocess() # Select the second image from a Dual-Pixel RAW with rawpy.imread("dualp.nef", shot_select=1) as raw: rgb = raw.postprocess() iio.imwrite("second_shot.tiff", rgb) ``` ### Response #### Success Response - **RawPy object** - An instance of the RawPy class, ready for postprocessing. ``` -------------------------------- ### Color and matrix properties Source: https://context7.com/letmaik/rawpy/llms.txt Access camera color pipeline metadata including color description, color matrix, RGB to XYZ matrix, and tone curve. ```APIDOC ## Color and matrix properties ### Description These properties expose the camera's color pipeline metadata: the color filter description string, the sensor-to-XYZ conversion matrix, and the camera's embedded tone curve (available for Nikon, Sony, and some other brands). ### Usage ```python import rawpy import numpy as np with rawpy.imread("photo.nef") as raw: print("Color desc :", raw.color_desc) # b'RGBG' print("Num colors :", raw.num_colors) # 3 or 4 # 3x4 color matrix (camera RGB -> sRGB) print("Color matrix:\n", raw.color_matrix) # 4x3 camera RGB -> XYZ matrix (last row is zero for RGB cameras) print("RGB->XYZ:\n", raw.rgb_xyz_matrix) # Tone curve (length 65536, read from file for Nikon/Sony) tc = raw.tone_curve print(f"Tone curve range: {tc.min()} – {tc.max()}") # Check for stacked (Foveon/sRAW) vs flat (Bayer) sensor if raw.raw_type == rawpy.RawType.Flat: print("Bayer pattern:", raw.raw_pattern) else: print("Stacked/sRAW image") ``` ``` -------------------------------- ### Test Built sdist Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Tests the source distribution (sdist) package after it has been built. Use 'sdist' as the argument to specify the package type. ```bash bash scripts/test_dist.sh sdist ``` -------------------------------- ### Clone Rawpy Repository Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Clone the rawpy repository and its submodules, including the LibRaw library. Navigate into the cloned directory. ```bash git clone https://github.com/letmaik/rawpy.git cd rawpy git submodule update --init ``` -------------------------------- ### rawpy.Params Source: https://context7.com/letmaik/rawpy/llms.txt A container for all LibRaw postprocessing options, allowing for reusable parameter sets. ```APIDOC ## rawpy.Params(...) — Postprocessing parameter container A dataclass-like object that encapsulates every LibRaw postprocessing option. An instance can be constructed once and reused across multiple `postprocess()` calls or passed directly. All parameters are optional and fall back to LibRaw defaults. ### Parameters All parameters are optional and correspond to LibRaw options. Examples include: - **demosaic_algorithm** (rawpy.DemosaicAlgorithm) - The demosaicing algorithm. - **use_camera_wb** (bool) - Use camera white balance. - **output_color** (rawpy.ColorSpace) - The output color space. - **output_bps** (int) - Output bits per pixel (8 or 16). - **no_auto_bright** (bool) - Disable automatic brightness adjustment. - **highlight_mode** (rawpy.HighlightMode) - Highlight reconstruction mode. - **median_filter_passes** (int) - Number of median filter passes. - **fbdd_noise_reduction** (rawpy.FBDDNoiseReductionMode) - FBDD noise reduction mode. - **chromatic_aberration** (tuple) - Chromatic aberration correction factors. ### Request Example ```python import rawpy # Build a reusable high-quality preset hq_params = rawpy.Params( demosaic_algorithm=rawpy.DemosaicAlgorithm.DHT, use_camera_wb=True, output_color=rawpy.ColorSpace.Adobe, output_bps=16, no_auto_bright=True, highlight_mode=rawpy.HighlightMode.Blend, median_filter_passes=1, fbdd_noise_reduction=rawpy.FBDDNoiseReductionMode.Light, chromatic_aberration=(0.999, 1.001), # slight red/blue scale correction ) files = ["frame1.nef", "frame2.nef", "frame3.nef"] import imageio.v3 as iio for path in files: with rawpy.imread(path) as raw: rgb = raw.postprocess(hq_params) iio.imwrite(path.replace(".nef", ".tiff"), rgb) ``` ### Response #### Success Response - **rawpy.Params object** - An instance of the Params class with the specified settings. ``` -------------------------------- ### Run All Tests Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Execute all tests in the 'test/' directory using pytest. ```bash pytest test/ ``` -------------------------------- ### Rebuild Rawpy After .pyx/C++ Changes Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Run this script to recompile Cython (.pyx) or C++ files after making edits. This ensures changes are reflected in the build. ```bash bash scripts/rebuild.sh ``` -------------------------------- ### Postprocess RAW image with RawPy.postprocess Source: https://context7.com/letmaik/rawpy/llms.txt The `postprocess` method runs the LibRaw pipeline to produce an RGB NumPy array. Parameters can be passed as keyword arguments or a `Params` object. Control output bit depth, color space, white balance, and apply various enhancements. ```python import rawpy with rawpy.imread("photo.nef") as raw: # Default postprocess — 8-bit sRGB, AHD demosaic, camera white balance off rgb_default = raw.postprocess() # 16-bit linear output (no gamma, no auto-brightness) — suitable for HDR work rgb_linear = raw.postprocess(gamma=(1, 1), no_auto_bright=True, output_bps=16) # Use camera white balance, AHD demosaic, 16-bit ProPhoto color space rgb_highq = raw.postprocess( use_camera_wb=True, demosaic_algorithm=rawpy.DemosaicAlgorithm.AHD, output_color=rawpy.ColorSpace.ProPhoto, output_bps=16, ) # Half-size fast preview with auto white balance rgb_preview = raw.postprocess(half_size=True, use_auto_wb=True) # Highlight reconstruction + 2-stop exposure increase rgb_exposed = raw.postprocess( use_camera_wb=True, highlight_mode=rawpy.HighlightMode.Reconstruct(5), exp_shift=4.0, # 2 stops brighter (linear scale) exp_preserve_highlights=1.0, ) ``` -------------------------------- ### White balance properties Source: https://context7.com/letmaik/rawpy/llms.txt Accesses white-balance multipliers. Properties include `camera_whitebalance` (as-shot multipliers), `daylight_whitebalance` (daylight reference), and `auto_whitebalance` (multipliers used in the last `postprocess()` call). Custom multipliers can also be supplied. ```APIDOC ## White balance properties — `camera_whitebalance`, `daylight_whitebalance`, `auto_whitebalance` ### Description Three properties expose the white-balance multipliers associated with a RAW file. `camera_whitebalance` gives the as-shot multipliers stored in the file; `daylight_whitebalance` gives a daylight reference; `auto_whitebalance` returns the multipliers that were actually applied during the most recent `postprocess()` call. ### Method ```python import rawpy with rawpy.imread("photo.nef") as raw: print("Camera WB :", raw.camera_whitebalance) # [2.11, 1.0, 1.52, 1.0] print("Daylight WB:", raw.daylight_whitebalance) # [2.40, 1.0, 1.35, 1.0] # Run postprocess with camera white balance rgb = raw.postprocess(use_camera_wb=True) # Retrieve the multipliers actually used (available after postprocess) print("Applied WB :", raw.auto_whitebalance) # [2.11, 1.0, 1.52, 1.0] # Custom white balance: manually supply RGBG multipliers rgb_custom = raw.postprocess(user_wb=[2.0, 1.0, 1.8, 1.0]) ``` ``` -------------------------------- ### Controlling Highlight Clipping and Recovery Source: https://context7.com/letmaik/rawpy/llms.txt Illustrates different highlight recovery modes using rawpy's HighlightMode enum. Modes include Clip, Blend, and Reconstruct with adjustable levels. ```python import rawpy import imageio.v3 as iio with rawpy.imread("high_contrast.nef") as raw: # Clip highlights (default) rgb_clip = raw.postprocess(use_camera_wb=True, highlight_mode=rawpy.HighlightMode.Clip) iio.imwrite("clip.tiff", rgb_clip) # Blend clipped and unclipped channels rgb_blend = raw.postprocess(use_camera_wb=True, highlight_mode=rawpy.HighlightMode.Blend) iio.imwrite("blend.tiff", rgb_blend) # Full reconstruction, level 5 (balanced) rgb_recon = raw.postprocess( use_camera_wb=True, highlight_mode=rawpy.HighlightMode.Reconstruct(5), ) iio.imwrite("reconstruct.tiff", rgb_recon) ``` -------------------------------- ### DemosaicAlgorithm enum Source: https://context7.com/letmaik/rawpy/llms.txt Enumerates all LibRaw-supported demosaic algorithms and allows checking their runtime support. ```APIDOC ## DemosaicAlgorithm enum ### Description Enumerates all LibRaw-supported demosaic algorithms. GPL2/GPL3 algorithms require a special build. `isSupported` and `checkSupported()` query at runtime whether the current LibRaw binary was compiled with the relevant pack. ### Usage ```python import rawpy # List all available demosaic algorithms and check runtime support for algo in rawpy.DemosaicAlgorithm: supported = algo.isSupported status = "✓" if supported else ("?" if supported is None else "✗") print(f" {status} {algo.name} (value={algo.value})") # Use DHT (high-quality, built-in, no GPL required) with rawpy.imread("photo.nef") as raw: rgb_dht = raw.postprocess( demosaic_algorithm=rawpy.DemosaicAlgorithm.DHT, use_camera_wb=True, output_bps=16, ) ``` ``` -------------------------------- ### Switch Numpy Version Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Use this script to switch to a specific version of NumPy for testing or development purposes. ```bash bash scripts/setup_numpy.sh 2.0.2 ``` -------------------------------- ### Find and Repair Bad Pixels Across Multiple RAW Files Source: https://github.com/letmaik/rawpy/blob/main/README.md Identifies bad pixels using multiple RAW files and then repairs them in each file using a median method. Requires 'image1.nef', 'image2.nef', and 'image3.nef'. ```python import rawpy.enhance paths = ['image1.nef', 'image2.nef', 'image3.nef'] bad_pixels = rawpy.enhance.find_bad_pixels(paths) for path in paths: with rawpy.imread(path) as raw: rawpy.enhance.repair_bad_pixels(raw, bad_pixels, method='median') rgb = raw.postprocess() iio.imwrite(path + '.tiff', rgb) ``` -------------------------------- ### LibRawFatalError Source: https://github.com/letmaik/rawpy/blob/main/docs/api/exceptions.md The following error types are subtypes of `rawpy.LibRawFatalError`. ```APIDOC ## LibRawFatalError The following error types are subtypes of `rawpy.LibRawFatalError`: ``` -------------------------------- ### Update Version Number for Pre-release Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Modify the __version__ string in rawpy/_version.py to reflect an alpha or beta pre-release. Use 'a' for alpha and 'b' for beta, followed by a build number. ```python __version__ = "X.Y.Za1" # Alpha pre-release (e.g., "0.26.0a1") # or __version__ = "X.Y.Zb1" # Beta pre-release (e.g., "0.26.0b1") ``` -------------------------------- ### RawPy.postprocess Source: https://context7.com/letmaik/rawpy/llms.txt Demosaics and postprocesses the RAW image using the LibRaw pipeline, returning an RGB NumPy array. Parameters can be provided as a Params object or keyword arguments. ```APIDOC ## RawPy.postprocess(params=None, **kw) — Demosaic and postprocess the RAW image Runs the full LibRaw postprocessing pipeline and returns a NumPy RGB array. Parameters can be supplied either as a `Params` object or as keyword arguments. Returns an `ndarray` of shape `(height, width, 3)` with dtype `uint8` (8-bit) or `uint16` (16-bit when `output_bps=16`). ### Parameters #### Path Parameters - **params** (rawpy.Params) - Optional - A `Params` object containing postprocessing settings. #### Keyword Arguments (**kw**) - **gamma** (tuple) - Optional - Gamma correction. Defaults to `(2.2, 4.5)`. - **no_auto_bright** (bool) - Optional - If True, disables automatic brightness adjustment. Defaults to False. - **output_bps** (int) - Optional - Output bits per pixel. Can be 8 or 16. Defaults to 8. - **use_camera_wb** (bool) - Optional - If True, uses the camera's white balance. Defaults to False. - **demosaic_algorithm** (rawpy.DemosaicAlgorithm) - Optional - The demosaicing algorithm to use. - **output_color** (rawpy.ColorSpace) - Optional - The output color space. - **half_size** (bool) - Optional - If True, processes the image at half size for a faster preview. - **use_auto_wb** (bool) - Optional - If True, uses automatic white balance. - **highlight_mode** (rawpy.HighlightMode) - Optional - Controls highlight reconstruction. - **exp_shift** (float) - Optional - Exposure shift in stops (linear scale). - **exp_preserve_highlights** (float) - Optional - Controls highlight preservation during exposure adjustments. ### Request Example ```python import rawpy with rawpy.imread("photo.nef") as raw: # Default postprocess — 8-bit sRGB, AHD demosaic, camera white balance off rgb_default = raw.postprocess() # 16-bit linear output (no gamma, no auto-brightness) — suitable for HDR work rgb_linear = raw.postprocess(gamma=(1, 1), no_auto_bright=True, output_bps=16) # Use camera white balance, AHD demosaic, 16-bit ProPhoto color space rgb_highq = raw.postprocess( use_camera_wb=True, demosaic_algorithm=rawpy.DemosaicAlgorithm.AHD, output_color=rawpy.ColorSpace.ProPhoto, output_bps=16, ) # Half-size fast preview with auto white balance rgb_preview = raw.postprocess(half_size=True, use_auto_wb=True) # Highlight reconstruction + 2-stop exposure increase rgb_exposed = raw.postprocess( use_camera_wb=True, highlight_mode=rawpy.HighlightMode.Reconstruct(5), exp_shift=4.0, # 2 stops brighter (linear scale) exp_preserve_highlights=1.0, ) ``` ### Response #### Success Response - **ndarray** - A NumPy array representing the processed RGB image. Shape is `(height, width, 3)` and dtype is `uint8` or `uint16`. ``` -------------------------------- ### Read EXIF Shot and Lens Metadata with RawPy Source: https://context7.com/letmaik/rawpy/llms.txt Retrieves EXIF metadata including shooting parameters like ISO, shutter speed, aperture, focal length, and timestamp, as well as camera and lens details. ```python import rawpy with rawpy.imread("photo.nef") as raw: o = raw.other print(f"ISO : {o.iso_speed}") print(f"Shutter speed: {o.shutter_speed} s") print(f"Aperture : f/{o.aperture}") print(f"Focal length : {o.focal_length} mm") print(f"Timestamp : {o.timestamp}") l = raw.lens print(f"Lens make : {l.make}") print(f"Lens model : {l.model}") print(f"Focal range : {l.min_focal}–{l.max_focal} mm") ``` -------------------------------- ### Update LibRaw Submodule Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Fetch the latest changes for the LibRaw submodule and update the git index. This is part of the pre-release process if a newer LibRaw version is desired. ```bash cd external/LibRaw git fetch git checkout main # or a specific commit cd ../.. git add external/LibRaw ``` -------------------------------- ### LibRawNonFatalError Source: https://github.com/letmaik/rawpy/blob/main/docs/api/exceptions.md The following error types are subtypes of `rawpy.LibRawNonFatalError`. ```APIDOC ## LibRawNonFatalError The following error types are subtypes of `rawpy.LibRawNonFatalError`: ``` -------------------------------- ### Run Specific Pytest Tests Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Commands to execute specific tests or groups of tests using pytest. Options include running a single test, matching patterns, or showing print output. ```bash pytest test/test_basic.py::testFileOpenAndPostProcess -v ``` ```bash pytest -k "thumbnail" -v ``` ```bash pytest -s test/test_basic.py ``` -------------------------------- ### Retrieve Image Dimension Metadata with RawPy Source: https://context7.com/letmaik/rawpy/llms.txt Retrieves comprehensive image dimension metadata, including raw sensor frame and processed output image sizes, margins, crop regions, pixel aspect ratio, and flip orientation. ```python import rawpy with rawpy.imread("photo.nef") as raw: s = raw.sizes print(f"Raw dimensions : {s.raw_width} x {s.raw_height}") print(f"Visible dimensions: {s.width} x {s.height}") print(f"Top margin : {s.top_margin}") print(f"Left margin : {s.left_margin}") print(f"Pixel aspect : {s.pixel_aspect}") print(f"Flip : {s.flip}" ) # 0=none, 3=180°, 5=90°CCW, 6=90°CW # Output: # Raw dimensions : 4284 x 2844 # Visible dimensions: 4256 x 2832 # Top margin : 6 # Left margin : 14 # Pixel aspect : 1.0 # Flip : 6 ``` -------------------------------- ### Run Single Pytest Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Execute a single test case using pytest. Specify the test file and function name for targeted testing. ```bash pytest test/test_basic.py::testName -v ``` -------------------------------- ### Update Version Number for Release Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Edit the '_version.py' file to set the new version number for a stable release. ```python __version__ = "X.Y.Z" # e.g., "0.26.0" ``` -------------------------------- ### Fix NumPy ABI Errors Source: https://github.com/letmaik/rawpy/blob/main/AGENTS.md Steps to resolve NumPy ABI compatibility issues by removing the stale C++ file and reinstalling the package in editable mode. ```bash rm rawpy/_rawpy.cpp pip install --no-build-isolation -e . ``` -------------------------------- ### Update LibRaw Submodule for Release Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Update the LibRaw submodule to a specific stable tag. Ensure to add the changes to git staging. ```bash cd external/LibRaw git fetch --tags git checkout 0.21.2 # or desired stable tag cd ../.. git add external/LibRaw ``` -------------------------------- ### Commit Release Changes Source: https://github.com/letmaik/rawpy/blob/main/DEVELOP.md Commit the changes to the version number and potentially the LibRaw submodule. ```bash git add rawpy/_version.py git commit -m "Release vX.Y.Z" ``` -------------------------------- ### Detecting Bad Pixels Source: https://context7.com/letmaik/rawpy/llms.txt Identifies hot and dead pixels across multiple RAW frames from the same camera. Requires `scikit-image` or `OpenCV`. The `confirm_ratio` parameter specifies the minimum percentage of frames a pixel must appear bad in to be confirmed. ```python import rawpy.enhance # Collect several frames from the same camera (shot with movement between them) paths = [ "frame_001.nef", "frame_002.nef", "frame_003.nef", "frame_004.nef", "frame_005.nef", ] # Find hot AND dead pixels; a pixel must appear bad in ≥90% of frames to be confirmed bad_pixels = rawpy.enhance.find_bad_pixels( paths, find_hot=True, find_dead=True, confirm_ratio=0.9, ) print(f"Found {len(bad_pixels)} confirmed bad pixels") # e.g.: Found 37 confirmed bad pixels # bad_pixels shape: (37, 2) — [[y0,x0], [y1,x1], ...] ```