pax_global_header 0000666 0000000 0000000 00000000064 15222163673 0014521 g ustar 00root root 0000000 0000000 52 comment=4bfa9fede868a96462e06a52bf1e0ce0cbb7a891
python-pyvips-3.1.1/ 0000775 0000000 0000000 00000000000 15222163673 0014374 5 ustar 00root root 0000000 0000000 python-pyvips-3.1.1/.github/ 0000775 0000000 0000000 00000000000 15222163673 0015734 5 ustar 00root root 0000000 0000000 python-pyvips-3.1.1/.github/workflows/ 0000775 0000000 0000000 00000000000 15222163673 0017771 5 ustar 00root root 0000000 0000000 python-pyvips-3.1.1/.github/workflows/ci.yml 0000664 0000000 0000000 00000001771 15222163673 0021115 0 ustar 00root root 0000000 0000000 name: CI
on: [push, pull_request]
jobs:
CI:
name: "Linux x64 (Ubuntu 22.04) - Python ${{ matrix.python-version }}"
runs-on: ubuntu-22.04
strategy:
fail-fast: false
matrix:
# Only test supported Python versions:
# https://endoflife.date/python
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14", "pypy3.9"]
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install libvips
run: |
sudo apt-get update
sudo apt-get install --no-install-recommends libvips
- name: Lint with flake8
run: |
pip install flake8
flake8 .
- name: Install tox and any other packages
run: pip install tox
- name: Run tox
# Run tox using the version of Python in `PATH`
run: tox -e py
python-pyvips-3.1.1/.gitignore 0000664 0000000 0000000 00000000157 15222163673 0016367 0 ustar 00root root 0000000 0000000 .pytest_cache
.*.swp
.DS_Store
*.pyc
*.egg-info
*.egg
*.eggs
*.cache
_libvips.*
dist
doc/build
build
.tox
tmp
python-pyvips-3.1.1/CHANGELOG.rst 0000664 0000000 0000000 00000015711 15222163673 0016422 0 ustar 00root root 0000000 0000000 ## Version 3.1.1 (released 9 December 2025)
- fix get_gainmap arguments [jcupitt]
- fix __array__ copy argument test [jcupitt]
- add a test [jcupitt]
## Version 3.1.0 (released 8 December 2025)
- fix glib DLL name with Conan [boussaffawalid]
- update docs for libvips 8.18 [jcupitt]
- add `get_gainmap()` [jcupitt]
- remove redundant `revalidate` flags from docs [kleisauke]
## Version 3.0.0 (released 28 April 2025)
- drop support for Python 2.7, require Python >= 3.7 [kleisauke]
- migrate to `pyproject.toml` [kleisauke]
- fix a small memleak in `write_to_buffer()` [kleisauke]
- add `[binary]` install option [kleisauke]
- add `shutdown()` [jcupitt]
## Version 2.2.3 (released 28 April 2024)
- ensure compatibility with a single shared libvips library [kleisauke]
- add flags_dict(), enum_dict() for better flags introspection
- improve generation of `enums.py`
- add `stream.py` example
- fix a missing reference issue with custom sources
- fix `addalpha` with scrgb images [RiskoZoSlovenska]
- fix macos compat, again [kleisauke]
## Version 2.2.2 (released 4 Jan 2023)
* fix with libvips nodeprecated [kleisauke]
* update README notes for py3.8+ on win [CristiFati]
* fix VipsObect.print_all() [jcupitt]
* add split, join, annotate animation examples [jcupitt]
* work around broken ffi bool type [amtsak]
* flag classes are now integer-valued so you can OR them [jcupitt]
* update docs for 8.15 [jcupitt]
## Version 2.2.1 (released 12 Jun 2022)
* add seek and end handlers for TargetCustom [jcupitt]
* add `block_untrusted_set`, `operation_block_set` [jcupitt]
* update for libvips 8.13 [jcupitt]
## Version 2.2.0 (released 18 Apr 2022)
* `repr()` will print matrix images as matrices [jcupitt]
* more robust bandwise index/slice; added fancy slicing (step != 1) [erdmann]
* fix `im.bandjoin([])`, now returns `im` [erdmann]
* add numpy-style extended indexing (index with list of ints or bools) [erdmann]
* earlier detection of unknown methods and class methods [jcupitt]
* add conversion from Image to numpy array via 'Image.__array__` [erdmann]
* add `Image.fromarray()` for conversion from numpy-ish arrays [erdmann]
* add `invalidate()` [jcupitt]
* add array-like functionality to `Image.new_from_array()` for conversion from
numpy-ish arrays [erdmann]
* add `Image.numpy()` (convenient for method chaining) [erdmann]
* add `tolist()` [erdmann]
* accept `pathlib.Path` objects for filenames (py3 only) [erdmann]
* cache pspec lookups for a 10% speed boost [jcupitt]
## Version 2.1.16 (started 28 Jun 2021)
* fix logging of deprecated args [manthey]
* add shepards example [tourtiere]
* update docs for 8.12 [jcupitt]
* add pagesplit(), pagejoin(), get_page_height(), get_n_pages() [jcupitt]
* add atan2() [jcupitt]
* add `cache_get_max()`, `cache_get_max_mem()`, `cache_get_max_files()`,
`cache_get_size()` [hroskes]
* don't generate docs for deprecated arguments [jcupitt]
* buffer save tries with the target API first [jcupitt]
* add hyperbolic functions `sinh`, `cosh`, `tanh`, `asinh`, `acosh`,
`atanh` [jcupitt]
* add `values_for_flag` [kleisauke]
## Version 2.1.15 (27 Dec 2020)
* better autodocs for enums [int-ua]
* better unreffing if operators fail [kleisauke]
## Version 2.1.14 (18 Dec 2020)
* add `stdio.py` example
* update examples
* improve formatting of enum documentation
* regenerate docs
* remove old `vips_free` declaration, fixing API build on some platforms
[rajasagashe]
## Version 2.1.13 (4 Jul 2020)
* better diagnostics for API mode install failure [kleisauke]
* revise docs [int-ua]
* better reference tracking for new_from_memory [aspadm]
## Version 2.1.12 (17 Feb 2020)
* update enums.py [tony612]
* add gen-enums.py [jcupitt]
* improve custom source/target types [jcupitt]
* revise types for set_blob to fix exception with old libvips [jcupitt]
* fix 32-bit support [dqxpb]
* remove pytest-runner from pipy deps [lgbaldoni]
* add watermark with image example [jcupitt]
## Version 2.1.11 (7 Nov 2019)
* revise README [jcupitt]
* add watermark example [jcupitt]
* fix syntax highlighting in README [favorable-mutation]
* add signal handling [jcupitt]
* add Source / Target support [jcupitt]
* add perf tests [kleisauke]
* speed up Operation.call [kleisauke]
* fix logging [h4l]
## Version 2.1.8 (1 Jul 2019)
* fix regression with py27 [jcupitt]
## Version 2.1.7 (1 Jul 2019)
* prevent exponential growth of reference tables in some cases [NextGuido]
## Version 2.1.6 (7 Jan 2019)
* switch to new-style callbacks [kleisauke]
* add get_suffixes() [jcupitt]
* add Region [jcupitt]
* better handling of NULL strings from ffi [jcupitt]
* add support for dealing with uint64 types [kleisauke]
## Version 2.1.5 (18 Dec 2018)
* better behaviour for new_from_memory fixes some segvs [wppd]
* added addalpha/hasalpha [jcupitt]
## Version 2.1.4 (3 Oct 2018)
* update links for repo move [jcupitt]
* update autodocs for libvips 8.7 [jcupitt]
## Version 2.1.3 (3 March 2018)
* record header version number in binary module and check compatibility with
the library during startup [jcupitt]
* add optional output params to docs [kleisauke]
* update docs [jcupitt]
* add some libvips 8.7 tests [jcupitt]
* move to pytest [kleisauke]
* better handling of many-byte values in py3 new_from_memory [MatthiasKohl]
* better handling of utf-8 i18n text [felixbuenemann]
* add enum introspection [kleisauke]
* move the libvips test suite back to libvips, just test pyvips here [jcupitt]
* fix five small memleaks [kleisauke]
## Version 2.1.2 (1 March 2018)
* only use get_fields on libvips 8.5+ [rebkwok]
* only use parent_instance on libvips 8.4+ [rebkwok]
* relative import for decl
## Version 2.1.1 (25 February 2018)
* switch to sdist
* better ABI mode fallback behaviour
## Version 2.1.0 (17 November 2017)
* support cffi API mode as well: much faster startup, about 20% faster on the
test suite [jcupitt]
* on install, it tries to build a binary interface, and if that fails, falls
back to ABI mode [jcupitt]
* better error for bad kwarg [geniass]
## Version 2.0.6 (22 February 2017)
* add version numbers to library names on linux
## Version 2.0.5 (8 September 2017)
* minor polish
* more tests
* add `composite` convenience method
* move tests outside module [greut]
* switch to tox [greut]
* allow info message logging
## Version 2.0.4 (3 September 2017)
* clear error log after failed get_typeof in get() workaround
* more tests pass with older libvips
* fix typo in logging handler
## Version 2.0.3 (2 September 2017)
* fix get() with old libvips
* better collapse for docs [kleisauke]
* add `get_fields()`
## Version 2.0.2 (26 August 2017)
* support `pyvips.__version__`
* add `version()` to get libvips version number
* add `cache_set_max()`, `cache_set_max_mem()`, `cache_set_max_files()`,
`cache_set_trace()`
* all glib log levels sent to py logger
* docs are collapsed for less scrolling [kleisauke]
## Version 2.0.1 (23 August 2017)
* doc revisions
* fix test suite on Windows
* redirect libvips warnings to logging
* fix debug logging
## Version 2.0.0 (19 August 2017)
* rewrite on top of 'cffi'
python-pyvips-3.1.1/LICENSE.txt 0000664 0000000 0000000 00000002037 15222163673 0016221 0 ustar 00root root 0000000 0000000 Copyright (c) 2017 John Cupitt
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
python-pyvips-3.1.1/MANIFEST.in 0000664 0000000 0000000 00000000057 15222163673 0016134 0 ustar 00root root 0000000 0000000 # Include the license file
include LICENSE.txt
python-pyvips-3.1.1/README.rst 0000664 0000000 0000000 00000014531 15222163673 0016067 0 ustar 00root root 0000000 0000000 README
======
.. image:: https://github.com/libvips/pyvips/workflows/CI/badge.svg
:alt: Build Status
:target: https://github.com/libvips/pyvips/actions
PyPI package:
https://pypi.python.org/pypi/pyvips
conda package:
https://anaconda.org/conda-forge/pyvips
We have formatted docs online here:
https://libvips.github.io/pyvips/
This module wraps the libvips image processing library:
https://www.libvips.org/
The libvips docs are also very useful:
https://www.libvips.org/API/current/
If you have the development headers for libvips installed and have a working C
compiler, this module will use cffi API mode to try to build a libvips
binary extension for your Python.
If it is unable to build a binary extension, it will use cffi ABI mode
instead and only needs the libvips shared library. This takes longer to
start up and is typically ~20% slower in execution. You can find out if
API mode is being used with:
.. code-block:: python
import pyvips
print(pyvips.API_mode)
This binding passes the vips test suite cleanly and with no leaks under
python3 and pypy3 on Windows, macOS and Linux.
How it works
------------
Programs that use ``pyvips`` don't manipulate images directly, instead
they create pipelines of image processing operations building on a source
image. When the end of the pipe is connected to a destination, the whole
pipeline executes at once, streaming the image in parallel from source to
destination a section at a time.
Because ``pyvips`` is parallel, it's quick, and because it doesn't need to
keep entire images in memory, it's light. For example, the libvips
speed and memory use benchmark:
https://github.com/libvips/libvips/wiki/Speed-and-memory-use
Loads a large tiff image, shrinks by 10%, sharpens, and saves again. On this
test ``pyvips`` is typically 3x faster than ImageMagick and needs 5x less
memory.
There's a handy chapter in the docs explaining how libvips opens files,
which gives some more background.
https://www.libvips.org/API/current/How-it-opens-files.html
Binary installation
-------------------
The quickest way to start with pyvips is by installing the binary package
with:
.. code-block:: shell
$ pip install "pyvips[binary]"
This installs a self-contained package with the most commonly needed
libraries. It should just work on most platforms, including Linux,
Windows and macOS, with 64 and 32 bit x64 and ARM CPUs. Note that this libvips
is missing features like PDF load and OpenSlide support.
If your platform is unsupported or the pre-built binary is unsuitable, you
can install libvips separately instead.
Local installation
------------------
You need the libvips shared library on your library search path, version 8.2
or later, though at least version 8.9 is required for all features to work.
See:
https://www.libvips.org/install.html
Linux
^^^^^
Perhaps:
.. code-block:: shell
$ sudo apt install libvips-dev --no-install-recommends
$ pip install pyvips
With python 3.11 and later, you will need to create a venv first and add
`path/to/venv` to your `PATH`. Something like:
.. code-block:: shell
$ python3 -m venv ~/.local
$ pip install pyvips
macOS
^^^^^
With Homebrew:
.. code-block:: shell
$ brew install vips python pkg-config
$ pip install pyvips
Windows
^^^^^^^
On Windows, you can download a pre-compiled binary from the libvips website.
https://www.libvips.org/install.html
You'll need a 64-bit Python. The official one works well.
You can add ``vips-dev-x.y\bin`` to your ``PATH``, but this will add a lot of
extra DLLs to your search path and they might conflict with other programs,
so it's usually safer to set ``PATH`` in your program.
To set ``PATH`` from within Python, you need something like this at the
start of your program:
.. code-block:: python
import os
vipsbin = r'c:\vips-dev-8.16\bin'
os.environ['PATH'] = vipsbin + ';' + os.environ['PATH']
For Python 3.8 and later, you need:
.. code-block:: python
import os
vipsbin = r'c:\vips-dev-8.16\bin'
add_dll_dir = getattr(os, 'add_dll_directory', None)
if callable(add_dll_dir):
add_dll_dir(vipsbin)
else:
os.environ['PATH'] = os.pathsep.join((vipsbin, os.environ['PATH']))
Now when you import pyvips, it should be able to find the DLLs.
Conda
^^^^^
The Conda package includes a matching libvips binary, so just enter:
.. code-block:: shell
$ conda install --channel conda-forge pyvips
Example
-------
This sample program loads a JPG image, doubles the value of every green pixel,
sharpens, and then writes the image back to the filesystem again:
.. code-block:: python
import pyvips
image = pyvips.Image.new_from_file('some-image.jpg', access='sequential')
image *= [1, 2, 1]
mask = pyvips.Image.new_from_array([
[-1, -1, -1],
[-1, 16, -1],
[-1, -1, -1],
], scale=8)
image = image.conv(mask, precision='integer')
image.write_to_file('x.jpg')
Notes
-----
Local user install:
.. code-block:: shell
$ pip install -e .[binary]
Run all tests:
.. code-block:: shell
$ tox
Run test suite:
.. code-block:: shell
$ pytest
Run a specific test:
.. code-block:: shell
$ pytest tests/test_saveload.py
Run perf tests:
.. code-block:: shell
$ cd tests/perf
$ ./run.sh
Stylecheck:
.. code-block:: shell
$ flake8
Generate HTML docs in ``doc/build/html``:
.. code-block:: shell
$ cd doc; sphinx-build -bhtml . build/html
Regenerate enums:
Make sure you have installed a libvips with all optional packages enabled,
then
.. code-block:: shell
$ cd examples; \
./gen-enums.py ~/GIT/libvips/build/libvips/Vips-8.0.gir > enums.py
Then check and move `enums.py` into `pyvips/`.
Regenerate autodocs:
Make sure you have installed a libvips with all optional packages enabled,
then
.. code-block:: shell
$ cd doc; \
python3 -c "import pyvips; pyvips.Operation.generate_sphinx_all()" > x
And copy-paste ``x`` into the obvious place in ``doc/vimage.rst``.
Update version number:
.. code-block:: shell
$ vi pyvips/version.py
$ vi doc/conf.py
Update pypi package:
.. code-block:: shell
$ python3 -m build --sdist
Ignore the deprecation warnings about the license, we need to update the
build backend before we can fix this.
.. code-block:: shell
$ twine upload --repository pyvips dist/*
$ git tag -a v3.0.0 -m "as uploaded to pypi"
$ git push origin v3.0.0
python-pyvips-3.1.1/doc/ 0000775 0000000 0000000 00000000000 15222163673 0015141 5 ustar 00root root 0000000 0000000 python-pyvips-3.1.1/doc/README.rst 0000777 0000000 0000000 00000000000 15222163673 0020525 2../README.rst ustar 00root root 0000000 0000000 python-pyvips-3.1.1/doc/_static/ 0000775 0000000 0000000 00000000000 15222163673 0016567 5 ustar 00root root 0000000 0000000 python-pyvips-3.1.1/doc/_static/collapse.js 0000664 0000000 0000000 00000001216 15222163673 0020727 0 ustar 00root root 0000000 0000000 $(document).ready(function() {
// Default to collapsed
$('dl.staticmethod, dl.method').addClass('collapsed')
$('dl.staticmethod > dd > p:first-child, dl.method > dd > p:first-child').click(function(e) {
$(this).parents().eq(1).toggleClass('collapsed');
});
// Attaching the hashchange event listener
$(window).on('hashchange', function() {
base = window.location.hash.replace(/\./g, '\\.');
base = $(base);
base.parent().removeClass('collapsed');
});
// Manually triggering it if we have hash part in URL
if (window.location.hash) {
$(window).trigger('hashchange')
}
});
python-pyvips-3.1.1/doc/_static/style.css 0000664 0000000 0000000 00000002220 15222163673 0020435 0 ustar 00root root 0000000 0000000 dl.staticmethod.collapsed > dd > p:not(:first-child),
dl.staticmethod.collapsed > dd > div,
dl.staticmethod.collapsed > dd > dl,
dl.staticmethod.collapsed > dd > table,
dl.method.collapsed > dd > p:not(:first-child),
dl.method.collapsed > dd > div,
dl.method.collapsed > dd > dl,
dl.method.collapsed > dd > table {
display: none;
}
dl.staticmethod > dd > p:not(:first-child),
dl.staticmethod > dd > div,
dl.staticmethod > dd > dl,
dl.staticmethod > dd > table,
dl.method > dd > p:not(:first-child),
dl.method > dd > div,
dl.method > dd > dl,
dl.method > dd > table {
display: block;
}
dl.staticmethod > dd > p:not(:only-child):first-child:before,
dl.method > dd > p:not(:only-child):first-child:before {
position: absolute;
font-family: "FontAwesome";
content: 'ï…‡';
display: inline-block;
font-style: normal;
font-weight: normal;
line-height: 1;
text-decoration: inherit;
margin-top: 5px;
margin-left: -20px;
white-space: pre;
cursor: pointer;
}
dl.staticmethod.collapsed > dd > p:not(:only-child):first-child:before,
dl.method.collapsed > dd > p:not(:only-child):first-child:before {
content: '';
}
python-pyvips-3.1.1/doc/_templates/ 0000775 0000000 0000000 00000000000 15222163673 0017276 5 ustar 00root root 0000000 0000000 python-pyvips-3.1.1/doc/_templates/layout.html 0000664 0000000 0000000 00000000353 15222163673 0021502 0 ustar 00root root 0000000 0000000 {% extends "!layout.html" %}
{% set script_files = script_files + [pathto("_static/collapse.js", True)] %}
{% block extrahead %}
{% endblock %}
python-pyvips-3.1.1/doc/base.rst 0000664 0000000 0000000 00000000176 15222163673 0016611 0 ustar 00root root 0000000 0000000 .. include global.rst
Base definitions
================
Basic utility stuff.
.. automodule:: pyvips.base
:members:
python-pyvips-3.1.1/doc/conf.py 0000664 0000000 0000000 00000020314 15222163673 0016440 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# pyvips documentation build configuration file, created by
# sphinx-quickstart on Wed Aug 9 15:19:17 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
import os
import sys
import sphinx_rtd_theme
sys.path.insert(0, os.path.abspath('..'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages',
'sphinx.ext.napoleon',
]
autodoc_member_order = 'bysource'
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'pyvips'
copyright = u'2019, John Cupitt'
author = u'John Cupitt'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'3.1'
# The full version, including alpha/beta/rc tags.
release = u'3.1.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['global.rst']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
html_sidebars = {
'**': [
'about.html',
'navigation.html',
'searchbox.html',
]
}
html_context = {
# Enable the "Edit on GitHub" link within the header of each page.
'display_github': True,
# Set the following variables to generate the resulting github URL for
# each page.
'github_user': 'libvips',
'github_repo': 'pyvips',
'github_version': 'master/doc/'
}
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'pyvipsdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'pyvips.tex', u'pyvips Documentation',
u'john', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'pyvips', u'pyvips Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'pyvips', u'pyvips Documentation',
author, 'pyvips', 'One line description of project.',
'Miscellaneous'),
]
# see https://stackoverflow.com/questions/20569011
# adds autoautosummary directive, see vimage.rst
# try to exclude deprecated
def skip_deprecated(app, what, name, obj, skip, options):
if hasattr(obj, "func_dict") and "__deprecated__" in obj.func_dict:
print("skipping " + name)
return True
return skip or False
def setup(app):
app.connect('autodoc-skip-member', skip_deprecated)
try:
from sphinx.ext.autosummary import Autosummary
from sphinx.ext.autosummary import get_documenter
from docutils.parsers.rst import directives
from sphinx.util.inspect import safe_getattr
class AutoAutoSummary(Autosummary):
option_spec = {
'methods': directives.unchanged,
'attributes': directives.unchanged
}
required_arguments = 1
@staticmethod
def get_members(obj, typ, include_public=None):
if not include_public:
include_public = []
items = []
for name in dir(obj):
try:
documenter = get_documenter(safe_getattr(obj, name),
obj)
except AttributeError:
continue
if documenter.objtype == typ:
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
return public, items
def run(self):
clazz = str(self.arguments[0])
try:
(module_name, class_name) = clazz.rsplit('.', 1)
m = __import__(module_name, globals(), locals(),
[class_name])
c = getattr(m, class_name)
if 'methods' in self.options:
_, methods = self.get_members(c,
'method', ['__init__'])
self.content = ["~%s.%s" % (clazz, method)
for method in methods
if not method.startswith('_')]
if 'attributes' in self.options:
_, attribs = self.get_members(c, 'attribute')
self.content = ["~%s.%s" % (clazz, attrib)
for attrib in attribs
if not attrib.startswith('_')]
finally:
return super(AutoAutoSummary, self).run()
app.add_directive('autoautosummary', AutoAutoSummary)
except BaseException as e:
raise e
python-pyvips-3.1.1/doc/enums.rst 0000664 0000000 0000000 00000000433 15222163673 0017022 0 ustar 00root root 0000000 0000000 .. include global.rst
The libvips enums
=================
This module contains the various libvips enums as Python classes.
Enums values are represented in pyvips as strings. These classes contain the
valid strings for each enum.
.. automodule:: pyvips.enums
:members:
python-pyvips-3.1.1/doc/error.rst 0000664 0000000 0000000 00000000161 15222163673 0017022 0 ustar 00root root 0000000 0000000 .. include global.rst
``Error``
=========
Errors from libvips.
.. automodule:: pyvips.error
:members:
python-pyvips-3.1.1/doc/global.rst 0000664 0000000 0000000 00000000026 15222163673 0017131 0 ustar 00root root 0000000 0000000 .. py:module:: pyvips
python-pyvips-3.1.1/doc/gobject.rst 0000664 0000000 0000000 00000000173 15222163673 0017311 0 ustar 00root root 0000000 0000000 .. include global.rst
``GObject``
===========
.. automodule:: pyvips.gobject
:members:
:special-members:
python-pyvips-3.1.1/doc/gvalue.rst 0000664 0000000 0000000 00000000343 15222163673 0017156 0 ustar 00root root 0000000 0000000 .. include global.rst
``GValue``
==========
This module defines the pyvips ``GValue`` class. You can use instances of
this class to get and set :class:`.GObject` properties.
.. automodule:: pyvips.gvalue
:members:
python-pyvips-3.1.1/doc/index.rst 0000664 0000000 0000000 00000001145 15222163673 0017003 0 ustar 00root root 0000000 0000000 .. include global.rst
`pyvips` -- Image processing with libvips
=========================================
.. module:: pyvips
:synopsis: Interface to the libvips image processing library.
.. moduleauthor:: John Cupitt
.. moduleauthor:: Kleis Auke Wolthuizen
Contents
--------
.. toctree::
:maxdepth: 2
README
intro
vimage
base
error
enums
vconnection
vsource
vtarget
vsourcecustom
vtargetcustom
vinterpolate
gvalue
gobject
voperation
vobject
Indicies
--------
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
python-pyvips-3.1.1/doc/intro.rst 0000664 0000000 0000000 00000034155 15222163673 0017036 0 ustar 00root root 0000000 0000000 .. include global.rst
Introduction
============
See the main libvips site for an introduction to the underlying library. These
notes introduce the Python binding.
https://libvips.github.io/libvips
Example
-------
This example loads a file, boosts the green channel, sharpens the image,
and saves it back to disc again::
import pyvips
image = pyvips.Image.new_from_file('some-image.jpg', access='sequential')
image *= [1, 2, 1]
mask = pyvips.Image.new_from_list([[-1, -1, -1],
[-1, 16, -1],
[-1, -1, -1]
], scale=8)
image = image.conv(mask, precision='integer')
image.write_to_file('x.jpg')
Reading this example line by line, we have::
image = pyvips.Image.new_from_file('some-image.jpg', access='sequential')
:meth:`.Image.new_from_file` can load any image file supported by libvips.
When you load an image, only the header is fetched from the file. Pixels will
not be read until you have built a pipeline of operations and connected it
to an output.
When you load, you can hint what type of access you will need. In this
example, we will be accessing pixels top-to-bottom as we sweep through
the image reading and writing, so `sequential` access mode is best for us.
The default mode is ``random`` which allows for full random access to image
pixels, but is slower and needs more memory. See :class:`.enums.Access`
for details on the various modes available.
You can also load formatted images from memory with
:meth:`.Image.new_from_buffer`, create images that wrap C-style memory arrays
held as Python buffers with :meth:`.Image.new_from_memory`, or make images
from constants with :meth:`.Image.new_from_list`. You can also create custom
sources and targets that link image processing pipelines to your own code,
see `Custom sources and targets`_.
The next line::
image *= [1, 2, 1]
Multiplies the image by an array constant using one array element for each
image band. This line assumes that the input image has three bands and will
double the middle band. For RGB images, that's doubling green.
There is a full set arithmetic operator `Overloads`_, so you can compute with
entire images just as you would with single numbers.
Next we have::
mask = pyvips.Image.new_from_list([[-1, -1, -1],
[-1, 16, -1],
[-1, -1, -1]
], scale = 8)
image = image.conv(mask, precision = 'integer')
:meth:`.new_from_list` creates an image from a list of lists. The
scale is the amount to divide the image by after integer convolution.
See the libvips API docs for ``vips_conv()`` (the operation
invoked by :meth:`.Image.conv`) for details on the convolution operator. By
default, it computes with a float mask, but ``integer`` is fine for this case,
and is much faster.
Finally::
image.write_to_file('x.jpg')
:meth:`.write_to_file` writes an image back to the filesystem. It can
write any format supported by vips: the file type is set from the filename
suffix. You can also write formatted images to memory, or dump
image data to a C-style array in a Python buffer.
Metadata and attributes
-----------------------
``pyvips`` adds a :meth:`.__getattr__` handler to :class:`.Image` and to
the Image metaclass, then uses it to look up unknown names in libvips.
Names are first checked against the set of properties that libvips
keeps for images, see :attr:`.width` and friends. If the name is not
found there, ``pyvips`` searches the set of libvips operations, see the next
section.
As well as the core properties, you can read and write the metadata
that libvips keeps for images with :meth:`.Image.get` and
friends. For example::
image = pyvips.Image.new_from_file('some-image.jpg')
ipct_string = image.get('ipct-data')
exif_date_string = image.get('exif-ifd0-DateTime')
Use :meth:`.get_fields` to get a list of all the field names you can use with
:meth:`.Image.get`.
libvips caches and shares images between different parts of your program. This
means that you can't modify an image unless you are certain that you have
the only reference to it. You can make a private copy of an image with
``copy``, for example::
new_image = image.copy(xres=12, yres=13)
Now ``new_image`` is a private clone of ``image`` with ``xres`` and ``yres``
changed.
Set image metadata with :meth:`.Image.set`. Use :meth:`.Image.copy` to make
a private copy of the image first, for example::
new_image = image.copy().set('icc-profile-data', new_profile)
Now ``new_image`` is a clone of ``image`` with a new ICC profile attached to
it.
NumPy and PIL
-------------
You can use :meth:`.new_from_array` to create a pyvips image from a NumPy array
or a PIL image. For example::
import pyvips
import numpy as np
a = (np.random.random((100, 100, 3)) * 255).astype(np.uint8)
image = pyvips.Image.new_from_array(a)
import PIL.Image
pil_image = PIL.Image.new('RGB', (60, 30), color = 'red')
image = pyvips.Image.new_from_array(pil_image)
Going the other direction, a conversion from a pyvips image to a NumPy array can
be obtained with the :meth:`.numpy()` method of the :class:`pyvips.Image` class
or from the numpy side with :func:`numpy.asarray`. This is a fast way to load
many image formats::
import pyvips
import numpy as np
image = pyvips.Image.new_from_file('some-image.jpg')
a1 = image.numpy()
a2 = np.asarray(image)
assert np.array_equal(a1, a2)
The :meth:`PIL.Image.fromarray` method can be used to convert a pyvips image
to a PIL image via a NumPy array::
import pyvips
import PIL.Image
image = pyvips.Image.black(100, 100, bands=3)
pil_image = PIL.Image.fromarray(image.numpy())
Calling libvips operations
--------------------------
Unknown names which are not image properties are looked up as libvips
operations. For example, the libvips operation ``add``, which appears in C as
``vips_add()``, appears in Python as :meth:`.Image.add`.
The operation's list of required arguments is searched and the first input
image is set to the value of ``self``. Operations which do not take an input
image, such as :meth:`.Image.black`, appear as class methods. The
remainder of the arguments you supply in the function call are used to set
the other required input arguments. Any trailing keyword arguments are used
to set options on the underlying libvips operation.
The result is the required output argument if there is only one result,
or a list of values if the operation produces several results. If the
operation has optional output objects, they are returned as a final
Python dictionary.
For example, :meth:`.Image.min`, the vips operation that searches an
image for the minimum value, has a large number of optional arguments. You
can use it to find the minimum value like this::
min_value = image.min()
You can ask it to return the position of the minimum with `:x` and `:y`::
min_value, opts = image.min(x=True, y=True)
x_pos = opts['x']
y_pos = opts['y']
Now ``x_pos`` and ``y_pos`` will have the coordinates of the minimum value.
There's actually a convenience method for this, :meth:`.minpos`.
You can also ask for the top *n* minimum, for example::
min_value, opts = min(size=10, x_array=True, y_array=True)
x_pos = opts['x_array']
y_pos = opts['y_array']
Now ``x_pos`` and ``y_pos`` will be 10-element arrays.
Because operations are member functions and return the result image, you can
chain them. For example, you can write::
result_image = image.real().cos()
to calculate the cosine of the real part of a complex image. There is
also a full set of arithmetic `Overloads`_.
libvips types are automatically wrapped. The binding looks at the type
of argument required by the operation and converts the value you supply,
when it can. For example, :meth:`.Image.linear` takes a
``VipsArrayDouble`` as an argument for the set of constants to use for
multiplication. You can supply this value as an integer, a float, or some
kind of compound object and it will be converted for you. You can write::
result_image = image.linear(1, 3)
result_image = image.linear(12.4, 13.9)
result_image = image.linear([1, 2, 3], [4, 5, 6])
result_image = image.linear(1, [4, 5, 6])
And so on. A set of overloads are defined for :meth:`.Image.linear`,
see below.
If an operation takes several input images, you can use a constant for all but
one of them and the wrapper will expand the constant to an image for you. For
example, :meth:`.ifthenelse` uses a condition image to pick pixels
between a then and an else image::
result_image = condition_image.ifthenelse(then_image, else_image)
You can use a constant instead of either the then or the else parts and it
will be expanded to an image for you. If you use a constant for both then and
else, it will be expanded to match the condition image. For example::
result_image = condition_image.ifthenelse([0, 255, 0], [255, 0, 0])
Will make an image where true pixels are green and false pixels are red.
This is useful for :meth:`.bandjoin`, the thing to join two or more
images up bandwise. You can write::
rgba = rgb.bandjoin(255)
to append a constant 255 band to an image, perhaps to add an alpha channel. Of
course you can also write::
result_image = image1.bandjoin(image2)
result_image = image1.bandjoin([image2, image3])
result_image = pyvips.Image.bandjoin([image1, image2, image3])
result_image = image1.bandjoin([image2, 255])
and so on.
Logging and warnings
--------------------
The module uses ``logging`` to log warnings from libvips, and debug messages
from the module itself. Some warnings are important, for example truncated
files, and you might want to see them.
Add these lines somewhere near the start of your program::
import logging
logging.basicConfig(level=logging.WARNING)
Exceptions
----------
The wrapper spots errors from vips operations and raises the :class:`.Error`
exception. You can catch it in the usual way.
Enums
-----
The libvips enums, such as ``VipsBandFormat``, appear in pyvips as strings
like ``'uchar'``. They are documented as a set of classes for convenience, see
:class:`.Access`, for example.
Overloads
---------
The wrapper defines the usual set of arithmetic, boolean and relational
overloads on image. You can mix images, constants and lists of constants
freely. For example, you can write::
result_image = ((image * [1, 2, 3]).abs() < 128) | 4
Expansions
----------
Some vips operators take an enum to select an action, for example
:meth:`.Image.math` can be used to calculate sine of every pixel
like this::
result_image = image.math('sin')
This is annoying, so the wrapper expands all these enums into separate members
named after the enum value. So you can also write::
result_image = image.sin()
Convenience functions
---------------------
The wrapper defines a few extra useful utility functions:
:meth:`.bandsplit`, :meth:`.maxpos`, :meth:`.minpos`,
:meth:`.median`.
Tracking and interrupting computation
-------------------------------------
You can attach progress handlers to images to watch the progress of
computation.
For example::
image = pyvips.Image.black(1, 500)
image.set_progress(True)
image.signal_connect('preeval', preeval_handler)
image.signal_connect('eval', eval_handler)
image.signal_connect('posteval', posteval_handler)
image.avg()
Handlers are given a `progress` object containing a number of useful fields.
For example::
def eval_handler(image, progress):
print(f' run = {progress.run} (seconds of run time)')
print(f' eta = {progress.eta} (estimated seconds left)')
print(f' tpels = {progress.tpels} (total number of pels)')
print(f' npels = {progress.npels} (number of pels computed so far)')
print(f' percent = {progress.percent} (percent complete)')
Use :meth:`.Image.set_kill` on the image to stop computation early.
For example::
def eval_handler(image, progress):
if progress.percent > 50:
image.set_kill(True)
Custom sources and targets
--------------------------
You can load and save images to and from :class:`.Source` and
:class:`.Target`.
For example::
source = pyvips.Source.new_from_file("some/file/name")
image = pyvips.Image.new_from_source(source, "", access="sequential")
target = pyvips.Target.new_to_file("some/file/name")
image.write_to_target(target, ".png")
Sources and targets can be files, descriptors (eg. pipes) and areas of memory.
You can define :class:`.SourceCustom` and :class:`.TargetCustom` too.
For example::
input_file = open(sys.argv[1], "rb")
def read_handler(size):
return input_file.read(size)
source = pyvips.SourceCustom()
source.on_read(read_handler)
output_file = open(sys.argv[2], "wb")
def write_handler(chunk):
return output_file.write(chunk)
target = pyvips.TargetCustom()
target.on_write(write_handler)
image = pyvips.Image.new_from_source(source, '', access='sequential')
image.write_to_target(target, '.png')
You can also define seek and finish handlers, see the docs.
Automatic documentation
-----------------------
The bulk of these API docs are generated automatically by
:meth:`.Operation.generate_sphinx_all`. It examines libvips and writes a
summary of each operation and the arguments and options that that operation
expects.
Use the C API docs for more detail:
https://libvips.github.io/libvips/API/current
Draw operations
---------------
Paint operations like :meth:`.Image.draw_circle` and
:meth:`.Image.draw_line` modify their input image. This makes them
hard to use with the rest of libvips: you need to be very careful about
the order in which operations execute or you can get nasty crashes.
The wrapper spots operations of this type and makes a private copy of the
image in memory before calling the operation. This stops crashes, but it does
make it inefficient. If you draw 100 lines on an image, for example, you'll
copy the image 100 times. The wrapper does make sure that memory is recycled
where possible, so you won't have 100 copies in memory.
If you want to avoid the copies, you'll need to call drawing operations
yourself.
python-pyvips-3.1.1/doc/vconnection.rst 0000664 0000000 0000000 00000000153 15222163673 0020217 0 ustar 00root root 0000000 0000000 .. include global.rst
``Connection``
==============
.. automodule:: pyvips.vconnection
:members:
python-pyvips-3.1.1/doc/vimage.rst 0000664 0000000 0000000 00000742103 15222163673 0017152 0 ustar 00root root 0000000 0000000 .. include global.rst
.. py:currentmodule:: pyvips
``Image``
=========
Main methods
------------
.. autoclass:: Image
:members:
:special-members:
.. rubric:: Methods
.. autoautosummary:: Image
:methods:
Attributes
----------
.. autosummary::
:nosignatures:
.. class:: Image
:noindex:
.. attribute:: width
int, read-only: Image width in pixels.
.. attribute:: height
int, read-only: Image height in pixels.
.. attribute:: bands
int, read-only: Number of bands in image.
.. attribute:: format
:class:`.BandFormat`, read-only: Image format.
.. attribute:: interpretation
:class:`.Interpretation`, read-only: Suggested interpretation of
image pixel values.
.. attribute:: coding
:class:`.Coding`, read-only: Pixel coding.
.. attribute:: filename
str, read-only: Filename image was loaded from, or None.
.. attribute:: xoffset
int, read-only: Image X offset.
.. attribute:: yoffset
int, read-only: Image Y offset.
.. attribute:: xres
float, read-only: Image X resolution, in pixels / mm
.. attribute:: yres
float, read-only: Image Y resolution, in pixels / mm.
.. attribute:: scale
float, read-only: Image scale.
.. attribute:: offset
float, read-only: Image offset.
Autogenerated methods
---------------------
.. class:: Image
:noindex:
.. rubric:: Methods
.. autosummary::
:nosignatures:
~CMC2LCh
~CMYK2XYZ
~HSV2sRGB
~LCh2CMC
~LCh2Lab
~Lab2LCh
~Lab2LabQ
~Lab2LabS
~Lab2XYZ
~LabQ2Lab
~LabQ2LabS
~LabQ2sRGB
~LabS2Lab
~LabS2LabQ
~Oklab2Oklch
~Oklab2XYZ
~Oklch2Oklab
~XYZ2CMYK
~XYZ2Lab
~XYZ2Oklab
~XYZ2Yxy
~XYZ2scRGB
~Yxy2XYZ
~abs
~add
~addalpha
~affine
~analyzeload
~arrayjoin
~autorot
~avg
~bandbool
~bandfold
~bandjoin_const
~bandmean
~bandunfold
~black
~boolean
~boolean_const
~buildlut
~byteswap
~canny
~case
~cast
~clamp
~colourspace
~compass
~complex
~complex2
~complexform
~complexget
~composite
~composite2
~conv
~conva
~convasep
~convf
~convi
~convsep
~copy
~countlines
~crop
~csvload
~csvload_source
~csvsave
~csvsave_target
~dE00
~dE76
~dECMC
~dcrawload
~dcrawload_buffer
~dcrawload_source
~deviate
~divide
~draw_circle
~draw_flood
~draw_image
~draw_line
~draw_mask
~draw_rect
~draw_smudge
~dzsave
~dzsave_buffer
~dzsave_target
~embed
~extract_area
~extract_band
~eye
~falsecolour
~fastcor
~fill_nearest
~find_trim
~fitsload
~fitsload_source
~fitssave
~flatten
~flip
~float2rad
~fractsurf
~freqmult
~fwfft
~gamma
~gaussblur
~gaussmat
~gaussnoise
~getpoint
~gifload
~gifload_buffer
~gifload_source
~gifsave
~gifsave_buffer
~gifsave_target
~globalbalance
~gravity
~grey
~grid
~heifload
~heifload_buffer
~heifload_source
~heifsave
~heifsave_buffer
~heifsave_target
~hist_cum
~hist_entropy
~hist_equal
~hist_find
~hist_find_indexed
~hist_find_ndim
~hist_ismonotonic
~hist_local
~hist_match
~hist_norm
~hist_plot
~hough_circle
~hough_line
~icc_export
~icc_import
~icc_transform
~identity
~insert
~invert
~invertlut
~invfft
~join
~jp2kload
~jp2kload_buffer
~jp2kload_source
~jp2ksave
~jp2ksave_buffer
~jp2ksave_target
~jpegload
~jpegload_buffer
~jpegload_source
~jpegsave
~jpegsave_buffer
~jpegsave_mime
~jpegsave_target
~jxlload
~jxlload_buffer
~jxlload_source
~jxlsave
~jxlsave_buffer
~jxlsave_target
~labelregions
~linear
~linecache
~logmat
~magickload
~magickload_buffer
~magickload_source
~magicksave
~magicksave_buffer
~mapim
~maplut
~mask_butterworth
~mask_butterworth_band
~mask_butterworth_ring
~mask_fractal
~mask_gaussian
~mask_gaussian_band
~mask_gaussian_ring
~mask_ideal
~mask_ideal_band
~mask_ideal_ring
~match
~math
~math2
~math2_const
~matload
~matrixinvert
~matrixload
~matrixload_source
~matrixmultiply
~matrixprint
~matrixsave
~matrixsave_target
~max
~maxpair
~measure
~merge
~min
~minpair
~morph
~mosaic
~mosaic1
~msb
~multiply
~niftiload
~niftiload_source
~niftisave
~openexrload
~openslideload
~openslideload_source
~pdfload
~pdfload_buffer
~pdfload_source
~percent
~perlin
~phasecor
~pngload
~pngload_buffer
~pngload_source
~pngsave
~pngsave_buffer
~pngsave_target
~ppmload
~ppmload_buffer
~ppmload_source
~ppmsave
~ppmsave_target
~premultiply
~prewitt
~profile
~profile_load
~project
~quadratic
~rad2float
~radload
~radload_buffer
~radload_source
~radsave
~radsave_buffer
~radsave_target
~rank
~rawload
~rawsave
~rawsave_buffer
~rawsave_target
~recomb
~reduce
~reduceh
~reducev
~relational
~relational_const
~remainder
~remainder_const
~remosaic
~replicate
~resize
~rot
~rot45
~rotate
~round
~sRGB2HSV
~sRGB2scRGB
~scRGB2BW
~scRGB2XYZ
~scRGB2sRGB
~scharr
~sdf
~sequential
~sharpen
~shrink
~shrinkh
~shrinkv
~sign
~similarity
~sines
~smartcrop
~sobel
~spcor
~spectrum
~stats
~stdif
~subsample
~subtract
~sum
~svgload
~svgload_buffer
~svgload_source
~switch
~system
~text
~thumbnail
~thumbnail_buffer
~thumbnail_image
~thumbnail_source
~tiffload
~tiffload_buffer
~tiffload_source
~tiffsave
~tiffsave_buffer
~tiffsave_target
~tilecache
~tonelut
~transpose3d
~uhdr2scRGB
~uhdrload
~uhdrload_buffer
~uhdrload_source
~uhdrsave
~uhdrsave_buffer
~uhdrsave_target
~unpremultiply
~vipsload
~vipsload_source
~vipssave
~vipssave_target
~webpload
~webpload_buffer
~webpload_source
~webpsave
~webpsave_buffer
~webpsave_mime
~webpsave_target
~worley
~wrap
~xyz
~zone
~zoom
.. method:: CMC2LCh()
Transform LCh to CMC.
Example:
out = in.CMC2LCh()
:rtype: Image
:raises Error:
.. method:: CMYK2XYZ()
Transform CMYK to XYZ.
Example:
out = in.CMYK2XYZ()
:rtype: Image
:raises Error:
.. method:: HSV2sRGB()
Transform HSV to sRGB.
Example:
out = in.HSV2sRGB()
:rtype: Image
:raises Error:
.. method:: LCh2CMC()
Transform LCh to CMC.
Example:
out = in.LCh2CMC()
:rtype: Image
:raises Error:
.. method:: LCh2Lab()
Transform LCh to Lab.
Example:
out = in.LCh2Lab()
:rtype: Image
:raises Error:
.. method:: Lab2LCh()
Transform Lab to LCh.
Example:
out = in.Lab2LCh()
:rtype: Image
:raises Error:
.. method:: Lab2LabQ()
Transform float Lab to LabQ coding.
Example:
out = in.Lab2LabQ()
:rtype: Image
:raises Error:
.. method:: Lab2LabS()
Transform float Lab to signed short.
Example:
out = in.Lab2LabS()
:rtype: Image
:raises Error:
.. method:: Lab2XYZ(temp=list[float])
Transform CIELAB to XYZ.
Example:
out = in.Lab2XYZ(temp=list[float])
:param temp: Color temperature
:type temp: list[float]
:rtype: Image
:raises Error:
.. method:: LabQ2Lab()
Unpack a LabQ image to float Lab.
Example:
out = in.LabQ2Lab()
:rtype: Image
:raises Error:
.. method:: LabQ2LabS()
Unpack a LabQ image to short Lab.
Example:
out = in.LabQ2LabS()
:rtype: Image
:raises Error:
.. method:: LabQ2sRGB()
Convert a LabQ image to sRGB.
Example:
out = in.LabQ2sRGB()
:rtype: Image
:raises Error:
.. method:: LabS2Lab()
Transform signed short Lab to float.
Example:
out = in.LabS2Lab()
:rtype: Image
:raises Error:
.. method:: LabS2LabQ()
Transform short Lab to LabQ coding.
Example:
out = in.LabS2LabQ()
:rtype: Image
:raises Error:
.. method:: Oklab2Oklch()
Transform Oklab to Oklch.
Example:
out = in.Oklab2Oklch()
:rtype: Image
:raises Error:
.. method:: Oklab2XYZ()
Transform Oklab to XYZ.
Example:
out = in.Oklab2XYZ()
:rtype: Image
:raises Error:
.. method:: Oklch2Oklab()
Transform Oklch to Oklab.
Example:
out = in.Oklch2Oklab()
:rtype: Image
:raises Error:
.. method:: XYZ2CMYK()
Transform XYZ to CMYK.
Example:
out = in.XYZ2CMYK()
:rtype: Image
:raises Error:
.. method:: XYZ2Lab(temp=list[float])
Transform XYZ to Lab.
Example:
out = in.XYZ2Lab(temp=list[float])
:param temp: Colour temperature
:type temp: list[float]
:rtype: Image
:raises Error:
.. method:: XYZ2Oklab()
Transform XYZ to Oklab.
Example:
out = in.XYZ2Oklab()
:rtype: Image
:raises Error:
.. method:: XYZ2Yxy()
Transform XYZ to Yxy.
Example:
out = in.XYZ2Yxy()
:rtype: Image
:raises Error:
.. method:: XYZ2scRGB()
Transform XYZ to scRGB.
Example:
out = in.XYZ2scRGB()
:rtype: Image
:raises Error:
.. method:: Yxy2XYZ()
Transform Yxy to XYZ.
Example:
out = in.Yxy2XYZ()
:rtype: Image
:raises Error:
.. method:: abs()
Absolute value of an image.
Example:
out = in.abs()
:rtype: Image
:raises Error:
.. method:: add(right)
Add two images.
Example:
out = left.add(right)
:param right: Right-hand image argument
:type right: Image
:rtype: Image
:raises Error:
.. method:: addalpha()
Append an alpha channel.
Example:
out = in.addalpha()
:rtype: Image
:raises Error:
.. method:: affine(matrix, interpolate=GObject, oarea=list[int], odx=float, ody=float, idx=float, idy=float, background=list[float], premultiplied=bool, extend=Union[str, Extend])
Affine transform of an image.
Example:
out = in.affine(matrix, interpolate=GObject, oarea=list[int], odx=float, ody=float, idx=float, idy=float, background=list[float], premultiplied=bool, extend=Union[str, Extend])
:param matrix: Transformation matrix
:type matrix: list[float]
:param interpolate: Interpolate pixels with this
:type interpolate: GObject
:param oarea: Area of output to generate
:type oarea: list[int]
:param odx: Horizontal output displacement
:type odx: float
:param ody: Vertical output displacement
:type ody: float
:param idx: Horizontal input displacement
:type idx: float
:param idy: Vertical input displacement
:type idy: float
:param background: Background value
:type background: list[float]
:param premultiplied: Images have premultiplied alpha
:type premultiplied: bool
:param extend: How to generate the extra pixels
:type extend: Union[str, Extend]
:rtype: Image
:raises Error:
.. staticmethod:: analyzeload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load an Analyze6 image.
Example:
out = pyvips.Image.analyzeload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: arrayjoin(in, across=int, shim=int, background=list[float], halign=Union[str, Align], valign=Union[str, Align], hspacing=int, vspacing=int)
Join an array of images.
Example:
out = pyvips.Image.arrayjoin(in, across=int, shim=int, background=list[float], halign=Union[str, Align], valign=Union[str, Align], hspacing=int, vspacing=int)
:param in: Array of input images
:type in: list[Image]
:param across: Number of images across grid
:type across: int
:param shim: Pixels between images
:type shim: int
:param background: Colour for new pixels
:type background: list[float]
:param halign: Align on the left, centre or right
:type halign: Union[str, Align]
:param valign: Align on the top, centre or bottom
:type valign: Union[str, Align]
:param hspacing: Horizontal spacing between images
:type hspacing: int
:param vspacing: Vertical spacing between images
:type vspacing: int
:rtype: Image
:raises Error:
.. method:: autorot(angle=bool, flip=bool)
Autorotate image by exif tag.
Example:
out = in.autorot()
:param angle: enable output: Angle image was rotated by
:type angle: bool
:param flip: enable output: Whether the image was flipped or not
:type flip: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: avg()
Find image average.
Example:
out = in.avg()
:rtype: float
:raises Error:
.. method:: bandbool(boolean)
Boolean operation across image bands.
Example:
out = in.bandbool(boolean)
:param boolean: Boolean to perform
:type boolean: Union[str, OperationBoolean]
:rtype: Image
:raises Error:
.. method:: bandfold(factor=int)
Fold up x axis into bands.
Example:
out = in.bandfold(factor=int)
:param factor: Fold by this factor
:type factor: int
:rtype: Image
:raises Error:
.. method:: bandjoin_const(c)
Append a constant band to an image.
Example:
out = in.bandjoin_const(c)
:param c: Array of constants to add
:type c: list[float]
:rtype: Image
:raises Error:
.. method:: bandmean()
Band-wise average.
Example:
out = in.bandmean()
:rtype: Image
:raises Error:
.. method:: bandunfold(factor=int)
Unfold image bands into x axis.
Example:
out = in.bandunfold(factor=int)
:param factor: Unfold by this factor
:type factor: int
:rtype: Image
:raises Error:
.. staticmethod:: black(width, height, bands=int)
Make a black image.
Example:
out = pyvips.Image.black(width, height, bands=int)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param bands: Number of bands in image
:type bands: int
:rtype: Image
:raises Error:
.. method:: boolean(right, boolean)
Boolean operation on two images.
Example:
out = left.boolean(right, boolean)
:param right: Right-hand image argument
:type right: Image
:param boolean: Boolean to perform
:type boolean: Union[str, OperationBoolean]
:rtype: Image
:raises Error:
.. method:: boolean_const(boolean, c)
Boolean operations against a constant.
Example:
out = in.boolean_const(boolean, c)
:param boolean: Boolean to perform
:type boolean: Union[str, OperationBoolean]
:param c: Array of constants
:type c: list[float]
:rtype: Image
:raises Error:
.. method:: buildlut()
Build a look-up table.
Example:
out = in.buildlut()
:rtype: Image
:raises Error:
.. method:: byteswap()
Byteswap an image.
Example:
out = in.byteswap()
:rtype: Image
:raises Error:
.. method:: canny(sigma=float, precision=Union[str, Precision])
Canny edge detector.
Example:
out = in.canny(sigma=float, precision=Union[str, Precision])
:param sigma: Sigma of Gaussian
:type sigma: float
:param precision: Convolve with this precision
:type precision: Union[str, Precision]
:rtype: Image
:raises Error:
.. method:: case(cases)
Use pixel values to pick cases from an array of images.
Example:
out = index.case(cases)
:param cases: Array of case images
:type cases: list[Image]
:rtype: Image
:raises Error:
.. method:: cast(format, shift=bool)
Cast an image.
Example:
out = in.cast(format, shift=bool)
:param format: Format to cast to
:type format: Union[str, BandFormat]
:param shift: Shift integer values up and down
:type shift: bool
:rtype: Image
:raises Error:
.. method:: clamp(min=float, max=float)
Clamp values of an image.
Example:
out = in.clamp(min=float, max=float)
:param min: Minimum value
:type min: float
:param max: Maximum value
:type max: float
:rtype: Image
:raises Error:
.. method:: colourspace(space, source_space=Union[str, Interpretation])
Convert to a new colorspace.
Example:
out = in.colourspace(space, source_space=Union[str, Interpretation])
:param space: Destination color space
:type space: Union[str, Interpretation]
:param source_space: Source color space
:type source_space: Union[str, Interpretation]
:rtype: Image
:raises Error:
.. method:: compass(mask, times=int, angle=Union[str, Angle45], combine=Union[str, Combine], precision=Union[str, Precision], layers=int, cluster=int)
Convolve with rotating mask.
Example:
out = in.compass(mask, times=int, angle=Union[str, Angle45], combine=Union[str, Combine], precision=Union[str, Precision], layers=int, cluster=int)
:param mask: Input matrix image
:type mask: Image
:param times: Rotate and convolve this many times
:type times: int
:param angle: Rotate mask by this much between convolutions
:type angle: Union[str, Angle45]
:param combine: Combine convolution results like this
:type combine: Union[str, Combine]
:param precision: Convolve with this precision
:type precision: Union[str, Precision]
:param layers: Use this many layers in approximation
:type layers: int
:param cluster: Cluster lines closer than this in approximation
:type cluster: int
:rtype: Image
:raises Error:
.. method:: complex(cmplx)
Perform a complex operation on an image.
Example:
out = in.complex(cmplx)
:param cmplx: Complex to perform
:type cmplx: Union[str, OperationComplex]
:rtype: Image
:raises Error:
.. method:: complex2(right, cmplx)
Complex binary operations on two images.
Example:
out = left.complex2(right, cmplx)
:param right: Right-hand image argument
:type right: Image
:param cmplx: Binary complex operation to perform
:type cmplx: Union[str, OperationComplex2]
:rtype: Image
:raises Error:
.. method:: complexform(right)
Form a complex image from two real images.
Example:
out = left.complexform(right)
:param right: Right-hand image argument
:type right: Image
:rtype: Image
:raises Error:
.. method:: complexget(get)
Get a component from a complex image.
Example:
out = in.complexget(get)
:param get: Complex to perform
:type get: Union[str, OperationComplexget]
:rtype: Image
:raises Error:
.. staticmethod:: composite(in, mode, x=list[int], y=list[int], compositing_space=Union[str, Interpretation], premultiplied=bool)
Blend an array of images with an array of blend modes.
Example:
out = pyvips.Image.composite(in, mode, x=list[int], y=list[int], compositing_space=Union[str, Interpretation], premultiplied=bool)
:param in: Array of input images
:type in: list[Image]
:param mode: Array of VipsBlendMode to join with
:type mode: list[int]
:param x: Array of x coordinates to join at
:type x: list[int]
:param y: Array of y coordinates to join at
:type y: list[int]
:param compositing_space: Composite images in this colour space
:type compositing_space: Union[str, Interpretation]
:param premultiplied: Images have premultiplied alpha
:type premultiplied: bool
:rtype: Image
:raises Error:
.. method:: composite2(overlay, mode, x=int, y=int, compositing_space=Union[str, Interpretation], premultiplied=bool)
Blend a pair of images with a blend mode.
Example:
out = base.composite2(overlay, mode, x=int, y=int, compositing_space=Union[str, Interpretation], premultiplied=bool)
:param overlay: Overlay image
:type overlay: Image
:param mode: VipsBlendMode to join with
:type mode: Union[str, BlendMode]
:param x: x position of overlay
:type x: int
:param y: y position of overlay
:type y: int
:param compositing_space: Composite images in this colour space
:type compositing_space: Union[str, Interpretation]
:param premultiplied: Images have premultiplied alpha
:type premultiplied: bool
:rtype: Image
:raises Error:
.. method:: conv(mask, precision=Union[str, Precision], layers=int, cluster=int)
Convolution operation.
Example:
out = in.conv(mask, precision=Union[str, Precision], layers=int, cluster=int)
:param mask: Input matrix image
:type mask: Image
:param precision: Convolve with this precision
:type precision: Union[str, Precision]
:param layers: Use this many layers in approximation
:type layers: int
:param cluster: Cluster lines closer than this in approximation
:type cluster: int
:rtype: Image
:raises Error:
.. method:: conva(mask, layers=int, cluster=int)
Approximate integer convolution.
Example:
out = in.conva(mask, layers=int, cluster=int)
:param mask: Input matrix image
:type mask: Image
:param layers: Use this many layers in approximation
:type layers: int
:param cluster: Cluster lines closer than this in approximation
:type cluster: int
:rtype: Image
:raises Error:
.. method:: convasep(mask, layers=int)
Approximate separable integer convolution.
Example:
out = in.convasep(mask, layers=int)
:param mask: Input matrix image
:type mask: Image
:param layers: Use this many layers in approximation
:type layers: int
:rtype: Image
:raises Error:
.. method:: convf(mask)
Float convolution operation.
Example:
out = in.convf(mask)
:param mask: Input matrix image
:type mask: Image
:rtype: Image
:raises Error:
.. method:: convi(mask)
Int convolution operation.
Example:
out = in.convi(mask)
:param mask: Input matrix image
:type mask: Image
:rtype: Image
:raises Error:
.. method:: convsep(mask, precision=Union[str, Precision], layers=int, cluster=int)
Separable convolution operation.
Example:
out = in.convsep(mask, precision=Union[str, Precision], layers=int, cluster=int)
:param mask: Input matrix image
:type mask: Image
:param precision: Convolve with this precision
:type precision: Union[str, Precision]
:param layers: Use this many layers in approximation
:type layers: int
:param cluster: Cluster lines closer than this in approximation
:type cluster: int
:rtype: Image
:raises Error:
.. method:: copy(width=int, height=int, bands=int, format=Union[str, BandFormat], coding=Union[str, Coding], interpretation=Union[str, Interpretation], xres=float, yres=float, xoffset=int, yoffset=int)
Copy an image.
Example:
out = in.copy(width=int, height=int, bands=int, format=Union[str, BandFormat], coding=Union[str, Coding], interpretation=Union[str, Interpretation], xres=float, yres=float, xoffset=int, yoffset=int)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param bands: Number of bands in image
:type bands: int
:param format: Pixel format in image
:type format: Union[str, BandFormat]
:param coding: Pixel coding
:type coding: Union[str, Coding]
:param interpretation: Pixel interpretation
:type interpretation: Union[str, Interpretation]
:param xres: Horizontal resolution in pixels/mm
:type xres: float
:param yres: Vertical resolution in pixels/mm
:type yres: float
:param xoffset: Horizontal offset of origin
:type xoffset: int
:param yoffset: Vertical offset of origin
:type yoffset: int
:rtype: Image
:raises Error:
.. method:: countlines(direction)
Count lines in an image.
Example:
nolines = in.countlines(direction)
:param direction: Countlines left-right or up-down
:type direction: Union[str, Direction]
:rtype: float
:raises Error:
.. method:: crop(left, top, width, height)
Extract an area from an image.
Example:
out = input.crop(left, top, width, height)
:param left: Left edge of extract area
:type left: int
:param top: Top edge of extract area
:type top: int
:param width: Width of extract area
:type width: int
:param height: Height of extract area
:type height: int
:rtype: Image
:raises Error:
.. staticmethod:: csvload(filename, skip=int, lines=int, whitespace=str, separator=str, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load csv.
Example:
out = pyvips.Image.csvload(filename, skip=int, lines=int, whitespace=str, separator=str, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param skip: Skip this many lines at the start of the file
:type skip: int
:param lines: Read this many lines from the file
:type lines: int
:param whitespace: Set of whitespace characters
:type whitespace: str
:param separator: Set of separator characters
:type separator: str
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: csvload_source(source, skip=int, lines=int, whitespace=str, separator=str, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load csv.
Example:
out = pyvips.Image.csvload_source(source, skip=int, lines=int, whitespace=str, separator=str, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param skip: Skip this many lines at the start of the file
:type skip: int
:param lines: Read this many lines from the file
:type lines: int
:param whitespace: Set of whitespace characters
:type whitespace: str
:param separator: Set of separator characters
:type separator: str
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: csvsave(filename, separator=str, keep=int, background=list[float], page_height=int, profile=str)
Save image to csv.
Example:
in.csvsave(filename, separator=str, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param separator: Separator characters
:type separator: str
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: csvsave_target(target, separator=str, keep=int, background=list[float], page_height=int, profile=str)
Save image to csv.
Example:
in.csvsave_target(target, separator=str, keep=int, background=list[float], page_height=int, profile=str)
:param target: Target to save to
:type target: Target
:param separator: Separator characters
:type separator: str
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: dE00(right)
Calculate dE00.
Example:
out = left.dE00(right)
:param right: Right-hand input image
:type right: Image
:rtype: Image
:raises Error:
.. method:: dE76(right)
Calculate dE76.
Example:
out = left.dE76(right)
:param right: Right-hand input image
:type right: Image
:rtype: Image
:raises Error:
.. method:: dECMC(right)
Calculate dECMC.
Example:
out = left.dECMC(right)
:param right: Right-hand input image
:type right: Image
:rtype: Image
:raises Error:
.. staticmethod:: dcrawload(filename, bitdepth=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load RAW camera files.
Example:
out = pyvips.Image.dcrawload(filename, bitdepth=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param bitdepth: Number of bits per pixel
:type bitdepth: int
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: dcrawload_buffer(buffer, bitdepth=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load RAW camera files.
Example:
out = pyvips.Image.dcrawload_buffer(buffer, bitdepth=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param buffer: Buffer to load from
:type buffer: str
:param bitdepth: Number of bits per pixel
:type bitdepth: int
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: dcrawload_source(source, bitdepth=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load RAW camera files.
Example:
out = pyvips.Image.dcrawload_source(source, bitdepth=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param bitdepth: Number of bits per pixel
:type bitdepth: int
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: deviate()
Find image standard deviation.
Example:
out = in.deviate()
:rtype: float
:raises Error:
.. method:: divide(right)
Divide two images.
Example:
out = left.divide(right)
:param right: Right-hand image argument
:type right: Image
:rtype: Image
:raises Error:
.. method:: draw_circle(ink, cx, cy, radius, fill=bool)
Draw a circle on an image.
Example:
image = image.draw_circle(ink, cx, cy, radius, fill=bool)
:param ink: Color for pixels
:type ink: list[float]
:param cx: Centre of draw_circle
:type cx: int
:param cy: Centre of draw_circle
:type cy: int
:param radius: Radius in pixels
:type radius: int
:param fill: Draw a solid object
:type fill: bool
:rtype: Image
:raises Error:
.. method:: draw_flood(ink, x, y, test=Image, equal=bool, left=bool, top=bool, width=bool, height=bool)
Flood-fill an area.
Example:
image = image.draw_flood(ink, x, y, test=Image, equal=bool)
:param ink: Color for pixels
:type ink: list[float]
:param x: DrawFlood start point
:type x: int
:param y: DrawFlood start point
:type y: int
:param test: Test pixels in this image
:type test: Image
:param equal: DrawFlood while equal to edge
:type equal: bool
:param left: enable output: Left edge of modified area
:type left: bool
:param top: enable output: Top edge of modified area
:type top: bool
:param width: enable output: Width of modified area
:type width: bool
:param height: enable output: Height of modified area
:type height: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: draw_image(sub, x, y, mode=Union[str, CombineMode])
Paint an image into another image.
Example:
image = image.draw_image(sub, x, y, mode=Union[str, CombineMode])
:param sub: Sub-image to insert into main image
:type sub: Image
:param x: Draw image here
:type x: int
:param y: Draw image here
:type y: int
:param mode: Combining mode
:type mode: Union[str, CombineMode]
:rtype: Image
:raises Error:
.. method:: draw_line(ink, x1, y1, x2, y2)
Draw a line on an image.
Example:
image = image.draw_line(ink, x1, y1, x2, y2)
:param ink: Color for pixels
:type ink: list[float]
:param x1: Start of draw_line
:type x1: int
:param y1: Start of draw_line
:type y1: int
:param x2: End of draw_line
:type x2: int
:param y2: End of draw_line
:type y2: int
:rtype: Image
:raises Error:
.. method:: draw_mask(ink, mask, x, y)
Draw a mask on an image.
Example:
image = image.draw_mask(ink, mask, x, y)
:param ink: Color for pixels
:type ink: list[float]
:param mask: Mask of pixels to draw
:type mask: Image
:param x: Draw mask here
:type x: int
:param y: Draw mask here
:type y: int
:rtype: Image
:raises Error:
.. method:: draw_rect(ink, left, top, width, height, fill=bool)
Paint a rectangle on an image.
Example:
image = image.draw_rect(ink, left, top, width, height, fill=bool)
:param ink: Color for pixels
:type ink: list[float]
:param left: Rect to fill
:type left: int
:param top: Rect to fill
:type top: int
:param width: Rect to fill
:type width: int
:param height: Rect to fill
:type height: int
:param fill: Draw a solid object
:type fill: bool
:rtype: Image
:raises Error:
.. method:: draw_smudge(left, top, width, height)
Blur a rectangle on an image.
Example:
image = image.draw_smudge(left, top, width, height)
:param left: Rect to fill
:type left: int
:param top: Rect to fill
:type top: int
:param width: Rect to fill
:type width: int
:param height: Rect to fill
:type height: int
:rtype: Image
:raises Error:
.. method:: dzsave(filename, imagename=str, layout=Union[str, ForeignDzLayout], suffix=str, overlap=int, tile_size=int, centre=bool, depth=Union[str, ForeignDzDepth], angle=Union[str, Angle], container=Union[str, ForeignDzContainer], compression=int, region_shrink=Union[str, RegionShrink], skip_blanks=int, id=str, Q=int, keep=int, background=list[float], page_height=int, profile=str)
Save image to deepzoom file.
Example:
in.dzsave(filename, imagename=str, layout=Union[str, ForeignDzLayout], suffix=str, overlap=int, tile_size=int, centre=bool, depth=Union[str, ForeignDzDepth], angle=Union[str, Angle], container=Union[str, ForeignDzContainer], compression=int, region_shrink=Union[str, RegionShrink], skip_blanks=int, id=str, Q=int, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param imagename: Image name
:type imagename: str
:param layout: Directory layout
:type layout: Union[str, ForeignDzLayout]
:param suffix: Filename suffix for tiles
:type suffix: str
:param overlap: Tile overlap in pixels
:type overlap: int
:param tile_size: Tile size in pixels
:type tile_size: int
:param centre: Center image in tile
:type centre: bool
:param depth: Pyramid depth
:type depth: Union[str, ForeignDzDepth]
:param angle: Rotate image during save
:type angle: Union[str, Angle]
:param container: Pyramid container type
:type container: Union[str, ForeignDzContainer]
:param compression: ZIP deflate compression level
:type compression: int
:param region_shrink: Method to shrink regions
:type region_shrink: Union[str, RegionShrink]
:param skip_blanks: Skip tiles which are nearly equal to the background
:type skip_blanks: int
:param id: Resource ID
:type id: str
:param Q: Q factor
:type Q: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: dzsave_buffer(imagename=str, layout=Union[str, ForeignDzLayout], suffix=str, overlap=int, tile_size=int, centre=bool, depth=Union[str, ForeignDzDepth], angle=Union[str, Angle], container=Union[str, ForeignDzContainer], compression=int, region_shrink=Union[str, RegionShrink], skip_blanks=int, id=str, Q=int, keep=int, background=list[float], page_height=int, profile=str)
Save image to dz buffer.
Example:
buffer = in.dzsave_buffer(imagename=str, layout=Union[str, ForeignDzLayout], suffix=str, overlap=int, tile_size=int, centre=bool, depth=Union[str, ForeignDzDepth], angle=Union[str, Angle], container=Union[str, ForeignDzContainer], compression=int, region_shrink=Union[str, RegionShrink], skip_blanks=int, id=str, Q=int, keep=int, background=list[float], page_height=int, profile=str)
:param imagename: Image name
:type imagename: str
:param layout: Directory layout
:type layout: Union[str, ForeignDzLayout]
:param suffix: Filename suffix for tiles
:type suffix: str
:param overlap: Tile overlap in pixels
:type overlap: int
:param tile_size: Tile size in pixels
:type tile_size: int
:param centre: Center image in tile
:type centre: bool
:param depth: Pyramid depth
:type depth: Union[str, ForeignDzDepth]
:param angle: Rotate image during save
:type angle: Union[str, Angle]
:param container: Pyramid container type
:type container: Union[str, ForeignDzContainer]
:param compression: ZIP deflate compression level
:type compression: int
:param region_shrink: Method to shrink regions
:type region_shrink: Union[str, RegionShrink]
:param skip_blanks: Skip tiles which are nearly equal to the background
:type skip_blanks: int
:param id: Resource ID
:type id: str
:param Q: Q factor
:type Q: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: str
:raises Error:
.. method:: dzsave_target(target, imagename=str, layout=Union[str, ForeignDzLayout], suffix=str, overlap=int, tile_size=int, centre=bool, depth=Union[str, ForeignDzDepth], angle=Union[str, Angle], container=Union[str, ForeignDzContainer], compression=int, region_shrink=Union[str, RegionShrink], skip_blanks=int, id=str, Q=int, keep=int, background=list[float], page_height=int, profile=str)
Save image to deepzoom target.
Example:
in.dzsave_target(target, imagename=str, layout=Union[str, ForeignDzLayout], suffix=str, overlap=int, tile_size=int, centre=bool, depth=Union[str, ForeignDzDepth], angle=Union[str, Angle], container=Union[str, ForeignDzContainer], compression=int, region_shrink=Union[str, RegionShrink], skip_blanks=int, id=str, Q=int, keep=int, background=list[float], page_height=int, profile=str)
:param target: Target to save to
:type target: Target
:param imagename: Image name
:type imagename: str
:param layout: Directory layout
:type layout: Union[str, ForeignDzLayout]
:param suffix: Filename suffix for tiles
:type suffix: str
:param overlap: Tile overlap in pixels
:type overlap: int
:param tile_size: Tile size in pixels
:type tile_size: int
:param centre: Center image in tile
:type centre: bool
:param depth: Pyramid depth
:type depth: Union[str, ForeignDzDepth]
:param angle: Rotate image during save
:type angle: Union[str, Angle]
:param container: Pyramid container type
:type container: Union[str, ForeignDzContainer]
:param compression: ZIP deflate compression level
:type compression: int
:param region_shrink: Method to shrink regions
:type region_shrink: Union[str, RegionShrink]
:param skip_blanks: Skip tiles which are nearly equal to the background
:type skip_blanks: int
:param id: Resource ID
:type id: str
:param Q: Q factor
:type Q: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: embed(x, y, width, height, extend=Union[str, Extend], background=list[float])
Embed an image in a larger image.
Example:
out = in.embed(x, y, width, height, extend=Union[str, Extend], background=list[float])
:param x: Left edge of input in output
:type x: int
:param y: Top edge of input in output
:type y: int
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param extend: How to generate the extra pixels
:type extend: Union[str, Extend]
:param background: Color for background pixels
:type background: list[float]
:rtype: Image
:raises Error:
.. method:: extract_area(left, top, width, height)
Extract an area from an image.
Example:
out = input.extract_area(left, top, width, height)
:param left: Left edge of extract area
:type left: int
:param top: Top edge of extract area
:type top: int
:param width: Width of extract area
:type width: int
:param height: Height of extract area
:type height: int
:rtype: Image
:raises Error:
.. method:: extract_band(band, n=int)
Extract band from an image.
Example:
out = in.extract_band(band, n=int)
:param band: Band to extract
:type band: int
:param n: Number of bands to extract
:type n: int
:rtype: Image
:raises Error:
.. staticmethod:: eye(width, height, uchar=bool, factor=float)
Make an image showing the eye's spatial response.
Example:
out = pyvips.Image.eye(width, height, uchar=bool, factor=float)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param uchar: Output an unsigned char image
:type uchar: bool
:param factor: Maximum spatial frequency
:type factor: float
:rtype: Image
:raises Error:
.. method:: falsecolour()
False-color an image.
Example:
out = in.falsecolour()
:rtype: Image
:raises Error:
.. method:: fastcor(ref)
Fast correlation.
Example:
out = in.fastcor(ref)
:param ref: Input reference image
:type ref: Image
:rtype: Image
:raises Error:
.. method:: fill_nearest(distance=bool)
Fill image zeros with nearest non-zero pixel.
Example:
out = in.fill_nearest()
:param distance: enable output: Distance to nearest non-zero pixel
:type distance: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: find_trim(threshold=float, background=list[float], line_art=bool)
Search an image for non-edge areas.
Example:
left, top, width, height = in.find_trim(threshold=float, background=list[float], line_art=bool)
:param threshold: Object threshold
:type threshold: float
:param background: Color for background pixels
:type background: list[float]
:param line_art: Enable line art mode
:type line_art: bool
:rtype: list[int, int, int, int]
:raises Error:
.. staticmethod:: fitsload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load a FITS image.
Example:
out = pyvips.Image.fitsload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: fitsload_source(source, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load FITS from a source.
Example:
out = pyvips.Image.fitsload_source(source, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: fitssave(filename, keep=int, background=list[float], page_height=int, profile=str)
Save image to fits file.
Example:
in.fitssave(filename, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: flatten(background=list[float], max_alpha=float)
Flatten alpha out of an image.
Example:
out = in.flatten(background=list[float], max_alpha=float)
:param background: Background value
:type background: list[float]
:param max_alpha: Maximum value of alpha channel
:type max_alpha: float
:rtype: Image
:raises Error:
.. method:: flip(direction)
Flip an image.
Example:
out = in.flip(direction)
:param direction: Direction to flip image
:type direction: Union[str, Direction]
:rtype: Image
:raises Error:
.. method:: float2rad()
Transform float RGB to Radiance coding.
Example:
out = in.float2rad()
:rtype: Image
:raises Error:
.. staticmethod:: fractsurf(width, height, fractal_dimension)
Make a fractal surface.
Example:
out = pyvips.Image.fractsurf(width, height, fractal_dimension)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param fractal_dimension: Fractal dimension
:type fractal_dimension: float
:rtype: Image
:raises Error:
.. method:: freqmult(mask)
Frequency-domain filtering.
Example:
out = in.freqmult(mask)
:param mask: Input mask image
:type mask: Image
:rtype: Image
:raises Error:
.. method:: fwfft()
Forward FFT.
Example:
out = in.fwfft()
:rtype: Image
:raises Error:
.. method:: gamma(exponent=float)
Gamma an image.
Example:
out = in.gamma(exponent=float)
:param exponent: Gamma factor
:type exponent: float
:rtype: Image
:raises Error:
.. method:: gaussblur(sigma, min_ampl=float, precision=Union[str, Precision])
Gaussian blur.
Example:
out = in.gaussblur(sigma, min_ampl=float, precision=Union[str, Precision])
:param sigma: Sigma of Gaussian
:type sigma: float
:param min_ampl: Minimum amplitude of Gaussian
:type min_ampl: float
:param precision: Convolve with this precision
:type precision: Union[str, Precision]
:rtype: Image
:raises Error:
.. staticmethod:: gaussmat(sigma, min_ampl, separable=bool, precision=Union[str, Precision])
Make a gaussian image.
Example:
out = pyvips.Image.gaussmat(sigma, min_ampl, separable=bool, precision=Union[str, Precision])
:param sigma: Sigma of Gaussian
:type sigma: float
:param min_ampl: Minimum amplitude of Gaussian
:type min_ampl: float
:param separable: Generate separable Gaussian
:type separable: bool
:param precision: Generate with this precision
:type precision: Union[str, Precision]
:rtype: Image
:raises Error:
.. staticmethod:: gaussnoise(width, height, sigma=float, mean=float, seed=int)
Make a gaussnoise image.
Example:
out = pyvips.Image.gaussnoise(width, height, sigma=float, mean=float, seed=int)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param sigma: Standard deviation of pixels in generated image
:type sigma: float
:param mean: Mean of pixels in generated image
:type mean: float
:param seed: Random number seed
:type seed: int
:rtype: Image
:raises Error:
.. method:: getpoint(x, y, unpack_complex=bool)
Read a point from an image.
Example:
out_array = in.getpoint(x, y, unpack_complex=bool)
:param x: Point to read
:type x: int
:param y: Point to read
:type y: int
:param unpack_complex: Complex pixels should be unpacked
:type unpack_complex: bool
:rtype: list[float]
:raises Error:
.. staticmethod:: gifload(filename, n=int, page=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load GIF with libnsgif.
Example:
out = pyvips.Image.gifload(filename, n=int, page=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param n: Number of pages to load, -1 for all
:type n: int
:param page: First page to load
:type page: int
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: gifload_buffer(buffer, n=int, page=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load GIF with libnsgif.
Example:
out = pyvips.Image.gifload_buffer(buffer, n=int, page=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param buffer: Buffer to load from
:type buffer: str
:param n: Number of pages to load, -1 for all
:type n: int
:param page: First page to load
:type page: int
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: gifload_source(source, n=int, page=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load gif from source.
Example:
out = pyvips.Image.gifload_source(source, n=int, page=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param n: Number of pages to load, -1 for all
:type n: int
:param page: First page to load
:type page: int
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: gifsave(filename, dither=float, effort=int, bitdepth=int, interframe_maxerror=float, reuse=bool, interpalette_maxerror=float, interlace=bool, keep_duplicate_frames=bool, keep=int, background=list[float], page_height=int, profile=str)
Save as gif.
Example:
in.gifsave(filename, dither=float, effort=int, bitdepth=int, interframe_maxerror=float, reuse=bool, interpalette_maxerror=float, interlace=bool, keep_duplicate_frames=bool, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param dither: Amount of dithering
:type dither: float
:param effort: Quantisation effort
:type effort: int
:param bitdepth: Number of bits per pixel
:type bitdepth: int
:param interframe_maxerror: Maximum inter-frame error for transparency
:type interframe_maxerror: float
:param reuse: Reuse palette from input
:type reuse: bool
:param interpalette_maxerror: Maximum inter-palette error for palette reusage
:type interpalette_maxerror: float
:param interlace: Generate an interlaced (progressive) GIF
:type interlace: bool
:param keep_duplicate_frames: Keep duplicate frames in the output instead of combining them
:type keep_duplicate_frames: bool
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: gifsave_buffer(dither=float, effort=int, bitdepth=int, interframe_maxerror=float, reuse=bool, interpalette_maxerror=float, interlace=bool, keep_duplicate_frames=bool, keep=int, background=list[float], page_height=int, profile=str)
Save as gif.
Example:
buffer = in.gifsave_buffer(dither=float, effort=int, bitdepth=int, interframe_maxerror=float, reuse=bool, interpalette_maxerror=float, interlace=bool, keep_duplicate_frames=bool, keep=int, background=list[float], page_height=int, profile=str)
:param dither: Amount of dithering
:type dither: float
:param effort: Quantisation effort
:type effort: int
:param bitdepth: Number of bits per pixel
:type bitdepth: int
:param interframe_maxerror: Maximum inter-frame error for transparency
:type interframe_maxerror: float
:param reuse: Reuse palette from input
:type reuse: bool
:param interpalette_maxerror: Maximum inter-palette error for palette reusage
:type interpalette_maxerror: float
:param interlace: Generate an interlaced (progressive) GIF
:type interlace: bool
:param keep_duplicate_frames: Keep duplicate frames in the output instead of combining them
:type keep_duplicate_frames: bool
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: str
:raises Error:
.. method:: gifsave_target(target, dither=float, effort=int, bitdepth=int, interframe_maxerror=float, reuse=bool, interpalette_maxerror=float, interlace=bool, keep_duplicate_frames=bool, keep=int, background=list[float], page_height=int, profile=str)
Save as gif.
Example:
in.gifsave_target(target, dither=float, effort=int, bitdepth=int, interframe_maxerror=float, reuse=bool, interpalette_maxerror=float, interlace=bool, keep_duplicate_frames=bool, keep=int, background=list[float], page_height=int, profile=str)
:param target: Target to save to
:type target: Target
:param dither: Amount of dithering
:type dither: float
:param effort: Quantisation effort
:type effort: int
:param bitdepth: Number of bits per pixel
:type bitdepth: int
:param interframe_maxerror: Maximum inter-frame error for transparency
:type interframe_maxerror: float
:param reuse: Reuse palette from input
:type reuse: bool
:param interpalette_maxerror: Maximum inter-palette error for palette reusage
:type interpalette_maxerror: float
:param interlace: Generate an interlaced (progressive) GIF
:type interlace: bool
:param keep_duplicate_frames: Keep duplicate frames in the output instead of combining them
:type keep_duplicate_frames: bool
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: globalbalance(gamma=float, int_output=bool)
Global balance an image mosaic.
Example:
out = in.globalbalance(gamma=float, int_output=bool)
:param gamma: Image gamma
:type gamma: float
:param int_output: Integer output
:type int_output: bool
:rtype: Image
:raises Error:
.. method:: gravity(direction, width, height, extend=Union[str, Extend], background=list[float])
Place an image within a larger image with a certain gravity.
Example:
out = in.gravity(direction, width, height, extend=Union[str, Extend], background=list[float])
:param direction: Direction to place image within width/height
:type direction: Union[str, CompassDirection]
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param extend: How to generate the extra pixels
:type extend: Union[str, Extend]
:param background: Color for background pixels
:type background: list[float]
:rtype: Image
:raises Error:
.. staticmethod:: grey(width, height, uchar=bool)
Make a grey ramp image.
Example:
out = pyvips.Image.grey(width, height, uchar=bool)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param uchar: Output an unsigned char image
:type uchar: bool
:rtype: Image
:raises Error:
.. method:: grid(tile_height, across, down)
Grid an image.
Example:
out = in.grid(tile_height, across, down)
:param tile_height: Chop into tiles this high
:type tile_height: int
:param across: Number of tiles across
:type across: int
:param down: Number of tiles down
:type down: int
:rtype: Image
:raises Error:
.. staticmethod:: heifload(filename, page=int, n=int, thumbnail=bool, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load a HEIF image.
Example:
out = pyvips.Image.heifload(filename, page=int, n=int, thumbnail=bool, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param thumbnail: Fetch thumbnail image
:type thumbnail: bool
:param unlimited: Remove all denial of service limits
:type unlimited: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: heifload_buffer(buffer, page=int, n=int, thumbnail=bool, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load a HEIF image.
Example:
out = pyvips.Image.heifload_buffer(buffer, page=int, n=int, thumbnail=bool, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param buffer: Buffer to load from
:type buffer: str
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param thumbnail: Fetch thumbnail image
:type thumbnail: bool
:param unlimited: Remove all denial of service limits
:type unlimited: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: heifload_source(source, page=int, n=int, thumbnail=bool, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load a HEIF image.
Example:
out = pyvips.Image.heifload_source(source, page=int, n=int, thumbnail=bool, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param thumbnail: Fetch thumbnail image
:type thumbnail: bool
:param unlimited: Remove all denial of service limits
:type unlimited: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: heifsave(filename, Q=int, bitdepth=int, lossless=bool, compression=Union[str, ForeignHeifCompression], effort=int, subsample_mode=Union[str, ForeignSubsample], encoder=Union[str, ForeignHeifEncoder], tune=str, keep=int, background=list[float], page_height=int, profile=str)
Save image in HEIF format.
Example:
in.heifsave(filename, Q=int, bitdepth=int, lossless=bool, compression=Union[str, ForeignHeifCompression], effort=int, subsample_mode=Union[str, ForeignSubsample], encoder=Union[str, ForeignHeifEncoder], tune=str, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param Q: Q factor
:type Q: int
:param bitdepth: Number of bits per pixel
:type bitdepth: int
:param lossless: Enable lossless compression
:type lossless: bool
:param compression: Compression format
:type compression: Union[str, ForeignHeifCompression]
:param effort: CPU effort
:type effort: int
:param subsample_mode: Select chroma subsample operation mode
:type subsample_mode: Union[str, ForeignSubsample]
:param encoder: Select encoder to use
:type encoder: Union[str, ForeignHeifEncoder]
:param tune: Tuning parameters
:type tune: str
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: heifsave_buffer(Q=int, bitdepth=int, lossless=bool, compression=Union[str, ForeignHeifCompression], effort=int, subsample_mode=Union[str, ForeignSubsample], encoder=Union[str, ForeignHeifEncoder], tune=str, keep=int, background=list[float], page_height=int, profile=str)
Save image in HEIF format.
Example:
buffer = in.heifsave_buffer(Q=int, bitdepth=int, lossless=bool, compression=Union[str, ForeignHeifCompression], effort=int, subsample_mode=Union[str, ForeignSubsample], encoder=Union[str, ForeignHeifEncoder], tune=str, keep=int, background=list[float], page_height=int, profile=str)
:param Q: Q factor
:type Q: int
:param bitdepth: Number of bits per pixel
:type bitdepth: int
:param lossless: Enable lossless compression
:type lossless: bool
:param compression: Compression format
:type compression: Union[str, ForeignHeifCompression]
:param effort: CPU effort
:type effort: int
:param subsample_mode: Select chroma subsample operation mode
:type subsample_mode: Union[str, ForeignSubsample]
:param encoder: Select encoder to use
:type encoder: Union[str, ForeignHeifEncoder]
:param tune: Tuning parameters
:type tune: str
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: str
:raises Error:
.. method:: heifsave_target(target, Q=int, bitdepth=int, lossless=bool, compression=Union[str, ForeignHeifCompression], effort=int, subsample_mode=Union[str, ForeignSubsample], encoder=Union[str, ForeignHeifEncoder], tune=str, keep=int, background=list[float], page_height=int, profile=str)
Save image in HEIF format.
Example:
in.heifsave_target(target, Q=int, bitdepth=int, lossless=bool, compression=Union[str, ForeignHeifCompression], effort=int, subsample_mode=Union[str, ForeignSubsample], encoder=Union[str, ForeignHeifEncoder], tune=str, keep=int, background=list[float], page_height=int, profile=str)
:param target: Target to save to
:type target: Target
:param Q: Q factor
:type Q: int
:param bitdepth: Number of bits per pixel
:type bitdepth: int
:param lossless: Enable lossless compression
:type lossless: bool
:param compression: Compression format
:type compression: Union[str, ForeignHeifCompression]
:param effort: CPU effort
:type effort: int
:param subsample_mode: Select chroma subsample operation mode
:type subsample_mode: Union[str, ForeignSubsample]
:param encoder: Select encoder to use
:type encoder: Union[str, ForeignHeifEncoder]
:param tune: Tuning parameters
:type tune: str
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: hist_cum()
Form cumulative histogram.
Example:
out = in.hist_cum()
:rtype: Image
:raises Error:
.. method:: hist_entropy()
Estimate image entropy.
Example:
out = in.hist_entropy()
:rtype: float
:raises Error:
.. method:: hist_equal(band=int)
Histogram equalisation.
Example:
out = in.hist_equal(band=int)
:param band: Equalise with this band
:type band: int
:rtype: Image
:raises Error:
.. method:: hist_find(band=int)
Find image histogram.
Example:
out = in.hist_find(band=int)
:param band: Find histogram of band
:type band: int
:rtype: Image
:raises Error:
.. method:: hist_find_indexed(index, combine=Union[str, Combine])
Find indexed image histogram.
Example:
out = in.hist_find_indexed(index, combine=Union[str, Combine])
:param index: Index image
:type index: Image
:param combine: Combine bins like this
:type combine: Union[str, Combine]
:rtype: Image
:raises Error:
.. method:: hist_find_ndim(bins=int)
Find n-dimensional image histogram.
Example:
out = in.hist_find_ndim(bins=int)
:param bins: Number of bins in each dimension
:type bins: int
:rtype: Image
:raises Error:
.. method:: hist_ismonotonic()
Test for monotonicity.
Example:
monotonic = in.hist_ismonotonic()
:rtype: bool
:raises Error:
.. method:: hist_local(width, height, max_slope=int)
Local histogram equalisation.
Example:
out = in.hist_local(width, height, max_slope=int)
:param width: Window width in pixels
:type width: int
:param height: Window height in pixels
:type height: int
:param max_slope: Maximum slope (CLAHE)
:type max_slope: int
:rtype: Image
:raises Error:
.. method:: hist_match(ref)
Match two histograms.
Example:
out = in.hist_match(ref)
:param ref: Reference histogram
:type ref: Image
:rtype: Image
:raises Error:
.. method:: hist_norm()
Normalise histogram.
Example:
out = in.hist_norm()
:rtype: Image
:raises Error:
.. method:: hist_plot()
Plot histogram.
Example:
out = in.hist_plot()
:rtype: Image
:raises Error:
.. method:: hough_circle(scale=int, min_radius=int, max_radius=int)
Find hough circle transform.
Example:
out = in.hough_circle(scale=int, min_radius=int, max_radius=int)
:param scale: Scale down dimensions by this factor
:type scale: int
:param min_radius: Smallest radius to search for
:type min_radius: int
:param max_radius: Largest radius to search for
:type max_radius: int
:rtype: Image
:raises Error:
.. method:: hough_line(width=int, height=int)
Find hough line transform.
Example:
out = in.hough_line(width=int, height=int)
:param width: Horizontal size of parameter space
:type width: int
:param height: Vertical size of parameter space
:type height: int
:rtype: Image
:raises Error:
.. method:: icc_export(pcs=Union[str, PCS], intent=Union[str, Intent], black_point_compensation=bool, output_profile=str, depth=int)
Output to device with ICC profile.
Example:
out = in.icc_export(pcs=Union[str, PCS], intent=Union[str, Intent], black_point_compensation=bool, output_profile=str, depth=int)
:param pcs: Set Profile Connection Space
:type pcs: Union[str, PCS]
:param intent: Rendering intent
:type intent: Union[str, Intent]
:param black_point_compensation: Enable black point compensation
:type black_point_compensation: bool
:param output_profile: Filename to load output profile from
:type output_profile: str
:param depth: Output device space depth in bits
:type depth: int
:rtype: Image
:raises Error:
.. method:: icc_import(pcs=Union[str, PCS], intent=Union[str, Intent], black_point_compensation=bool, embedded=bool, input_profile=str)
Import from device with ICC profile.
Example:
out = in.icc_import(pcs=Union[str, PCS], intent=Union[str, Intent], black_point_compensation=bool, embedded=bool, input_profile=str)
:param pcs: Set Profile Connection Space
:type pcs: Union[str, PCS]
:param intent: Rendering intent
:type intent: Union[str, Intent]
:param black_point_compensation: Enable black point compensation
:type black_point_compensation: bool
:param embedded: Use embedded input profile, if available
:type embedded: bool
:param input_profile: Filename to load input profile from
:type input_profile: str
:rtype: Image
:raises Error:
.. method:: icc_transform(output_profile, pcs=Union[str, PCS], intent=Union[str, Intent], black_point_compensation=bool, embedded=bool, input_profile=str, depth=int)
Transform between devices with ICC profiles.
Example:
out = in.icc_transform(output_profile, pcs=Union[str, PCS], intent=Union[str, Intent], black_point_compensation=bool, embedded=bool, input_profile=str, depth=int)
:param output_profile: Filename to load output profile from
:type output_profile: str
:param pcs: Set Profile Connection Space
:type pcs: Union[str, PCS]
:param intent: Rendering intent
:type intent: Union[str, Intent]
:param black_point_compensation: Enable black point compensation
:type black_point_compensation: bool
:param embedded: Use embedded input profile, if available
:type embedded: bool
:param input_profile: Filename to load input profile from
:type input_profile: str
:param depth: Output device space depth in bits
:type depth: int
:rtype: Image
:raises Error:
.. staticmethod:: identity(bands=int, ushort=bool, size=int)
Make a 1D image where pixel values are indexes.
Example:
out = pyvips.Image.identity(bands=int, ushort=bool, size=int)
:param bands: Number of bands in LUT
:type bands: int
:param ushort: Create a 16-bit LUT
:type ushort: bool
:param size: Size of 16-bit LUT
:type size: int
:rtype: Image
:raises Error:
.. method:: insert(sub, x, y, expand=bool, background=list[float])
Insert image @sub into @main at @x, @y.
Example:
out = main.insert(sub, x, y, expand=bool, background=list[float])
:param sub: Sub-image to insert into main image
:type sub: Image
:param x: Left edge of sub in main
:type x: int
:param y: Top edge of sub in main
:type y: int
:param expand: Expand output to hold all of both inputs
:type expand: bool
:param background: Color for new pixels
:type background: list[float]
:rtype: Image
:raises Error:
.. method:: invert()
Invert an image.
Example:
out = in.invert()
:rtype: Image
:raises Error:
.. method:: invertlut(size=int)
Build an inverted look-up table.
Example:
out = in.invertlut(size=int)
:param size: LUT size to generate
:type size: int
:rtype: Image
:raises Error:
.. method:: invfft(real=bool)
Inverse FFT.
Example:
out = in.invfft(real=bool)
:param real: Output only the real part of the transform
:type real: bool
:rtype: Image
:raises Error:
.. method:: join(in2, direction, expand=bool, shim=int, background=list[float], align=Union[str, Align])
Join a pair of images.
Example:
out = in1.join(in2, direction, expand=bool, shim=int, background=list[float], align=Union[str, Align])
:param in2: Second input image
:type in2: Image
:param direction: Join left-right or up-down
:type direction: Union[str, Direction]
:param expand: Expand output to hold all of both inputs
:type expand: bool
:param shim: Pixels between images
:type shim: int
:param background: Colour for new pixels
:type background: list[float]
:param align: Align on the low, centre or high coordinate edge
:type align: Union[str, Align]
:rtype: Image
:raises Error:
.. staticmethod:: jp2kload(filename, page=int, oneshot=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load JPEG2000 image.
Example:
out = pyvips.Image.jp2kload(filename, page=int, oneshot=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param page: Load this page from the image
:type page: int
:param oneshot: Load images a frame at a time
:type oneshot: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: jp2kload_buffer(buffer, page=int, oneshot=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load JPEG2000 image.
Example:
out = pyvips.Image.jp2kload_buffer(buffer, page=int, oneshot=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param buffer: Buffer to load from
:type buffer: str
:param page: Load this page from the image
:type page: int
:param oneshot: Load images a frame at a time
:type oneshot: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: jp2kload_source(source, page=int, oneshot=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load JPEG2000 image.
Example:
out = pyvips.Image.jp2kload_source(source, page=int, oneshot=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param page: Load this page from the image
:type page: int
:param oneshot: Load images a frame at a time
:type oneshot: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: jp2ksave(filename, tile_width=int, tile_height=int, lossless=bool, Q=int, subsample_mode=Union[str, ForeignSubsample], keep=int, background=list[float], page_height=int, profile=str)
Save image in JPEG2000 format.
Example:
in.jp2ksave(filename, tile_width=int, tile_height=int, lossless=bool, Q=int, subsample_mode=Union[str, ForeignSubsample], keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param tile_width: Tile width in pixels
:type tile_width: int
:param tile_height: Tile height in pixels
:type tile_height: int
:param lossless: Enable lossless compression
:type lossless: bool
:param Q: Q factor
:type Q: int
:param subsample_mode: Select chroma subsample operation mode
:type subsample_mode: Union[str, ForeignSubsample]
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: jp2ksave_buffer(tile_width=int, tile_height=int, lossless=bool, Q=int, subsample_mode=Union[str, ForeignSubsample], keep=int, background=list[float], page_height=int, profile=str)
Save image in JPEG2000 format.
Example:
buffer = in.jp2ksave_buffer(tile_width=int, tile_height=int, lossless=bool, Q=int, subsample_mode=Union[str, ForeignSubsample], keep=int, background=list[float], page_height=int, profile=str)
:param tile_width: Tile width in pixels
:type tile_width: int
:param tile_height: Tile height in pixels
:type tile_height: int
:param lossless: Enable lossless compression
:type lossless: bool
:param Q: Q factor
:type Q: int
:param subsample_mode: Select chroma subsample operation mode
:type subsample_mode: Union[str, ForeignSubsample]
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: str
:raises Error:
.. method:: jp2ksave_target(target, tile_width=int, tile_height=int, lossless=bool, Q=int, subsample_mode=Union[str, ForeignSubsample], keep=int, background=list[float], page_height=int, profile=str)
Save image in JPEG2000 format.
Example:
in.jp2ksave_target(target, tile_width=int, tile_height=int, lossless=bool, Q=int, subsample_mode=Union[str, ForeignSubsample], keep=int, background=list[float], page_height=int, profile=str)
:param target: Target to save to
:type target: Target
:param tile_width: Tile width in pixels
:type tile_width: int
:param tile_height: Tile height in pixels
:type tile_height: int
:param lossless: Enable lossless compression
:type lossless: bool
:param Q: Q factor
:type Q: int
:param subsample_mode: Select chroma subsample operation mode
:type subsample_mode: Union[str, ForeignSubsample]
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. staticmethod:: jpegload(filename, shrink=int, autorotate=bool, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load jpeg from file.
Example:
out = pyvips.Image.jpegload(filename, shrink=int, autorotate=bool, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param shrink: Shrink factor on load
:type shrink: int
:param autorotate: Rotate image using exif orientation
:type autorotate: bool
:param unlimited: Remove all denial of service limits
:type unlimited: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: jpegload_buffer(buffer, shrink=int, autorotate=bool, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load jpeg from buffer.
Example:
out = pyvips.Image.jpegload_buffer(buffer, shrink=int, autorotate=bool, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param buffer: Buffer to load from
:type buffer: str
:param shrink: Shrink factor on load
:type shrink: int
:param autorotate: Rotate image using exif orientation
:type autorotate: bool
:param unlimited: Remove all denial of service limits
:type unlimited: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: jpegload_source(source, shrink=int, autorotate=bool, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load image from jpeg source.
Example:
out = pyvips.Image.jpegload_source(source, shrink=int, autorotate=bool, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param shrink: Shrink factor on load
:type shrink: int
:param autorotate: Rotate image using exif orientation
:type autorotate: bool
:param unlimited: Remove all denial of service limits
:type unlimited: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: jpegsave(filename, Q=int, optimize_coding=bool, interlace=bool, trellis_quant=bool, overshoot_deringing=bool, optimize_scans=bool, quant_table=int, subsample_mode=Union[str, ForeignSubsample], restart_interval=int, keep=int, background=list[float], page_height=int, profile=str)
Save as jpeg.
Example:
in.jpegsave(filename, Q=int, optimize_coding=bool, interlace=bool, trellis_quant=bool, overshoot_deringing=bool, optimize_scans=bool, quant_table=int, subsample_mode=Union[str, ForeignSubsample], restart_interval=int, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param Q: Q factor
:type Q: int
:param optimize_coding: Compute optimal Huffman coding tables
:type optimize_coding: bool
:param interlace: Generate an interlaced (progressive) jpeg
:type interlace: bool
:param trellis_quant: Apply trellis quantisation to each 8x8 block
:type trellis_quant: bool
:param overshoot_deringing: Apply overshooting to samples with extreme values
:type overshoot_deringing: bool
:param optimize_scans: Split spectrum of DCT coefficients into separate scans
:type optimize_scans: bool
:param quant_table: Use predefined quantization table with given index
:type quant_table: int
:param subsample_mode: Select chroma subsample operation mode
:type subsample_mode: Union[str, ForeignSubsample]
:param restart_interval: Add restart markers every specified number of mcu
:type restart_interval: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: jpegsave_buffer(Q=int, optimize_coding=bool, interlace=bool, trellis_quant=bool, overshoot_deringing=bool, optimize_scans=bool, quant_table=int, subsample_mode=Union[str, ForeignSubsample], restart_interval=int, keep=int, background=list[float], page_height=int, profile=str)
Save as jpeg.
Example:
buffer = in.jpegsave_buffer(Q=int, optimize_coding=bool, interlace=bool, trellis_quant=bool, overshoot_deringing=bool, optimize_scans=bool, quant_table=int, subsample_mode=Union[str, ForeignSubsample], restart_interval=int, keep=int, background=list[float], page_height=int, profile=str)
:param Q: Q factor
:type Q: int
:param optimize_coding: Compute optimal Huffman coding tables
:type optimize_coding: bool
:param interlace: Generate an interlaced (progressive) jpeg
:type interlace: bool
:param trellis_quant: Apply trellis quantisation to each 8x8 block
:type trellis_quant: bool
:param overshoot_deringing: Apply overshooting to samples with extreme values
:type overshoot_deringing: bool
:param optimize_scans: Split spectrum of DCT coefficients into separate scans
:type optimize_scans: bool
:param quant_table: Use predefined quantization table with given index
:type quant_table: int
:param subsample_mode: Select chroma subsample operation mode
:type subsample_mode: Union[str, ForeignSubsample]
:param restart_interval: Add restart markers every specified number of mcu
:type restart_interval: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: str
:raises Error:
.. method:: jpegsave_mime(Q=int, optimize_coding=bool, interlace=bool, trellis_quant=bool, overshoot_deringing=bool, optimize_scans=bool, quant_table=int, subsample_mode=Union[str, ForeignSubsample], restart_interval=int, keep=int, background=list[float], page_height=int, profile=str)
Save image to jpeg mime.
Example:
in.jpegsave_mime(Q=int, optimize_coding=bool, interlace=bool, trellis_quant=bool, overshoot_deringing=bool, optimize_scans=bool, quant_table=int, subsample_mode=Union[str, ForeignSubsample], restart_interval=int, keep=int, background=list[float], page_height=int, profile=str)
:param Q: Q factor
:type Q: int
:param optimize_coding: Compute optimal Huffman coding tables
:type optimize_coding: bool
:param interlace: Generate an interlaced (progressive) jpeg
:type interlace: bool
:param trellis_quant: Apply trellis quantisation to each 8x8 block
:type trellis_quant: bool
:param overshoot_deringing: Apply overshooting to samples with extreme values
:type overshoot_deringing: bool
:param optimize_scans: Split spectrum of DCT coefficients into separate scans
:type optimize_scans: bool
:param quant_table: Use predefined quantization table with given index
:type quant_table: int
:param subsample_mode: Select chroma subsample operation mode
:type subsample_mode: Union[str, ForeignSubsample]
:param restart_interval: Add restart markers every specified number of mcu
:type restart_interval: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: jpegsave_target(target, Q=int, optimize_coding=bool, interlace=bool, trellis_quant=bool, overshoot_deringing=bool, optimize_scans=bool, quant_table=int, subsample_mode=Union[str, ForeignSubsample], restart_interval=int, keep=int, background=list[float], page_height=int, profile=str)
Save as jpeg.
Example:
in.jpegsave_target(target, Q=int, optimize_coding=bool, interlace=bool, trellis_quant=bool, overshoot_deringing=bool, optimize_scans=bool, quant_table=int, subsample_mode=Union[str, ForeignSubsample], restart_interval=int, keep=int, background=list[float], page_height=int, profile=str)
:param target: Target to save to
:type target: Target
:param Q: Q factor
:type Q: int
:param optimize_coding: Compute optimal Huffman coding tables
:type optimize_coding: bool
:param interlace: Generate an interlaced (progressive) jpeg
:type interlace: bool
:param trellis_quant: Apply trellis quantisation to each 8x8 block
:type trellis_quant: bool
:param overshoot_deringing: Apply overshooting to samples with extreme values
:type overshoot_deringing: bool
:param optimize_scans: Split spectrum of DCT coefficients into separate scans
:type optimize_scans: bool
:param quant_table: Use predefined quantization table with given index
:type quant_table: int
:param subsample_mode: Select chroma subsample operation mode
:type subsample_mode: Union[str, ForeignSubsample]
:param restart_interval: Add restart markers every specified number of mcu
:type restart_interval: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. staticmethod:: jxlload(filename, page=int, n=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load JPEG-XL image.
Example:
out = pyvips.Image.jxlload(filename, page=int, n=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: jxlload_buffer(buffer, page=int, n=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load JPEG-XL image.
Example:
out = pyvips.Image.jxlload_buffer(buffer, page=int, n=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param buffer: Buffer to load from
:type buffer: str
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: jxlload_source(source, page=int, n=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load JPEG-XL image.
Example:
out = pyvips.Image.jxlload_source(source, page=int, n=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: jxlsave(filename, tier=int, distance=float, effort=int, lossless=bool, Q=int, bitdepth=int, keep=int, background=list[float], page_height=int, profile=str)
Save image in JPEG-XL format.
Example:
in.jxlsave(filename, tier=int, distance=float, effort=int, lossless=bool, Q=int, bitdepth=int, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param tier: Decode speed tier
:type tier: int
:param distance: Target butteraugli distance
:type distance: float
:param effort: Encoding effort
:type effort: int
:param lossless: Enable lossless compression
:type lossless: bool
:param Q: Quality factor
:type Q: int
:param bitdepth: Bit depth
:type bitdepth: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: jxlsave_buffer(tier=int, distance=float, effort=int, lossless=bool, Q=int, bitdepth=int, keep=int, background=list[float], page_height=int, profile=str)
Save image in JPEG-XL format.
Example:
buffer = in.jxlsave_buffer(tier=int, distance=float, effort=int, lossless=bool, Q=int, bitdepth=int, keep=int, background=list[float], page_height=int, profile=str)
:param tier: Decode speed tier
:type tier: int
:param distance: Target butteraugli distance
:type distance: float
:param effort: Encoding effort
:type effort: int
:param lossless: Enable lossless compression
:type lossless: bool
:param Q: Quality factor
:type Q: int
:param bitdepth: Bit depth
:type bitdepth: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: str
:raises Error:
.. method:: jxlsave_target(target, tier=int, distance=float, effort=int, lossless=bool, Q=int, bitdepth=int, keep=int, background=list[float], page_height=int, profile=str)
Save image in JPEG-XL format.
Example:
in.jxlsave_target(target, tier=int, distance=float, effort=int, lossless=bool, Q=int, bitdepth=int, keep=int, background=list[float], page_height=int, profile=str)
:param target: Target to save to
:type target: Target
:param tier: Decode speed tier
:type tier: int
:param distance: Target butteraugli distance
:type distance: float
:param effort: Encoding effort
:type effort: int
:param lossless: Enable lossless compression
:type lossless: bool
:param Q: Quality factor
:type Q: int
:param bitdepth: Bit depth
:type bitdepth: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: labelregions(segments=bool)
Label regions in an image.
Example:
mask = in.labelregions()
:param segments: enable output: Number of discrete contiguous regions
:type segments: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: linear(a, b, uchar=bool)
Calculate (a * in + b).
Example:
out = in.linear(a, b, uchar=bool)
:param a: Multiply by this
:type a: list[float]
:param b: Add this
:type b: list[float]
:param uchar: Output should be uchar
:type uchar: bool
:rtype: Image
:raises Error:
.. method:: linecache(tile_height=int, access=Union[str, Access], threaded=bool, persistent=bool)
Cache an image as a set of lines.
Example:
out = in.linecache(tile_height=int, access=Union[str, Access], threaded=bool, persistent=bool)
:param tile_height: Tile height in pixels
:type tile_height: int
:param access: Expected access pattern
:type access: Union[str, Access]
:param threaded: Allow threaded access
:type threaded: bool
:param persistent: Keep cache between evaluations
:type persistent: bool
:rtype: Image
:raises Error:
.. staticmethod:: logmat(sigma, min_ampl, separable=bool, precision=Union[str, Precision])
Make a Laplacian of Gaussian image.
Example:
out = pyvips.Image.logmat(sigma, min_ampl, separable=bool, precision=Union[str, Precision])
:param sigma: Radius of Gaussian
:type sigma: float
:param min_ampl: Minimum amplitude of Gaussian
:type min_ampl: float
:param separable: Generate separable Gaussian
:type separable: bool
:param precision: Generate with this precision
:type precision: Union[str, Precision]
:rtype: Image
:raises Error:
.. staticmethod:: magickload(filename, density=str, page=int, n=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load file with ImageMagick7.
Example:
out = pyvips.Image.magickload(filename, density=str, page=int, n=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param filename: Filename to load from
:type filename: str
:param density: Canvas resolution for rendering vector formats like SVG
:type density: str
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: magickload_buffer(buffer, density=str, page=int, n=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load buffer with ImageMagick7.
Example:
out = pyvips.Image.magickload_buffer(buffer, density=str, page=int, n=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param buffer: Buffer to load from
:type buffer: str
:param density: Canvas resolution for rendering vector formats like SVG
:type density: str
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: magickload_source(source, density=str, page=int, n=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load source with ImageMagick7.
Example:
out = pyvips.Image.magickload_source(source, density=str, page=int, n=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param density: Canvas resolution for rendering vector formats like SVG
:type density: str
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: magicksave(filename, format=str, quality=int, optimize_gif_frames=bool, optimize_gif_transparency=bool, bitdepth=int, keep=int, background=list[float], page_height=int, profile=str)
Save file with ImageMagick.
Example:
in.magicksave(filename, format=str, quality=int, optimize_gif_frames=bool, optimize_gif_transparency=bool, bitdepth=int, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param format: Format to save in
:type format: str
:param quality: Quality to use
:type quality: int
:param optimize_gif_frames: Apply GIF frames optimization
:type optimize_gif_frames: bool
:param optimize_gif_transparency: Apply GIF transparency optimization
:type optimize_gif_transparency: bool
:param bitdepth: Number of bits per pixel
:type bitdepth: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: magicksave_buffer(format=str, quality=int, optimize_gif_frames=bool, optimize_gif_transparency=bool, bitdepth=int, keep=int, background=list[float], page_height=int, profile=str)
Save image to magick buffer.
Example:
buffer = in.magicksave_buffer(format=str, quality=int, optimize_gif_frames=bool, optimize_gif_transparency=bool, bitdepth=int, keep=int, background=list[float], page_height=int, profile=str)
:param format: Format to save in
:type format: str
:param quality: Quality to use
:type quality: int
:param optimize_gif_frames: Apply GIF frames optimization
:type optimize_gif_frames: bool
:param optimize_gif_transparency: Apply GIF transparency optimization
:type optimize_gif_transparency: bool
:param bitdepth: Number of bits per pixel
:type bitdepth: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: str
:raises Error:
.. method:: mapim(index, interpolate=GObject, background=list[float], premultiplied=bool, extend=Union[str, Extend])
Resample with a map image.
Example:
out = in.mapim(index, interpolate=GObject, background=list[float], premultiplied=bool, extend=Union[str, Extend])
:param index: Index pixels with this
:type index: Image
:param interpolate: Interpolate pixels with this
:type interpolate: GObject
:param background: Background value
:type background: list[float]
:param premultiplied: Images have premultiplied alpha
:type premultiplied: bool
:param extend: How to generate the extra pixels
:type extend: Union[str, Extend]
:rtype: Image
:raises Error:
.. method:: maplut(lut, band=int)
Map an image though a lut.
Example:
out = in.maplut(lut, band=int)
:param lut: Look-up table image
:type lut: Image
:param band: Apply one-band lut to this band of in
:type band: int
:rtype: Image
:raises Error:
.. staticmethod:: mask_butterworth(width, height, order, frequency_cutoff, amplitude_cutoff, uchar=bool, nodc=bool, reject=bool, optical=bool)
Make a butterworth filter.
Example:
out = pyvips.Image.mask_butterworth(width, height, order, frequency_cutoff, amplitude_cutoff, uchar=bool, nodc=bool, reject=bool, optical=bool)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param order: Filter order
:type order: float
:param frequency_cutoff: Frequency cutoff
:type frequency_cutoff: float
:param amplitude_cutoff: Amplitude cutoff
:type amplitude_cutoff: float
:param uchar: Output an unsigned char image
:type uchar: bool
:param nodc: Remove DC component
:type nodc: bool
:param reject: Invert the sense of the filter
:type reject: bool
:param optical: Rotate quadrants to optical space
:type optical: bool
:rtype: Image
:raises Error:
.. staticmethod:: mask_butterworth_band(width, height, order, frequency_cutoff_x, frequency_cutoff_y, radius, amplitude_cutoff, uchar=bool, nodc=bool, reject=bool, optical=bool)
Make a butterworth_band filter.
Example:
out = pyvips.Image.mask_butterworth_band(width, height, order, frequency_cutoff_x, frequency_cutoff_y, radius, amplitude_cutoff, uchar=bool, nodc=bool, reject=bool, optical=bool)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param order: Filter order
:type order: float
:param frequency_cutoff_x: Frequency cutoff x
:type frequency_cutoff_x: float
:param frequency_cutoff_y: Frequency cutoff y
:type frequency_cutoff_y: float
:param radius: Radius of circle
:type radius: float
:param amplitude_cutoff: Amplitude cutoff
:type amplitude_cutoff: float
:param uchar: Output an unsigned char image
:type uchar: bool
:param nodc: Remove DC component
:type nodc: bool
:param reject: Invert the sense of the filter
:type reject: bool
:param optical: Rotate quadrants to optical space
:type optical: bool
:rtype: Image
:raises Error:
.. staticmethod:: mask_butterworth_ring(width, height, order, frequency_cutoff, amplitude_cutoff, ringwidth, uchar=bool, nodc=bool, reject=bool, optical=bool)
Make a butterworth ring filter.
Example:
out = pyvips.Image.mask_butterworth_ring(width, height, order, frequency_cutoff, amplitude_cutoff, ringwidth, uchar=bool, nodc=bool, reject=bool, optical=bool)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param order: Filter order
:type order: float
:param frequency_cutoff: Frequency cutoff
:type frequency_cutoff: float
:param amplitude_cutoff: Amplitude cutoff
:type amplitude_cutoff: float
:param ringwidth: Ringwidth
:type ringwidth: float
:param uchar: Output an unsigned char image
:type uchar: bool
:param nodc: Remove DC component
:type nodc: bool
:param reject: Invert the sense of the filter
:type reject: bool
:param optical: Rotate quadrants to optical space
:type optical: bool
:rtype: Image
:raises Error:
.. staticmethod:: mask_fractal(width, height, fractal_dimension, uchar=bool, nodc=bool, reject=bool, optical=bool)
Make fractal filter.
Example:
out = pyvips.Image.mask_fractal(width, height, fractal_dimension, uchar=bool, nodc=bool, reject=bool, optical=bool)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param fractal_dimension: Fractal dimension
:type fractal_dimension: float
:param uchar: Output an unsigned char image
:type uchar: bool
:param nodc: Remove DC component
:type nodc: bool
:param reject: Invert the sense of the filter
:type reject: bool
:param optical: Rotate quadrants to optical space
:type optical: bool
:rtype: Image
:raises Error:
.. staticmethod:: mask_gaussian(width, height, frequency_cutoff, amplitude_cutoff, uchar=bool, nodc=bool, reject=bool, optical=bool)
Make a gaussian filter.
Example:
out = pyvips.Image.mask_gaussian(width, height, frequency_cutoff, amplitude_cutoff, uchar=bool, nodc=bool, reject=bool, optical=bool)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param frequency_cutoff: Frequency cutoff
:type frequency_cutoff: float
:param amplitude_cutoff: Amplitude cutoff
:type amplitude_cutoff: float
:param uchar: Output an unsigned char image
:type uchar: bool
:param nodc: Remove DC component
:type nodc: bool
:param reject: Invert the sense of the filter
:type reject: bool
:param optical: Rotate quadrants to optical space
:type optical: bool
:rtype: Image
:raises Error:
.. staticmethod:: mask_gaussian_band(width, height, frequency_cutoff_x, frequency_cutoff_y, radius, amplitude_cutoff, uchar=bool, nodc=bool, reject=bool, optical=bool)
Make a gaussian filter.
Example:
out = pyvips.Image.mask_gaussian_band(width, height, frequency_cutoff_x, frequency_cutoff_y, radius, amplitude_cutoff, uchar=bool, nodc=bool, reject=bool, optical=bool)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param frequency_cutoff_x: Frequency cutoff x
:type frequency_cutoff_x: float
:param frequency_cutoff_y: Frequency cutoff y
:type frequency_cutoff_y: float
:param radius: Radius of circle
:type radius: float
:param amplitude_cutoff: Amplitude cutoff
:type amplitude_cutoff: float
:param uchar: Output an unsigned char image
:type uchar: bool
:param nodc: Remove DC component
:type nodc: bool
:param reject: Invert the sense of the filter
:type reject: bool
:param optical: Rotate quadrants to optical space
:type optical: bool
:rtype: Image
:raises Error:
.. staticmethod:: mask_gaussian_ring(width, height, frequency_cutoff, amplitude_cutoff, ringwidth, uchar=bool, nodc=bool, reject=bool, optical=bool)
Make a gaussian ring filter.
Example:
out = pyvips.Image.mask_gaussian_ring(width, height, frequency_cutoff, amplitude_cutoff, ringwidth, uchar=bool, nodc=bool, reject=bool, optical=bool)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param frequency_cutoff: Frequency cutoff
:type frequency_cutoff: float
:param amplitude_cutoff: Amplitude cutoff
:type amplitude_cutoff: float
:param ringwidth: Ringwidth
:type ringwidth: float
:param uchar: Output an unsigned char image
:type uchar: bool
:param nodc: Remove DC component
:type nodc: bool
:param reject: Invert the sense of the filter
:type reject: bool
:param optical: Rotate quadrants to optical space
:type optical: bool
:rtype: Image
:raises Error:
.. staticmethod:: mask_ideal(width, height, frequency_cutoff, uchar=bool, nodc=bool, reject=bool, optical=bool)
Make an ideal filter.
Example:
out = pyvips.Image.mask_ideal(width, height, frequency_cutoff, uchar=bool, nodc=bool, reject=bool, optical=bool)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param frequency_cutoff: Frequency cutoff
:type frequency_cutoff: float
:param uchar: Output an unsigned char image
:type uchar: bool
:param nodc: Remove DC component
:type nodc: bool
:param reject: Invert the sense of the filter
:type reject: bool
:param optical: Rotate quadrants to optical space
:type optical: bool
:rtype: Image
:raises Error:
.. staticmethod:: mask_ideal_band(width, height, frequency_cutoff_x, frequency_cutoff_y, radius, uchar=bool, nodc=bool, reject=bool, optical=bool)
Make an ideal band filter.
Example:
out = pyvips.Image.mask_ideal_band(width, height, frequency_cutoff_x, frequency_cutoff_y, radius, uchar=bool, nodc=bool, reject=bool, optical=bool)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param frequency_cutoff_x: Frequency cutoff x
:type frequency_cutoff_x: float
:param frequency_cutoff_y: Frequency cutoff y
:type frequency_cutoff_y: float
:param radius: Radius of circle
:type radius: float
:param uchar: Output an unsigned char image
:type uchar: bool
:param nodc: Remove DC component
:type nodc: bool
:param reject: Invert the sense of the filter
:type reject: bool
:param optical: Rotate quadrants to optical space
:type optical: bool
:rtype: Image
:raises Error:
.. staticmethod:: mask_ideal_ring(width, height, frequency_cutoff, ringwidth, uchar=bool, nodc=bool, reject=bool, optical=bool)
Make an ideal ring filter.
Example:
out = pyvips.Image.mask_ideal_ring(width, height, frequency_cutoff, ringwidth, uchar=bool, nodc=bool, reject=bool, optical=bool)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param frequency_cutoff: Frequency cutoff
:type frequency_cutoff: float
:param ringwidth: Ringwidth
:type ringwidth: float
:param uchar: Output an unsigned char image
:type uchar: bool
:param nodc: Remove DC component
:type nodc: bool
:param reject: Invert the sense of the filter
:type reject: bool
:param optical: Rotate quadrants to optical space
:type optical: bool
:rtype: Image
:raises Error:
.. method:: match(sec, xr1, yr1, xs1, ys1, xr2, yr2, xs2, ys2, hwindow=int, harea=int, search=bool, interpolate=GObject)
First-order match of two images.
Example:
out = ref.match(sec, xr1, yr1, xs1, ys1, xr2, yr2, xs2, ys2, hwindow=int, harea=int, search=bool, interpolate=GObject)
:param sec: Secondary image
:type sec: Image
:param xr1: Position of first reference tie-point
:type xr1: int
:param yr1: Position of first reference tie-point
:type yr1: int
:param xs1: Position of first secondary tie-point
:type xs1: int
:param ys1: Position of first secondary tie-point
:type ys1: int
:param xr2: Position of second reference tie-point
:type xr2: int
:param yr2: Position of second reference tie-point
:type yr2: int
:param xs2: Position of second secondary tie-point
:type xs2: int
:param ys2: Position of second secondary tie-point
:type ys2: int
:param hwindow: Half window size
:type hwindow: int
:param harea: Half area size
:type harea: int
:param search: Search to improve tie-points
:type search: bool
:param interpolate: Interpolate pixels with this
:type interpolate: GObject
:rtype: Image
:raises Error:
.. method:: math(math)
Apply a math operation to an image.
Example:
out = in.math(math)
:param math: Math to perform
:type math: Union[str, OperationMath]
:rtype: Image
:raises Error:
.. method:: math2(right, math2)
Binary math operations.
Example:
out = left.math2(right, math2)
:param right: Right-hand image argument
:type right: Image
:param math2: Math to perform
:type math2: Union[str, OperationMath2]
:rtype: Image
:raises Error:
.. method:: math2_const(math2, c)
Binary math operations with a constant.
Example:
out = in.math2_const(math2, c)
:param math2: Math to perform
:type math2: Union[str, OperationMath2]
:param c: Array of constants
:type c: list[float]
:rtype: Image
:raises Error:
.. staticmethod:: matload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load mat from file.
Example:
out = pyvips.Image.matload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: matrixinvert()
Invert a matrix.
Example:
out = in.matrixinvert()
:rtype: Image
:raises Error:
.. staticmethod:: matrixload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load matrix.
Example:
out = pyvips.Image.matrixload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: matrixload_source(source, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load matrix.
Example:
out = pyvips.Image.matrixload_source(source, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: matrixmultiply(right)
Multiply two matrices.
Example:
out = left.matrixmultiply(right)
:param right: Second matrix to multiply
:type right: Image
:rtype: Image
:raises Error:
.. method:: matrixprint(keep=int, background=list[float], page_height=int, profile=str)
Print matrix.
Example:
in.matrixprint(keep=int, background=list[float], page_height=int, profile=str)
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: matrixsave(filename, keep=int, background=list[float], page_height=int, profile=str)
Save image to matrix.
Example:
in.matrixsave(filename, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: matrixsave_target(target, keep=int, background=list[float], page_height=int, profile=str)
Save image to matrix.
Example:
in.matrixsave_target(target, keep=int, background=list[float], page_height=int, profile=str)
:param target: Target to save to
:type target: Target
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: max(size=int, x=bool, y=bool, out_array=bool, x_array=bool, y_array=bool)
Find image maximum.
Example:
out = in.max(size=int)
:param size: Number of maximum values to find
:type size: int
:param x: enable output: Horizontal position of maximum
:type x: bool
:param y: enable output: Vertical position of maximum
:type y: bool
:param out_array: enable output: Array of output values
:type out_array: bool
:param x_array: enable output: Array of horizontal positions
:type x_array: bool
:param y_array: enable output: Array of vertical positions
:type y_array: bool
:rtype: float or list[float, Dict[str, mixed]]
:raises Error:
.. method:: maxpair(right)
Maximum of a pair of images.
Example:
out = left.maxpair(right)
:param right: Right-hand image argument
:type right: Image
:rtype: Image
:raises Error:
.. method:: measure(h, v, left=int, top=int, width=int, height=int)
Measure a set of patches on a color chart.
Example:
out = in.measure(h, v, left=int, top=int, width=int, height=int)
:param h: Number of patches across chart
:type h: int
:param v: Number of patches down chart
:type v: int
:param left: Left edge of extract area
:type left: int
:param top: Top edge of extract area
:type top: int
:param width: Width of extract area
:type width: int
:param height: Height of extract area
:type height: int
:rtype: Image
:raises Error:
.. method:: merge(sec, direction, dx, dy, mblend=int)
Merge two images.
Example:
out = ref.merge(sec, direction, dx, dy, mblend=int)
:param sec: Secondary image
:type sec: Image
:param direction: Horizontal or vertical merge
:type direction: Union[str, Direction]
:param dx: Horizontal displacement from sec to ref
:type dx: int
:param dy: Vertical displacement from sec to ref
:type dy: int
:param mblend: Maximum blend size
:type mblend: int
:rtype: Image
:raises Error:
.. method:: min(size=int, x=bool, y=bool, out_array=bool, x_array=bool, y_array=bool)
Find image minimum.
Example:
out = in.min(size=int)
:param size: Number of minimum values to find
:type size: int
:param x: enable output: Horizontal position of minimum
:type x: bool
:param y: enable output: Vertical position of minimum
:type y: bool
:param out_array: enable output: Array of output values
:type out_array: bool
:param x_array: enable output: Array of horizontal positions
:type x_array: bool
:param y_array: enable output: Array of vertical positions
:type y_array: bool
:rtype: float or list[float, Dict[str, mixed]]
:raises Error:
.. method:: minpair(right)
Minimum of a pair of images.
Example:
out = left.minpair(right)
:param right: Right-hand image argument
:type right: Image
:rtype: Image
:raises Error:
.. method:: morph(mask, morph)
Morphology operation.
Example:
out = in.morph(mask, morph)
:param mask: Input matrix image
:type mask: Image
:param morph: Morphological operation to perform
:type morph: Union[str, OperationMorphology]
:rtype: Image
:raises Error:
.. method:: mosaic(sec, direction, xref, yref, xsec, ysec, hwindow=int, harea=int, mblend=int, bandno=int, dx0=bool, dy0=bool, scale1=bool, angle1=bool, dy1=bool, dx1=bool)
Mosaic two images.
Example:
out = ref.mosaic(sec, direction, xref, yref, xsec, ysec, hwindow=int, harea=int, mblend=int, bandno=int)
:param sec: Secondary image
:type sec: Image
:param direction: Horizontal or vertical mosaic
:type direction: Union[str, Direction]
:param xref: Position of reference tie-point
:type xref: int
:param yref: Position of reference tie-point
:type yref: int
:param xsec: Position of secondary tie-point
:type xsec: int
:param ysec: Position of secondary tie-point
:type ysec: int
:param hwindow: Half window size
:type hwindow: int
:param harea: Half area size
:type harea: int
:param mblend: Maximum blend size
:type mblend: int
:param bandno: Band to search for features on
:type bandno: int
:param dx0: enable output: Detected integer offset
:type dx0: bool
:param dy0: enable output: Detected integer offset
:type dy0: bool
:param scale1: enable output: Detected scale
:type scale1: bool
:param angle1: enable output: Detected rotation
:type angle1: bool
:param dy1: enable output: Detected first-order displacement
:type dy1: bool
:param dx1: enable output: Detected first-order displacement
:type dx1: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: mosaic1(sec, direction, xr1, yr1, xs1, ys1, xr2, yr2, xs2, ys2, hwindow=int, harea=int, search=bool, interpolate=GObject, mblend=int)
First-order mosaic of two images.
Example:
out = ref.mosaic1(sec, direction, xr1, yr1, xs1, ys1, xr2, yr2, xs2, ys2, hwindow=int, harea=int, search=bool, interpolate=GObject, mblend=int)
:param sec: Secondary image
:type sec: Image
:param direction: Horizontal or vertical mosaic
:type direction: Union[str, Direction]
:param xr1: Position of first reference tie-point
:type xr1: int
:param yr1: Position of first reference tie-point
:type yr1: int
:param xs1: Position of first secondary tie-point
:type xs1: int
:param ys1: Position of first secondary tie-point
:type ys1: int
:param xr2: Position of second reference tie-point
:type xr2: int
:param yr2: Position of second reference tie-point
:type yr2: int
:param xs2: Position of second secondary tie-point
:type xs2: int
:param ys2: Position of second secondary tie-point
:type ys2: int
:param hwindow: Half window size
:type hwindow: int
:param harea: Half area size
:type harea: int
:param search: Search to improve tie-points
:type search: bool
:param interpolate: Interpolate pixels with this
:type interpolate: GObject
:param mblend: Maximum blend size
:type mblend: int
:rtype: Image
:raises Error:
.. method:: msb(band=int)
Pick most-significant byte from an image.
Example:
out = in.msb(band=int)
:param band: Band to msb
:type band: int
:rtype: Image
:raises Error:
.. method:: multiply(right)
Multiply two images.
Example:
out = left.multiply(right)
:param right: Right-hand image argument
:type right: Image
:rtype: Image
:raises Error:
.. staticmethod:: niftiload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load NIfTI volume.
Example:
out = pyvips.Image.niftiload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: niftiload_source(source, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load NIfTI volumes.
Example:
out = pyvips.Image.niftiload_source(source, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: niftisave(filename, keep=int, background=list[float], page_height=int, profile=str)
Save image to nifti file.
Example:
in.niftisave(filename, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. staticmethod:: openexrload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load an OpenEXR image.
Example:
out = pyvips.Image.openexrload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: openslideload(filename, level=int, autocrop=bool, associated=str, attach_associated=bool, rgb=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load file with OpenSlide.
Example:
out = pyvips.Image.openslideload(filename, level=int, autocrop=bool, associated=str, attach_associated=bool, rgb=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param level: Load this level from the file
:type level: int
:param autocrop: Crop to image bounds
:type autocrop: bool
:param associated: Load this associated image
:type associated: str
:param attach_associated: Attach all associated images
:type attach_associated: bool
:param rgb: Output RGB (not RGBA)
:type rgb: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: openslideload_source(source, level=int, autocrop=bool, associated=str, attach_associated=bool, rgb=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load source with OpenSlide.
Example:
out = pyvips.Image.openslideload_source(source, level=int, autocrop=bool, associated=str, attach_associated=bool, rgb=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param level: Load this level from the file
:type level: int
:param autocrop: Crop to image bounds
:type autocrop: bool
:param associated: Load this associated image
:type associated: str
:param attach_associated: Attach all associated images
:type attach_associated: bool
:param rgb: Output RGB (not RGBA)
:type rgb: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: pdfload(filename, page=int, n=int, dpi=float, scale=float, background=list[float], password=str, page_box=Union[str, ForeignPdfPageBox], memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load PDF from file (poppler).
Example:
out = pyvips.Image.pdfload(filename, page=int, n=int, dpi=float, scale=float, background=list[float], password=str, page_box=Union[str, ForeignPdfPageBox], memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param dpi: DPI to render at
:type dpi: float
:param scale: Factor to scale by
:type scale: float
:param background: Background colour
:type background: list[float]
:param password: Password to decrypt with
:type password: str
:param page_box: The region of the page to render
:type page_box: Union[str, ForeignPdfPageBox]
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: pdfload_buffer(buffer, page=int, n=int, dpi=float, scale=float, background=list[float], password=str, page_box=Union[str, ForeignPdfPageBox], memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load PDF from buffer (poppler).
Example:
out = pyvips.Image.pdfload_buffer(buffer, page=int, n=int, dpi=float, scale=float, background=list[float], password=str, page_box=Union[str, ForeignPdfPageBox], memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param buffer: Buffer to load from
:type buffer: str
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param dpi: DPI to render at
:type dpi: float
:param scale: Factor to scale by
:type scale: float
:param background: Background colour
:type background: list[float]
:param password: Password to decrypt with
:type password: str
:param page_box: The region of the page to render
:type page_box: Union[str, ForeignPdfPageBox]
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: pdfload_source(source, page=int, n=int, dpi=float, scale=float, background=list[float], password=str, page_box=Union[str, ForeignPdfPageBox], memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load PDF from source (poppler).
Example:
out = pyvips.Image.pdfload_source(source, page=int, n=int, dpi=float, scale=float, background=list[float], password=str, page_box=Union[str, ForeignPdfPageBox], memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param dpi: DPI to render at
:type dpi: float
:param scale: Factor to scale by
:type scale: float
:param background: Background colour
:type background: list[float]
:param password: Password to decrypt with
:type password: str
:param page_box: The region of the page to render
:type page_box: Union[str, ForeignPdfPageBox]
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: percent(percent)
Find threshold for percent of pixels.
Example:
threshold = in.percent(percent)
:param percent: Percent of pixels
:type percent: float
:rtype: int
:raises Error:
.. staticmethod:: perlin(width, height, cell_size=int, uchar=bool, seed=int)
Make a perlin noise image.
Example:
out = pyvips.Image.perlin(width, height, cell_size=int, uchar=bool, seed=int)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param cell_size: Size of Perlin cells
:type cell_size: int
:param uchar: Output an unsigned char image
:type uchar: bool
:param seed: Random number seed
:type seed: int
:rtype: Image
:raises Error:
.. method:: phasecor(in2)
Calculate phase correlation.
Example:
out = in.phasecor(in2)
:param in2: Second input image
:type in2: Image
:rtype: Image
:raises Error:
.. staticmethod:: pngload(filename, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load png from file.
Example:
out = pyvips.Image.pngload(filename, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param unlimited: Remove all denial of service limits
:type unlimited: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: pngload_buffer(buffer, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load png from buffer.
Example:
out = pyvips.Image.pngload_buffer(buffer, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param buffer: Buffer to load from
:type buffer: str
:param unlimited: Remove all denial of service limits
:type unlimited: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: pngload_source(source, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load png from source.
Example:
out = pyvips.Image.pngload_source(source, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param unlimited: Remove all denial of service limits
:type unlimited: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: pngsave(filename, compression=int, interlace=bool, filter=int, palette=bool, Q=int, dither=float, bitdepth=int, effort=int, keep=int, background=list[float], page_height=int, profile=str)
Save image to file as png.
Example:
in.pngsave(filename, compression=int, interlace=bool, filter=int, palette=bool, Q=int, dither=float, bitdepth=int, effort=int, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param compression: Compression factor
:type compression: int
:param interlace: Interlace image
:type interlace: bool
:param filter: libpng row filter flag(s)
:type filter: int
:param palette: Quantise to 8bpp palette
:type palette: bool
:param Q: Quantisation quality
:type Q: int
:param dither: Amount of dithering
:type dither: float
:param bitdepth: Write as a 1, 2, 4, 8 or 16 bit image
:type bitdepth: int
:param effort: Quantisation CPU effort
:type effort: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: pngsave_buffer(compression=int, interlace=bool, filter=int, palette=bool, Q=int, dither=float, bitdepth=int, effort=int, keep=int, background=list[float], page_height=int, profile=str)
Save image to buffer as png.
Example:
buffer = in.pngsave_buffer(compression=int, interlace=bool, filter=int, palette=bool, Q=int, dither=float, bitdepth=int, effort=int, keep=int, background=list[float], page_height=int, profile=str)
:param compression: Compression factor
:type compression: int
:param interlace: Interlace image
:type interlace: bool
:param filter: libpng row filter flag(s)
:type filter: int
:param palette: Quantise to 8bpp palette
:type palette: bool
:param Q: Quantisation quality
:type Q: int
:param dither: Amount of dithering
:type dither: float
:param bitdepth: Write as a 1, 2, 4, 8 or 16 bit image
:type bitdepth: int
:param effort: Quantisation CPU effort
:type effort: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: str
:raises Error:
.. method:: pngsave_target(target, compression=int, interlace=bool, filter=int, palette=bool, Q=int, dither=float, bitdepth=int, effort=int, keep=int, background=list[float], page_height=int, profile=str)
Save image to target as PNG.
Example:
in.pngsave_target(target, compression=int, interlace=bool, filter=int, palette=bool, Q=int, dither=float, bitdepth=int, effort=int, keep=int, background=list[float], page_height=int, profile=str)
:param target: Target to save to
:type target: Target
:param compression: Compression factor
:type compression: int
:param interlace: Interlace image
:type interlace: bool
:param filter: libpng row filter flag(s)
:type filter: int
:param palette: Quantise to 8bpp palette
:type palette: bool
:param Q: Quantisation quality
:type Q: int
:param dither: Amount of dithering
:type dither: float
:param bitdepth: Write as a 1, 2, 4, 8 or 16 bit image
:type bitdepth: int
:param effort: Quantisation CPU effort
:type effort: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. staticmethod:: ppmload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load ppm from file.
Example:
out = pyvips.Image.ppmload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: ppmload_buffer(buffer, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load ppm from buffer.
Example:
out = pyvips.Image.ppmload_buffer(buffer, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param buffer: Buffer to load from
:type buffer: str
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: ppmload_source(source, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load ppm from source.
Example:
out = pyvips.Image.ppmload_source(source, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: ppmsave(filename, format=Union[str, ForeignPpmFormat], ascii=bool, bitdepth=int, keep=int, background=list[float], page_height=int, profile=str)
Save image to ppm file.
Example:
in.ppmsave(filename, format=Union[str, ForeignPpmFormat], ascii=bool, bitdepth=int, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param format: Format to save in
:type format: Union[str, ForeignPpmFormat]
:param ascii: Save as ascii
:type ascii: bool
:param bitdepth: Set to 1 to write as a 1 bit image
:type bitdepth: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: ppmsave_target(target, format=Union[str, ForeignPpmFormat], ascii=bool, bitdepth=int, keep=int, background=list[float], page_height=int, profile=str)
Save to ppm.
Example:
in.ppmsave_target(target, format=Union[str, ForeignPpmFormat], ascii=bool, bitdepth=int, keep=int, background=list[float], page_height=int, profile=str)
:param target: Target to save to
:type target: Target
:param format: Format to save in
:type format: Union[str, ForeignPpmFormat]
:param ascii: Save as ascii
:type ascii: bool
:param bitdepth: Set to 1 to write as a 1 bit image
:type bitdepth: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: premultiply(max_alpha=float)
Premultiply image alpha.
Example:
out = in.premultiply(max_alpha=float)
:param max_alpha: Maximum value of alpha channel
:type max_alpha: float
:rtype: Image
:raises Error:
.. method:: prewitt()
Prewitt edge detector.
Example:
out = in.prewitt()
:rtype: Image
:raises Error:
.. method:: profile()
Find image profiles.
Example:
columns, rows = in.profile()
:rtype: list[Image, Image]
:raises Error:
.. staticmethod:: profile_load(name)
Load named ICC profile.
Example:
profile = pyvips.Image.profile_load(name)
:param name: Profile name
:type name: str
:rtype: str
:raises Error:
.. method:: project()
Find image projections.
Example:
columns, rows = in.project()
:rtype: list[Image, Image]
:raises Error:
.. method:: quadratic(coeff, interpolate=GObject)
Resample an image with a quadratic transform.
Example:
out = in.quadratic(coeff, interpolate=GObject)
:param coeff: Coefficient matrix
:type coeff: Image
:param interpolate: Interpolate values with this
:type interpolate: GObject
:rtype: Image
:raises Error:
.. method:: rad2float()
Unpack Radiance coding to float RGB.
Example:
out = in.rad2float()
:rtype: Image
:raises Error:
.. staticmethod:: radload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load a Radiance image from a file.
Example:
out = pyvips.Image.radload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: radload_buffer(buffer, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load rad from buffer.
Example:
out = pyvips.Image.radload_buffer(buffer, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param buffer: Buffer to load from
:type buffer: str
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: radload_source(source, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load rad from source.
Example:
out = pyvips.Image.radload_source(source, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: radsave(filename, keep=int, background=list[float], page_height=int, profile=str)
Save image to Radiance file.
Example:
in.radsave(filename, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: radsave_buffer(keep=int, background=list[float], page_height=int, profile=str)
Save image to Radiance buffer.
Example:
buffer = in.radsave_buffer(keep=int, background=list[float], page_height=int, profile=str)
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: str
:raises Error:
.. method:: radsave_target(target, keep=int, background=list[float], page_height=int, profile=str)
Save image to Radiance target.
Example:
in.radsave_target(target, keep=int, background=list[float], page_height=int, profile=str)
:param target: Target to save to
:type target: Target
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: rank(width, height, index)
Rank filter.
Example:
out = in.rank(width, height, index)
:param width: Window width in pixels
:type width: int
:param height: Window height in pixels
:type height: int
:param index: Select pixel at index
:type index: int
:rtype: Image
:raises Error:
.. staticmethod:: rawload(filename, width, height, bands, offset=long, format=Union[str, BandFormat], interpretation=Union[str, Interpretation], memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load raw data from a file.
Example:
out = pyvips.Image.rawload(filename, width, height, bands, offset=long, format=Union[str, BandFormat], interpretation=Union[str, Interpretation], memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param bands: Number of bands in image
:type bands: int
:param offset: Offset in bytes from start of file
:type offset: long
:param format: Pixel format in image
:type format: Union[str, BandFormat]
:param interpretation: Pixel interpretation
:type interpretation: Union[str, Interpretation]
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: rawsave(filename, keep=int, background=list[float], page_height=int, profile=str)
Save image to raw file.
Example:
in.rawsave(filename, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: rawsave_buffer(keep=int, background=list[float], page_height=int, profile=str)
Write raw image to buffer.
Example:
buffer = in.rawsave_buffer(keep=int, background=list[float], page_height=int, profile=str)
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: str
:raises Error:
.. method:: rawsave_target(target, keep=int, background=list[float], page_height=int, profile=str)
Write raw image to target.
Example:
in.rawsave_target(target, keep=int, background=list[float], page_height=int, profile=str)
:param target: Target to save to
:type target: Target
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: recomb(m)
Linear recombination with matrix.
Example:
out = in.recomb(m)
:param m: Matrix of coefficients
:type m: Image
:rtype: Image
:raises Error:
.. method:: reduce(hshrink, vshrink, kernel=Union[str, Kernel], gap=float)
Reduce an image.
Example:
out = in.reduce(hshrink, vshrink, kernel=Union[str, Kernel], gap=float)
:param hshrink: Horizontal shrink factor
:type hshrink: float
:param vshrink: Vertical shrink factor
:type vshrink: float
:param kernel: Resampling kernel
:type kernel: Union[str, Kernel]
:param gap: Reducing gap
:type gap: float
:rtype: Image
:raises Error:
.. method:: reduceh(hshrink, kernel=Union[str, Kernel], gap=float)
Shrink an image horizontally.
Example:
out = in.reduceh(hshrink, kernel=Union[str, Kernel], gap=float)
:param hshrink: Horizontal shrink factor
:type hshrink: float
:param kernel: Resampling kernel
:type kernel: Union[str, Kernel]
:param gap: Reducing gap
:type gap: float
:rtype: Image
:raises Error:
.. method:: reducev(vshrink, kernel=Union[str, Kernel], gap=float)
Shrink an image vertically.
Example:
out = in.reducev(vshrink, kernel=Union[str, Kernel], gap=float)
:param vshrink: Vertical shrink factor
:type vshrink: float
:param kernel: Resampling kernel
:type kernel: Union[str, Kernel]
:param gap: Reducing gap
:type gap: float
:rtype: Image
:raises Error:
.. method:: relational(right, relational)
Relational operation on two images.
Example:
out = left.relational(right, relational)
:param right: Right-hand image argument
:type right: Image
:param relational: Relational to perform
:type relational: Union[str, OperationRelational]
:rtype: Image
:raises Error:
.. method:: relational_const(relational, c)
Relational operations against a constant.
Example:
out = in.relational_const(relational, c)
:param relational: Relational to perform
:type relational: Union[str, OperationRelational]
:param c: Array of constants
:type c: list[float]
:rtype: Image
:raises Error:
.. method:: remainder(right)
Remainder after integer division of two images.
Example:
out = left.remainder(right)
:param right: Right-hand image argument
:type right: Image
:rtype: Image
:raises Error:
.. method:: remainder_const(c)
Remainder after integer division of an image and a constant.
Example:
out = in.remainder_const(c)
:param c: Array of constants
:type c: list[float]
:rtype: Image
:raises Error:
.. method:: remosaic(old_str, new_str)
Rebuild an mosaiced image.
Example:
out = in.remosaic(old_str, new_str)
:param old_str: Search for this string
:type old_str: str
:param new_str: And swap for this string
:type new_str: str
:rtype: Image
:raises Error:
.. method:: replicate(across, down)
Replicate an image.
Example:
out = in.replicate(across, down)
:param across: Repeat this many times horizontally
:type across: int
:param down: Repeat this many times vertically
:type down: int
:rtype: Image
:raises Error:
.. method:: resize(scale, kernel=Union[str, Kernel], gap=float, vscale=float)
Resize an image.
Example:
out = in.resize(scale, kernel=Union[str, Kernel], gap=float, vscale=float)
:param scale: Scale image by this factor
:type scale: float
:param kernel: Resampling kernel
:type kernel: Union[str, Kernel]
:param gap: Reducing gap
:type gap: float
:param vscale: Vertical scale image by this factor
:type vscale: float
:rtype: Image
:raises Error:
.. method:: rot(angle)
Rotate an image.
Example:
out = in.rot(angle)
:param angle: Angle to rotate image
:type angle: Union[str, Angle]
:rtype: Image
:raises Error:
.. method:: rot45(angle=Union[str, Angle45])
Rotate an image.
Example:
out = in.rot45(angle=Union[str, Angle45])
:param angle: Angle to rotate image
:type angle: Union[str, Angle45]
:rtype: Image
:raises Error:
.. method:: rotate(angle, interpolate=GObject, background=list[float], odx=float, ody=float, idx=float, idy=float)
Rotate an image by a number of degrees.
Example:
out = in.rotate(angle, interpolate=GObject, background=list[float], odx=float, ody=float, idx=float, idy=float)
:param angle: Rotate clockwise by this many degrees
:type angle: float
:param interpolate: Interpolate pixels with this
:type interpolate: GObject
:param background: Background value
:type background: list[float]
:param odx: Horizontal output displacement
:type odx: float
:param ody: Vertical output displacement
:type ody: float
:param idx: Horizontal input displacement
:type idx: float
:param idy: Vertical input displacement
:type idy: float
:rtype: Image
:raises Error:
.. method:: round(round)
Perform a round function on an image.
Example:
out = in.round(round)
:param round: Rounding operation to perform
:type round: Union[str, OperationRound]
:rtype: Image
:raises Error:
.. method:: sRGB2HSV()
Transform sRGB to HSV.
Example:
out = in.sRGB2HSV()
:rtype: Image
:raises Error:
.. method:: sRGB2scRGB()
Convert an sRGB image to scRGB.
Example:
out = in.sRGB2scRGB()
:rtype: Image
:raises Error:
.. method:: scRGB2BW(depth=int)
Convert scRGB to BW.
Example:
out = in.scRGB2BW(depth=int)
:param depth: Output device space depth in bits
:type depth: int
:rtype: Image
:raises Error:
.. method:: scRGB2XYZ()
Transform scRGB to XYZ.
Example:
out = in.scRGB2XYZ()
:rtype: Image
:raises Error:
.. method:: scRGB2sRGB(depth=int)
Convert scRGB to sRGB.
Example:
out = in.scRGB2sRGB(depth=int)
:param depth: Output device space depth in bits
:type depth: int
:rtype: Image
:raises Error:
.. method:: scharr()
Scharr edge detector.
Example:
out = in.scharr()
:rtype: Image
:raises Error:
.. staticmethod:: sdf(width, height, shape, r=float, a=list[float], b=list[float], corners=list[float])
Create an SDF image.
Example:
out = pyvips.Image.sdf(width, height, shape, r=float, a=list[float], b=list[float], corners=list[float])
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param shape: SDF shape to create
:type shape: Union[str, SdfShape]
:param r: Radius
:type r: float
:param a: Point a
:type a: list[float]
:param b: Point b
:type b: list[float]
:param corners: Corner radii
:type corners: list[float]
:rtype: Image
:raises Error:
.. method:: sequential(tile_height=int)
Check sequential access.
Example:
out = in.sequential(tile_height=int)
:param tile_height: Tile height in pixels
:type tile_height: int
:rtype: Image
:raises Error:
.. method:: sharpen(sigma=float, x1=float, y2=float, y3=float, m1=float, m2=float)
Unsharp masking for print.
Example:
out = in.sharpen(sigma=float, x1=float, y2=float, y3=float, m1=float, m2=float)
:param sigma: Sigma of Gaussian
:type sigma: float
:param x1: Flat/jaggy threshold
:type x1: float
:param y2: Maximum brightening
:type y2: float
:param y3: Maximum darkening
:type y3: float
:param m1: Slope for flat areas
:type m1: float
:param m2: Slope for jaggy areas
:type m2: float
:rtype: Image
:raises Error:
.. method:: shrink(hshrink, vshrink, ceil=bool)
Shrink an image.
Example:
out = in.shrink(hshrink, vshrink, ceil=bool)
:param hshrink: Horizontal shrink factor
:type hshrink: float
:param vshrink: Vertical shrink factor
:type vshrink: float
:param ceil: Round-up output dimensions
:type ceil: bool
:rtype: Image
:raises Error:
.. method:: shrinkh(hshrink, ceil=bool)
Shrink an image horizontally.
Example:
out = in.shrinkh(hshrink, ceil=bool)
:param hshrink: Horizontal shrink factor
:type hshrink: int
:param ceil: Round-up output dimensions
:type ceil: bool
:rtype: Image
:raises Error:
.. method:: shrinkv(vshrink, ceil=bool)
Shrink an image vertically.
Example:
out = in.shrinkv(vshrink, ceil=bool)
:param vshrink: Vertical shrink factor
:type vshrink: int
:param ceil: Round-up output dimensions
:type ceil: bool
:rtype: Image
:raises Error:
.. method:: sign()
Unit vector of pixel.
Example:
out = in.sign()
:rtype: Image
:raises Error:
.. method:: similarity(scale=float, angle=float, interpolate=GObject, background=list[float], odx=float, ody=float, idx=float, idy=float)
Similarity transform of an image.
Example:
out = in.similarity(scale=float, angle=float, interpolate=GObject, background=list[float], odx=float, ody=float, idx=float, idy=float)
:param scale: Scale by this factor
:type scale: float
:param angle: Rotate clockwise by this many degrees
:type angle: float
:param interpolate: Interpolate pixels with this
:type interpolate: GObject
:param background: Background value
:type background: list[float]
:param odx: Horizontal output displacement
:type odx: float
:param ody: Vertical output displacement
:type ody: float
:param idx: Horizontal input displacement
:type idx: float
:param idy: Vertical input displacement
:type idy: float
:rtype: Image
:raises Error:
.. staticmethod:: sines(width, height, uchar=bool, hfreq=float, vfreq=float)
Make a 2D sine wave.
Example:
out = pyvips.Image.sines(width, height, uchar=bool, hfreq=float, vfreq=float)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param uchar: Output an unsigned char image
:type uchar: bool
:param hfreq: Horizontal spatial frequency
:type hfreq: float
:param vfreq: Vertical spatial frequency
:type vfreq: float
:rtype: Image
:raises Error:
.. method:: smartcrop(width, height, interesting=Union[str, Interesting], premultiplied=bool, attention_x=bool, attention_y=bool)
Extract an area from an image.
Example:
out = input.smartcrop(width, height, interesting=Union[str, Interesting], premultiplied=bool)
:param width: Width of extract area
:type width: int
:param height: Height of extract area
:type height: int
:param interesting: How to measure interestingness
:type interesting: Union[str, Interesting]
:param premultiplied: Input image already has premultiplied alpha
:type premultiplied: bool
:param attention_x: enable output: Horizontal position of attention centre
:type attention_x: bool
:param attention_y: enable output: Vertical position of attention centre
:type attention_y: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: sobel()
Sobel edge detector.
Example:
out = in.sobel()
:rtype: Image
:raises Error:
.. method:: spcor(ref)
Spatial correlation.
Example:
out = in.spcor(ref)
:param ref: Input reference image
:type ref: Image
:rtype: Image
:raises Error:
.. method:: spectrum()
Make displayable power spectrum.
Example:
out = in.spectrum()
:rtype: Image
:raises Error:
.. method:: stats()
Find many image stats.
Example:
out = in.stats()
:rtype: Image
:raises Error:
.. method:: stdif(width, height, s0=float, b=float, m0=float, a=float)
Statistical difference.
Example:
out = in.stdif(width, height, s0=float, b=float, m0=float, a=float)
:param width: Window width in pixels
:type width: int
:param height: Window height in pixels
:type height: int
:param s0: New deviation
:type s0: float
:param b: Weight of new deviation
:type b: float
:param m0: New mean
:type m0: float
:param a: Weight of new mean
:type a: float
:rtype: Image
:raises Error:
.. method:: subsample(xfac, yfac, point=bool)
Subsample an image.
Example:
out = input.subsample(xfac, yfac, point=bool)
:param xfac: Horizontal subsample factor
:type xfac: int
:param yfac: Vertical subsample factor
:type yfac: int
:param point: Point sample
:type point: bool
:rtype: Image
:raises Error:
.. method:: subtract(right)
Subtract two images.
Example:
out = left.subtract(right)
:param right: Right-hand image argument
:type right: Image
:rtype: Image
:raises Error:
.. staticmethod:: sum(in)
Sum an array of images.
Example:
out = pyvips.Image.sum(in)
:param in: Array of input images
:type in: list[Image]
:rtype: Image
:raises Error:
.. staticmethod:: svgload(filename, dpi=float, scale=float, unlimited=bool, stylesheet=str, high_bitdepth=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load SVG with rsvg.
Example:
out = pyvips.Image.svgload(filename, dpi=float, scale=float, unlimited=bool, stylesheet=str, high_bitdepth=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param dpi: Render at this DPI
:type dpi: float
:param scale: Scale output by this factor
:type scale: float
:param unlimited: Allow SVG of any size
:type unlimited: bool
:param stylesheet: Custom CSS
:type stylesheet: str
:param high_bitdepth: Enable scRGB 128-bit output (32-bit per channel)
:type high_bitdepth: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: svgload_buffer(buffer, dpi=float, scale=float, unlimited=bool, stylesheet=str, high_bitdepth=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load SVG with rsvg.
Example:
out = pyvips.Image.svgload_buffer(buffer, dpi=float, scale=float, unlimited=bool, stylesheet=str, high_bitdepth=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param buffer: Buffer to load from
:type buffer: str
:param dpi: Render at this DPI
:type dpi: float
:param scale: Scale output by this factor
:type scale: float
:param unlimited: Allow SVG of any size
:type unlimited: bool
:param stylesheet: Custom CSS
:type stylesheet: str
:param high_bitdepth: Enable scRGB 128-bit output (32-bit per channel)
:type high_bitdepth: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: svgload_source(source, dpi=float, scale=float, unlimited=bool, stylesheet=str, high_bitdepth=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load svg from source.
Example:
out = pyvips.Image.svgload_source(source, dpi=float, scale=float, unlimited=bool, stylesheet=str, high_bitdepth=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param dpi: Render at this DPI
:type dpi: float
:param scale: Scale output by this factor
:type scale: float
:param unlimited: Allow SVG of any size
:type unlimited: bool
:param stylesheet: Custom CSS
:type stylesheet: str
:param high_bitdepth: Enable scRGB 128-bit output (32-bit per channel)
:type high_bitdepth: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: switch(tests)
Find the index of the first non-zero pixel in tests.
Example:
out = pyvips.Image.switch(tests)
:param tests: Table of images to test
:type tests: list[Image]
:rtype: Image
:raises Error:
.. staticmethod:: system(cmd_format, in=list[Image], in_format=str, out_format=str, cache=bool, out=bool, log=bool)
Run an external command.
Example:
pyvips.Image.system(cmd_format, in=list[Image], in_format=str, out_format=str, cache=bool)
:param cmd_format: Command to run
:type cmd_format: str
:param in: Array of input images
:type in: list[Image]
:param in_format: Format for input filename
:type in_format: str
:param out_format: Format for output filename
:type out_format: str
:param cache: Cache this call
:type cache: bool
:param out: enable output: Output image
:type out: bool
:param log: enable output: Command log
:type log: bool
:rtype: list[] or list[Dict[str, mixed]]
:raises Error:
.. staticmethod:: text(text, font=str, width=int, height=int, align=Union[str, Align], justify=bool, dpi=int, spacing=int, fontfile=str, rgba=bool, wrap=Union[str, TextWrap], autofit_dpi=bool)
Make a text image.
Example:
out = pyvips.Image.text(text, font=str, width=int, height=int, align=Union[str, Align], justify=bool, dpi=int, spacing=int, fontfile=str, rgba=bool, wrap=Union[str, TextWrap])
:param text: Text to render
:type text: str
:param font: Font to render with
:type font: str
:param width: Maximum image width in pixels
:type width: int
:param height: Maximum image height in pixels
:type height: int
:param align: Align on the low, centre or high edge
:type align: Union[str, Align]
:param justify: Justify lines
:type justify: bool
:param dpi: DPI to render at
:type dpi: int
:param spacing: Line spacing
:type spacing: int
:param fontfile: Load this font file
:type fontfile: str
:param rgba: Enable RGBA output
:type rgba: bool
:param wrap: Wrap lines on word or character boundaries
:type wrap: Union[str, TextWrap]
:param autofit_dpi: enable output: DPI selected by autofit
:type autofit_dpi: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: thumbnail(filename, width, height=int, size=Union[str, Size], no_rotate=bool, crop=Union[str, Interesting], linear=bool, input_profile=str, output_profile=str, intent=Union[str, Intent], fail_on=Union[str, FailOn])
Generate thumbnail from file.
Example:
out = pyvips.Image.thumbnail(filename, width, height=int, size=Union[str, Size], no_rotate=bool, crop=Union[str, Interesting], linear=bool, input_profile=str, output_profile=str, intent=Union[str, Intent], fail_on=Union[str, FailOn])
:param filename: Filename to read from
:type filename: str
:param width: Size to this width
:type width: int
:param height: Size to this height
:type height: int
:param size: Only upsize, only downsize, or both
:type size: Union[str, Size]
:param no_rotate: Don't use orientation tags to rotate image upright
:type no_rotate: bool
:param crop: Reduce to fill target rectangle, then crop
:type crop: Union[str, Interesting]
:param linear: Reduce in linear light
:type linear: bool
:param input_profile: Fallback input profile
:type input_profile: str
:param output_profile: Fallback output profile
:type output_profile: str
:param intent: Rendering intent
:type intent: Union[str, Intent]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:rtype: Image
:raises Error:
.. staticmethod:: thumbnail_buffer(buffer, width, option_string=str, height=int, size=Union[str, Size], no_rotate=bool, crop=Union[str, Interesting], linear=bool, input_profile=str, output_profile=str, intent=Union[str, Intent], fail_on=Union[str, FailOn])
Generate thumbnail from buffer.
Example:
out = pyvips.Image.thumbnail_buffer(buffer, width, option_string=str, height=int, size=Union[str, Size], no_rotate=bool, crop=Union[str, Interesting], linear=bool, input_profile=str, output_profile=str, intent=Union[str, Intent], fail_on=Union[str, FailOn])
:param buffer: Buffer to load from
:type buffer: str
:param width: Size to this width
:type width: int
:param option_string: Options that are passed on to the underlying loader
:type option_string: str
:param height: Size to this height
:type height: int
:param size: Only upsize, only downsize, or both
:type size: Union[str, Size]
:param no_rotate: Don't use orientation tags to rotate image upright
:type no_rotate: bool
:param crop: Reduce to fill target rectangle, then crop
:type crop: Union[str, Interesting]
:param linear: Reduce in linear light
:type linear: bool
:param input_profile: Fallback input profile
:type input_profile: str
:param output_profile: Fallback output profile
:type output_profile: str
:param intent: Rendering intent
:type intent: Union[str, Intent]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:rtype: Image
:raises Error:
.. method:: thumbnail_image(width, height=int, size=Union[str, Size], no_rotate=bool, crop=Union[str, Interesting], linear=bool, input_profile=str, output_profile=str, intent=Union[str, Intent], fail_on=Union[str, FailOn])
Generate thumbnail from image.
Example:
out = in.thumbnail_image(width, height=int, size=Union[str, Size], no_rotate=bool, crop=Union[str, Interesting], linear=bool, input_profile=str, output_profile=str, intent=Union[str, Intent], fail_on=Union[str, FailOn])
:param width: Size to this width
:type width: int
:param height: Size to this height
:type height: int
:param size: Only upsize, only downsize, or both
:type size: Union[str, Size]
:param no_rotate: Don't use orientation tags to rotate image upright
:type no_rotate: bool
:param crop: Reduce to fill target rectangle, then crop
:type crop: Union[str, Interesting]
:param linear: Reduce in linear light
:type linear: bool
:param input_profile: Fallback input profile
:type input_profile: str
:param output_profile: Fallback output profile
:type output_profile: str
:param intent: Rendering intent
:type intent: Union[str, Intent]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:rtype: Image
:raises Error:
.. staticmethod:: thumbnail_source(source, width, option_string=str, height=int, size=Union[str, Size], no_rotate=bool, crop=Union[str, Interesting], linear=bool, input_profile=str, output_profile=str, intent=Union[str, Intent], fail_on=Union[str, FailOn])
Generate thumbnail from source.
Example:
out = pyvips.Image.thumbnail_source(source, width, option_string=str, height=int, size=Union[str, Size], no_rotate=bool, crop=Union[str, Interesting], linear=bool, input_profile=str, output_profile=str, intent=Union[str, Intent], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param width: Size to this width
:type width: int
:param option_string: Options that are passed on to the underlying loader
:type option_string: str
:param height: Size to this height
:type height: int
:param size: Only upsize, only downsize, or both
:type size: Union[str, Size]
:param no_rotate: Don't use orientation tags to rotate image upright
:type no_rotate: bool
:param crop: Reduce to fill target rectangle, then crop
:type crop: Union[str, Interesting]
:param linear: Reduce in linear light
:type linear: bool
:param input_profile: Fallback input profile
:type input_profile: str
:param output_profile: Fallback output profile
:type output_profile: str
:param intent: Rendering intent
:type intent: Union[str, Intent]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:rtype: Image
:raises Error:
.. staticmethod:: tiffload(filename, page=int, n=int, autorotate=bool, subifd=int, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load tiff from file.
Example:
out = pyvips.Image.tiffload(filename, page=int, n=int, autorotate=bool, subifd=int, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param autorotate: Rotate image using orientation tag
:type autorotate: bool
:param subifd: Subifd index
:type subifd: int
:param unlimited: Remove all denial of service limits
:type unlimited: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: tiffload_buffer(buffer, page=int, n=int, autorotate=bool, subifd=int, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load tiff from buffer.
Example:
out = pyvips.Image.tiffload_buffer(buffer, page=int, n=int, autorotate=bool, subifd=int, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param buffer: Buffer to load from
:type buffer: str
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param autorotate: Rotate image using orientation tag
:type autorotate: bool
:param subifd: Subifd index
:type subifd: int
:param unlimited: Remove all denial of service limits
:type unlimited: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: tiffload_source(source, page=int, n=int, autorotate=bool, subifd=int, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load tiff from source.
Example:
out = pyvips.Image.tiffload_source(source, page=int, n=int, autorotate=bool, subifd=int, unlimited=bool, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param autorotate: Rotate image using orientation tag
:type autorotate: bool
:param subifd: Subifd index
:type subifd: int
:param unlimited: Remove all denial of service limits
:type unlimited: bool
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: tiffsave(filename, compression=Union[str, ForeignTiffCompression], Q=int, predictor=Union[str, ForeignTiffPredictor], tile=bool, tile_width=int, tile_height=int, pyramid=bool, miniswhite=bool, bitdepth=int, resunit=Union[str, ForeignTiffResunit], xres=float, yres=float, bigtiff=bool, properties=bool, region_shrink=Union[str, RegionShrink], level=int, lossless=bool, depth=Union[str, ForeignDzDepth], subifd=bool, premultiply=bool, keep=int, background=list[float], page_height=int, profile=str)
Save image to tiff file.
Example:
in.tiffsave(filename, compression=Union[str, ForeignTiffCompression], Q=int, predictor=Union[str, ForeignTiffPredictor], tile=bool, tile_width=int, tile_height=int, pyramid=bool, miniswhite=bool, bitdepth=int, resunit=Union[str, ForeignTiffResunit], xres=float, yres=float, bigtiff=bool, properties=bool, region_shrink=Union[str, RegionShrink], level=int, lossless=bool, depth=Union[str, ForeignDzDepth], subifd=bool, premultiply=bool, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param compression: Compression for this file
:type compression: Union[str, ForeignTiffCompression]
:param Q: Q factor
:type Q: int
:param predictor: Compression prediction
:type predictor: Union[str, ForeignTiffPredictor]
:param tile: Write a tiled tiff
:type tile: bool
:param tile_width: Tile width in pixels
:type tile_width: int
:param tile_height: Tile height in pixels
:type tile_height: int
:param pyramid: Write a pyramidal tiff
:type pyramid: bool
:param miniswhite: Use 0 for white in 1-bit images
:type miniswhite: bool
:param bitdepth: Write as a 1, 2, 4 or 8 bit image
:type bitdepth: int
:param resunit: Resolution unit
:type resunit: Union[str, ForeignTiffResunit]
:param xres: Horizontal resolution in pixels/mm
:type xres: float
:param yres: Vertical resolution in pixels/mm
:type yres: float
:param bigtiff: Write a bigtiff image
:type bigtiff: bool
:param properties: Write a properties document to IMAGEDESCRIPTION
:type properties: bool
:param region_shrink: Method to shrink regions
:type region_shrink: Union[str, RegionShrink]
:param level: Deflate (1-9, default 6) or ZSTD (1-22, default 9) compression level
:type level: int
:param lossless: Enable WEBP lossless mode
:type lossless: bool
:param depth: Pyramid depth
:type depth: Union[str, ForeignDzDepth]
:param subifd: Save pyr layers as sub-IFDs
:type subifd: bool
:param premultiply: Save with premultiplied alpha
:type premultiply: bool
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: tiffsave_buffer(compression=Union[str, ForeignTiffCompression], Q=int, predictor=Union[str, ForeignTiffPredictor], tile=bool, tile_width=int, tile_height=int, pyramid=bool, miniswhite=bool, bitdepth=int, resunit=Union[str, ForeignTiffResunit], xres=float, yres=float, bigtiff=bool, properties=bool, region_shrink=Union[str, RegionShrink], level=int, lossless=bool, depth=Union[str, ForeignDzDepth], subifd=bool, premultiply=bool, keep=int, background=list[float], page_height=int, profile=str)
Save image to tiff buffer.
Example:
buffer = in.tiffsave_buffer(compression=Union[str, ForeignTiffCompression], Q=int, predictor=Union[str, ForeignTiffPredictor], tile=bool, tile_width=int, tile_height=int, pyramid=bool, miniswhite=bool, bitdepth=int, resunit=Union[str, ForeignTiffResunit], xres=float, yres=float, bigtiff=bool, properties=bool, region_shrink=Union[str, RegionShrink], level=int, lossless=bool, depth=Union[str, ForeignDzDepth], subifd=bool, premultiply=bool, keep=int, background=list[float], page_height=int, profile=str)
:param compression: Compression for this file
:type compression: Union[str, ForeignTiffCompression]
:param Q: Q factor
:type Q: int
:param predictor: Compression prediction
:type predictor: Union[str, ForeignTiffPredictor]
:param tile: Write a tiled tiff
:type tile: bool
:param tile_width: Tile width in pixels
:type tile_width: int
:param tile_height: Tile height in pixels
:type tile_height: int
:param pyramid: Write a pyramidal tiff
:type pyramid: bool
:param miniswhite: Use 0 for white in 1-bit images
:type miniswhite: bool
:param bitdepth: Write as a 1, 2, 4 or 8 bit image
:type bitdepth: int
:param resunit: Resolution unit
:type resunit: Union[str, ForeignTiffResunit]
:param xres: Horizontal resolution in pixels/mm
:type xres: float
:param yres: Vertical resolution in pixels/mm
:type yres: float
:param bigtiff: Write a bigtiff image
:type bigtiff: bool
:param properties: Write a properties document to IMAGEDESCRIPTION
:type properties: bool
:param region_shrink: Method to shrink regions
:type region_shrink: Union[str, RegionShrink]
:param level: Deflate (1-9, default 6) or ZSTD (1-22, default 9) compression level
:type level: int
:param lossless: Enable WEBP lossless mode
:type lossless: bool
:param depth: Pyramid depth
:type depth: Union[str, ForeignDzDepth]
:param subifd: Save pyr layers as sub-IFDs
:type subifd: bool
:param premultiply: Save with premultiplied alpha
:type premultiply: bool
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: str
:raises Error:
.. method:: tiffsave_target(target, compression=Union[str, ForeignTiffCompression], Q=int, predictor=Union[str, ForeignTiffPredictor], tile=bool, tile_width=int, tile_height=int, pyramid=bool, miniswhite=bool, bitdepth=int, resunit=Union[str, ForeignTiffResunit], xres=float, yres=float, bigtiff=bool, properties=bool, region_shrink=Union[str, RegionShrink], level=int, lossless=bool, depth=Union[str, ForeignDzDepth], subifd=bool, premultiply=bool, keep=int, background=list[float], page_height=int, profile=str)
Save image to tiff target.
Example:
in.tiffsave_target(target, compression=Union[str, ForeignTiffCompression], Q=int, predictor=Union[str, ForeignTiffPredictor], tile=bool, tile_width=int, tile_height=int, pyramid=bool, miniswhite=bool, bitdepth=int, resunit=Union[str, ForeignTiffResunit], xres=float, yres=float, bigtiff=bool, properties=bool, region_shrink=Union[str, RegionShrink], level=int, lossless=bool, depth=Union[str, ForeignDzDepth], subifd=bool, premultiply=bool, keep=int, background=list[float], page_height=int, profile=str)
:param target: Target to save to
:type target: Target
:param compression: Compression for this file
:type compression: Union[str, ForeignTiffCompression]
:param Q: Q factor
:type Q: int
:param predictor: Compression prediction
:type predictor: Union[str, ForeignTiffPredictor]
:param tile: Write a tiled tiff
:type tile: bool
:param tile_width: Tile width in pixels
:type tile_width: int
:param tile_height: Tile height in pixels
:type tile_height: int
:param pyramid: Write a pyramidal tiff
:type pyramid: bool
:param miniswhite: Use 0 for white in 1-bit images
:type miniswhite: bool
:param bitdepth: Write as a 1, 2, 4 or 8 bit image
:type bitdepth: int
:param resunit: Resolution unit
:type resunit: Union[str, ForeignTiffResunit]
:param xres: Horizontal resolution in pixels/mm
:type xres: float
:param yres: Vertical resolution in pixels/mm
:type yres: float
:param bigtiff: Write a bigtiff image
:type bigtiff: bool
:param properties: Write a properties document to IMAGEDESCRIPTION
:type properties: bool
:param region_shrink: Method to shrink regions
:type region_shrink: Union[str, RegionShrink]
:param level: Deflate (1-9, default 6) or ZSTD (1-22, default 9) compression level
:type level: int
:param lossless: Enable WEBP lossless mode
:type lossless: bool
:param depth: Pyramid depth
:type depth: Union[str, ForeignDzDepth]
:param subifd: Save pyr layers as sub-IFDs
:type subifd: bool
:param premultiply: Save with premultiplied alpha
:type premultiply: bool
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: tilecache(tile_width=int, tile_height=int, max_tiles=int, access=Union[str, Access], threaded=bool, persistent=bool)
Cache an image as a set of tiles.
Example:
out = in.tilecache(tile_width=int, tile_height=int, max_tiles=int, access=Union[str, Access], threaded=bool, persistent=bool)
:param tile_width: Tile width in pixels
:type tile_width: int
:param tile_height: Tile height in pixels
:type tile_height: int
:param max_tiles: Maximum number of tiles to cache
:type max_tiles: int
:param access: Expected access pattern
:type access: Union[str, Access]
:param threaded: Allow threaded access
:type threaded: bool
:param persistent: Keep cache between evaluations
:type persistent: bool
:rtype: Image
:raises Error:
.. staticmethod:: tonelut(in_max=int, out_max=int, Lb=float, Lw=float, Ps=float, Pm=float, Ph=float, S=float, M=float, H=float)
Build a look-up table.
Example:
out = pyvips.Image.tonelut(in_max=int, out_max=int, Lb=float, Lw=float, Ps=float, Pm=float, Ph=float, S=float, M=float, H=float)
:param in_max: Size of LUT to build
:type in_max: int
:param out_max: Maximum value in output LUT
:type out_max: int
:param Lb: Lowest value in output
:type Lb: float
:param Lw: Highest value in output
:type Lw: float
:param Ps: Position of shadow
:type Ps: float
:param Pm: Position of mid-tones
:type Pm: float
:param Ph: Position of highlights
:type Ph: float
:param S: Adjust shadows by this much
:type S: float
:param M: Adjust mid-tones by this much
:type M: float
:param H: Adjust highlights by this much
:type H: float
:rtype: Image
:raises Error:
.. method:: transpose3d(page_height=int)
Transpose3d an image.
Example:
out = in.transpose3d(page_height=int)
:param page_height: Height of each input page
:type page_height: int
:rtype: Image
:raises Error:
.. method:: uhdr2scRGB()
Transform uhdr to scRGB.
Example:
out = in.uhdr2scRGB()
:rtype: Image
:raises Error:
.. staticmethod:: uhdrload(filename, shrink=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load a UHDR image.
Example:
out = pyvips.Image.uhdrload(filename, shrink=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param shrink: Shrink factor on load
:type shrink: int
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: uhdrload_buffer(buffer, shrink=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load a UHDR image.
Example:
out = pyvips.Image.uhdrload_buffer(buffer, shrink=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param buffer: Buffer to load from
:type buffer: str
:param shrink: Shrink factor on load
:type shrink: int
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: uhdrload_source(source, shrink=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load a UHDR image.
Example:
out = pyvips.Image.uhdrload_source(source, shrink=int, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param shrink: Shrink factor on load
:type shrink: int
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: uhdrsave(filename, Q=int, keep=int, background=list[float], page_height=int, profile=str)
Save image in UltraHDR format.
Example:
in.uhdrsave(filename, Q=int, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param Q: Q factor
:type Q: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: uhdrsave_buffer(Q=int, keep=int, background=list[float], page_height=int, profile=str)
Save image in UltraHDR format.
Example:
buffer = in.uhdrsave_buffer(Q=int, keep=int, background=list[float], page_height=int, profile=str)
:param Q: Q factor
:type Q: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: str
:raises Error:
.. method:: uhdrsave_target(target, Q=int, keep=int, background=list[float], page_height=int, profile=str)
Save image in UltraHDR format.
Example:
in.uhdrsave_target(target, Q=int, keep=int, background=list[float], page_height=int, profile=str)
:param target: Target to save to
:type target: Target
:param Q: Q factor
:type Q: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: unpremultiply(max_alpha=float, alpha_band=int)
Unpremultiply image alpha.
Example:
out = in.unpremultiply(max_alpha=float, alpha_band=int)
:param max_alpha: Maximum value of alpha channel
:type max_alpha: float
:param alpha_band: Unpremultiply with this alpha
:type alpha_band: int
:rtype: Image
:raises Error:
.. staticmethod:: vipsload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load vips from file.
Example:
out = pyvips.Image.vipsload(filename, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: vipsload_source(source, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load vips from source.
Example:
out = pyvips.Image.vipsload_source(source, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: vipssave(filename, keep=int, background=list[float], page_height=int, profile=str)
Save image to file in vips format.
Example:
in.vipssave(filename, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: vipssave_target(target, keep=int, background=list[float], page_height=int, profile=str)
Save image to target in vips format.
Example:
in.vipssave_target(target, keep=int, background=list[float], page_height=int, profile=str)
:param target: Target to save to
:type target: Target
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. staticmethod:: webpload(filename, page=int, n=int, scale=float, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool, flags=bool)
Load webp from file.
Example:
out = pyvips.Image.webpload(filename, page=int, n=int, scale=float, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], revalidate=bool)
:param filename: Filename to load from
:type filename: str
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param scale: Factor to scale by
:type scale: float
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param revalidate: Don't use a cached result for this operation
:type revalidate: bool
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: webpload_buffer(buffer, page=int, n=int, scale=float, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load webp from buffer.
Example:
out = pyvips.Image.webpload_buffer(buffer, page=int, n=int, scale=float, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param buffer: Buffer to load from
:type buffer: str
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param scale: Factor to scale by
:type scale: float
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. staticmethod:: webpload_source(source, page=int, n=int, scale=float, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn], flags=bool)
Load webp from source.
Example:
out = pyvips.Image.webpload_source(source, page=int, n=int, scale=float, memory=bool, access=Union[str, Access], fail_on=Union[str, FailOn])
:param source: Source to load from
:type source: Source
:param page: First page to load
:type page: int
:param n: Number of pages to load, -1 for all
:type n: int
:param scale: Factor to scale by
:type scale: float
:param memory: Force open via memory
:type memory: bool
:param access: Required access pattern for this file
:type access: Union[str, Access]
:param fail_on: Error level to fail on
:type fail_on: Union[str, FailOn]
:param flags: enable output: Flags for this file
:type flags: bool
:rtype: Image or list[Image, Dict[str, mixed]]
:raises Error:
.. method:: webpsave(filename, Q=int, lossless=bool, exact=bool, preset=Union[str, ForeignWebpPreset], smart_subsample=bool, near_lossless=bool, alpha_q=int, min_size=bool, kmin=int, kmax=int, effort=int, target_size=int, mixed=bool, smart_deblock=bool, passes=int, keep=int, background=list[float], page_height=int, profile=str)
Save as WebP.
Example:
in.webpsave(filename, Q=int, lossless=bool, exact=bool, preset=Union[str, ForeignWebpPreset], smart_subsample=bool, near_lossless=bool, alpha_q=int, min_size=bool, kmin=int, kmax=int, effort=int, target_size=int, mixed=bool, smart_deblock=bool, passes=int, keep=int, background=list[float], page_height=int, profile=str)
:param filename: Filename to save to
:type filename: str
:param Q: Q factor
:type Q: int
:param lossless: Enable lossless compression
:type lossless: bool
:param exact: Preserve color values from transparent pixels
:type exact: bool
:param preset: Preset for lossy compression
:type preset: Union[str, ForeignWebpPreset]
:param smart_subsample: Enable high quality chroma subsampling
:type smart_subsample: bool
:param near_lossless: Enable preprocessing in lossless mode (uses Q)
:type near_lossless: bool
:param alpha_q: Change alpha plane fidelity for lossy compression
:type alpha_q: int
:param min_size: Optimise for minimum size
:type min_size: bool
:param kmin: Minimum number of frames between key frames
:type kmin: int
:param kmax: Maximum number of frames between key frames
:type kmax: int
:param effort: Level of CPU effort to reduce file size
:type effort: int
:param target_size: Desired target size in bytes
:type target_size: int
:param mixed: Allow mixed encoding (might reduce file size)
:type mixed: bool
:param smart_deblock: Enable auto-adjusting of the deblocking filter
:type smart_deblock: bool
:param passes: Number of entropy-analysis passes (in [1..10])
:type passes: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: webpsave_buffer(Q=int, lossless=bool, exact=bool, preset=Union[str, ForeignWebpPreset], smart_subsample=bool, near_lossless=bool, alpha_q=int, min_size=bool, kmin=int, kmax=int, effort=int, target_size=int, mixed=bool, smart_deblock=bool, passes=int, keep=int, background=list[float], page_height=int, profile=str)
Save as WebP.
Example:
buffer = in.webpsave_buffer(Q=int, lossless=bool, exact=bool, preset=Union[str, ForeignWebpPreset], smart_subsample=bool, near_lossless=bool, alpha_q=int, min_size=bool, kmin=int, kmax=int, effort=int, target_size=int, mixed=bool, smart_deblock=bool, passes=int, keep=int, background=list[float], page_height=int, profile=str)
:param Q: Q factor
:type Q: int
:param lossless: Enable lossless compression
:type lossless: bool
:param exact: Preserve color values from transparent pixels
:type exact: bool
:param preset: Preset for lossy compression
:type preset: Union[str, ForeignWebpPreset]
:param smart_subsample: Enable high quality chroma subsampling
:type smart_subsample: bool
:param near_lossless: Enable preprocessing in lossless mode (uses Q)
:type near_lossless: bool
:param alpha_q: Change alpha plane fidelity for lossy compression
:type alpha_q: int
:param min_size: Optimise for minimum size
:type min_size: bool
:param kmin: Minimum number of frames between key frames
:type kmin: int
:param kmax: Maximum number of frames between key frames
:type kmax: int
:param effort: Level of CPU effort to reduce file size
:type effort: int
:param target_size: Desired target size in bytes
:type target_size: int
:param mixed: Allow mixed encoding (might reduce file size)
:type mixed: bool
:param smart_deblock: Enable auto-adjusting of the deblocking filter
:type smart_deblock: bool
:param passes: Number of entropy-analysis passes (in [1..10])
:type passes: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: str
:raises Error:
.. method:: webpsave_mime(Q=int, lossless=bool, exact=bool, preset=Union[str, ForeignWebpPreset], smart_subsample=bool, near_lossless=bool, alpha_q=int, min_size=bool, kmin=int, kmax=int, effort=int, target_size=int, mixed=bool, smart_deblock=bool, passes=int, keep=int, background=list[float], page_height=int, profile=str)
Save image to webp mime.
Example:
in.webpsave_mime(Q=int, lossless=bool, exact=bool, preset=Union[str, ForeignWebpPreset], smart_subsample=bool, near_lossless=bool, alpha_q=int, min_size=bool, kmin=int, kmax=int, effort=int, target_size=int, mixed=bool, smart_deblock=bool, passes=int, keep=int, background=list[float], page_height=int, profile=str)
:param Q: Q factor
:type Q: int
:param lossless: Enable lossless compression
:type lossless: bool
:param exact: Preserve color values from transparent pixels
:type exact: bool
:param preset: Preset for lossy compression
:type preset: Union[str, ForeignWebpPreset]
:param smart_subsample: Enable high quality chroma subsampling
:type smart_subsample: bool
:param near_lossless: Enable preprocessing in lossless mode (uses Q)
:type near_lossless: bool
:param alpha_q: Change alpha plane fidelity for lossy compression
:type alpha_q: int
:param min_size: Optimise for minimum size
:type min_size: bool
:param kmin: Minimum number of frames between key frames
:type kmin: int
:param kmax: Maximum number of frames between key frames
:type kmax: int
:param effort: Level of CPU effort to reduce file size
:type effort: int
:param target_size: Desired target size in bytes
:type target_size: int
:param mixed: Allow mixed encoding (might reduce file size)
:type mixed: bool
:param smart_deblock: Enable auto-adjusting of the deblocking filter
:type smart_deblock: bool
:param passes: Number of entropy-analysis passes (in [1..10])
:type passes: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. method:: webpsave_target(target, Q=int, lossless=bool, exact=bool, preset=Union[str, ForeignWebpPreset], smart_subsample=bool, near_lossless=bool, alpha_q=int, min_size=bool, kmin=int, kmax=int, effort=int, target_size=int, mixed=bool, smart_deblock=bool, passes=int, keep=int, background=list[float], page_height=int, profile=str)
Save as WebP.
Example:
in.webpsave_target(target, Q=int, lossless=bool, exact=bool, preset=Union[str, ForeignWebpPreset], smart_subsample=bool, near_lossless=bool, alpha_q=int, min_size=bool, kmin=int, kmax=int, effort=int, target_size=int, mixed=bool, smart_deblock=bool, passes=int, keep=int, background=list[float], page_height=int, profile=str)
:param target: Target to save to
:type target: Target
:param Q: Q factor
:type Q: int
:param lossless: Enable lossless compression
:type lossless: bool
:param exact: Preserve color values from transparent pixels
:type exact: bool
:param preset: Preset for lossy compression
:type preset: Union[str, ForeignWebpPreset]
:param smart_subsample: Enable high quality chroma subsampling
:type smart_subsample: bool
:param near_lossless: Enable preprocessing in lossless mode (uses Q)
:type near_lossless: bool
:param alpha_q: Change alpha plane fidelity for lossy compression
:type alpha_q: int
:param min_size: Optimise for minimum size
:type min_size: bool
:param kmin: Minimum number of frames between key frames
:type kmin: int
:param kmax: Maximum number of frames between key frames
:type kmax: int
:param effort: Level of CPU effort to reduce file size
:type effort: int
:param target_size: Desired target size in bytes
:type target_size: int
:param mixed: Allow mixed encoding (might reduce file size)
:type mixed: bool
:param smart_deblock: Enable auto-adjusting of the deblocking filter
:type smart_deblock: bool
:param passes: Number of entropy-analysis passes (in [1..10])
:type passes: int
:param keep: Which metadata to retain
:type keep: int
:param background: Background value
:type background: list[float]
:param page_height: Set page height for multipage save
:type page_height: int
:param profile: Filename of ICC profile to embed
:type profile: str
:rtype: list[]
:raises Error:
.. staticmethod:: worley(width, height, cell_size=int, seed=int)
Make a worley noise image.
Example:
out = pyvips.Image.worley(width, height, cell_size=int, seed=int)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param cell_size: Size of Worley cells
:type cell_size: int
:param seed: Random number seed
:type seed: int
:rtype: Image
:raises Error:
.. method:: wrap(x=int, y=int)
Wrap image origin.
Example:
out = in.wrap(x=int, y=int)
:param x: Left edge of input in output
:type x: int
:param y: Top edge of input in output
:type y: int
:rtype: Image
:raises Error:
.. staticmethod:: xyz(width, height, csize=int, dsize=int, esize=int)
Make an image where pixel values are coordinates.
Example:
out = pyvips.Image.xyz(width, height, csize=int, dsize=int, esize=int)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param csize: Size of third dimension
:type csize: int
:param dsize: Size of fourth dimension
:type dsize: int
:param esize: Size of fifth dimension
:type esize: int
:rtype: Image
:raises Error:
.. staticmethod:: zone(width, height, uchar=bool)
Make a zone plate.
Example:
out = pyvips.Image.zone(width, height, uchar=bool)
:param width: Image width in pixels
:type width: int
:param height: Image height in pixels
:type height: int
:param uchar: Output an unsigned char image
:type uchar: bool
:rtype: Image
:raises Error:
.. method:: zoom(xfac, yfac)
Zoom an image.
Example:
out = input.zoom(xfac, yfac)
:param xfac: Horizontal zoom factor
:type xfac: int
:param yfac: Vertical zoom factor
:type yfac: int
:rtype: Image
:raises Error:
python-pyvips-3.1.1/doc/vinterpolate.rst 0000664 0000000 0000000 00000000156 15222163673 0020411 0 ustar 00root root 0000000 0000000 .. include global.rst
``Interpolate``
===============
.. automodule:: pyvips.vinterpolate
:members:
python-pyvips-3.1.1/doc/vobject.rst 0000664 0000000 0000000 00000000147 15222163673 0017331 0 ustar 00root root 0000000 0000000 .. include global.rst
``VipsObject``
==============
.. automodule:: pyvips.vobject
:members:
python-pyvips-3.1.1/doc/voperation.rst 0000664 0000000 0000000 00000000150 15222163673 0020055 0 ustar 00root root 0000000 0000000 .. include global.rst
``Operation``
=============
.. automodule:: pyvips.voperation
:members:
python-pyvips-3.1.1/doc/vsource.rst 0000664 0000000 0000000 00000000137 15222163673 0017362 0 ustar 00root root 0000000 0000000 .. include global.rst
``Source``
==========
.. automodule:: pyvips.vsource
:members:
python-pyvips-3.1.1/doc/vsourcecustom.rst 0000664 0000000 0000000 00000000161 15222163673 0020612 0 ustar 00root root 0000000 0000000 .. include global.rst
``SourceCustom``
================
.. automodule:: pyvips.vsourcecustom
:members:
python-pyvips-3.1.1/doc/vtarget.rst 0000664 0000000 0000000 00000000137 15222163673 0017350 0 ustar 00root root 0000000 0000000 .. include global.rst
``Target``
==========
.. automodule:: pyvips.vtarget
:members:
python-pyvips-3.1.1/doc/vtargetcustom.rst 0000664 0000000 0000000 00000000161 15222163673 0020600 0 ustar 00root root 0000000 0000000 .. include global.rst
``TargetCustom``
================
.. automodule:: pyvips.vtargetcustom
:members:
python-pyvips-3.1.1/examples/ 0000775 0000000 0000000 00000000000 15222163673 0016212 5 ustar 00root root 0000000 0000000 python-pyvips-3.1.1/examples/affine.py 0000775 0000000 0000000 00000000341 15222163673 0020015 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
x = pyvips.Image.new_from_file(sys.argv[1])
if not x.hasalpha():
x = x.addalpha()
y = x.affine([0.70710678, 0.70710678, -0.70710678, 0.70710678])
y.write_to_file(sys.argv[2])
python-pyvips-3.1.1/examples/annotate-animation.py 0000775 0000000 0000000 00000001370 15222163673 0022356 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
if len(sys.argv) != 4:
print(f"usage: {sys.argv[0]} input-animation output-animation text")
sys.exit(1)
text = pyvips.Image.text(sys.argv[3], dpi=300, rgba=True)
# draw an overlay on a page ... this could do anything
def process_page(page, i):
return page.composite(text, "over",
x=(i * 4) % page.width,
y=(i * 4) % page.height)
# load the animation, chop into pages, rejoin, save
animation = pyvips.Image.new_from_file(sys.argv[1], n=-1, access="sequential")
pages = animation.pagesplit()
pages = [process_page(page, i) for page, i in zip(pages, range(len(pages)))]
animation = pages[0].pagejoin(pages[1:])
animation.write_to_file(sys.argv[2])
python-pyvips-3.1.1/examples/cod.py 0000775 0000000 0000000 00000003032 15222163673 0017332 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
# import logging
# logging.basicConfig(level = logging.DEBUG)
# pyvips.cache_set_trace(True)
def to_polar(image):
"""Transform image coordinates to polar.
The image is transformed so that it is wrapped around a point in the
centre. Vertical straight lines become circles or segments of circles,
horizontal straight lines become radial spokes.
"""
# xy image, origin in the centre, scaled to fit image to a circle
xy = pyvips.Image.xyz(image.width, image.height)
xy -= [image.width / 2.0, image.height / 2.0]
scale = min(image.width, image.height) / float(image.width)
xy *= 2.0 / scale
index = xy.polar()
# scale vertical axis to 360 degrees
index *= [1, image.height / 360.0]
return image.mapim(index)
def to_rectangular(image):
"""Transform image coordinates to rectangular.
The image is transformed so that it is unwrapped from a point in the
centre. Circles or segments of circles become vertical straight lines,
radial lines become horizontal lines.
"""
# xy image, vertical scaled to 360 degrees
xy = pyvips.Image.xyz(image.width, image.height)
xy *= [1, 360.0 / image.height]
index = xy.rect()
# scale to image rect
scale = min(image.width, image.height) / float(image.width)
index *= scale / 2.0
index += [image.width / 2.0, image.height / 2.0]
return image.mapim(index)
a = pyvips.Image.new_from_file(sys.argv[1])
a = to_polar(a)
a = to_rectangular(a)
a.write_to_file(sys.argv[2])
python-pyvips-3.1.1/examples/connection.py 0000775 0000000 0000000 00000003356 15222163673 0020735 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
if len(sys.argv) != 4:
print(f"usage: {sys.argv[0]} IN-FILE OUT-FILE FORMAT")
print(f" eg.: {sys.argv[0]} ~/pics/k2.jpg x .tif[tile]")
sys.exit(1)
def source_custom(filename):
input_file = open(sys.argv[1], "rb")
def read_handler(size):
return input_file.read(size)
# seek is optional, but may improve performance by reducing buffering
def seek_handler(offset, whence):
input_file.seek(offset, whence)
return input_file.tell()
source = pyvips.SourceCustom()
source.on_read(read_handler)
source.on_seek(seek_handler)
return source
def target_custom(filename):
# w+ means read and write ... we need to be able to read from our output
# stream for TIFF write
output_file = open(sys.argv[2], "w+b")
def write_handler(chunk):
return output_file.write(chunk)
# read and seek are optional and only needed for formats like TIFF
def read_handler(size):
return output_file.read(size)
def seek_handler(offset, whence):
output_file.seek(offset, whence)
return output_file.tell()
def end_handler():
# you can't throw exceptions over on_ handlers, you must return an
# error code
try:
output_file.close()
except IOError:
return -1
else:
return 0
target = pyvips.TargetCustom()
target.on_write(write_handler)
target.on_read(read_handler)
target.on_seek(seek_handler)
target.on_end(end_handler)
return target
source = source_custom(sys.argv[1])
target = target_custom(sys.argv[2])
image = pyvips.Image.new_from_source(source, '', access='sequential')
image.write_to_target(target, sys.argv[3])
python-pyvips-3.1.1/examples/convolve.py 0000775 0000000 0000000 00000001356 15222163673 0020427 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
""" example pyvips code to convolve an image with a 3x3 mask
args: inputfile outputfile
no error checking for simplicity
Notes: the convolution mask can be other sizes,
here we use a scale of 1 (no scaling - see libvips conv docs)
https://www.libvips.org/API/current/libvips-convolution.html#vips-conv
and offset of 128 so zero output is mid-grey
"""
import pyvips
import sys
image = pyvips.Image.new_from_file(sys.argv[1], access='sequential')
mask = pyvips.Image.new_from_array([[1, 1, 1],
[1, -8, 1],
[1, 1, 1]
], scale=1, offset=128)
image = image.conv(mask, precision='integer')
image.write_to_file(sys.argv[2])
python-pyvips-3.1.1/examples/gen-enums.py 0000775 0000000 0000000 00000013265 15222163673 0020474 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
import sys
import xml.etree.ElementTree as ET
from pyvips import ffi, enum_dict, flags_dict, \
type_map, type_name, type_from_name
# This file generates enums.py -- the set of classes giving the permissible
# values for the pyvips enums/flags. Run with something like:
#
# ./gen-enums.py ~/GIT/libvips/build/libvips/Vips-8.0.gir > enums.py
# mv enums.py ../pyvips
# The GIR file
root = ET.parse(sys.argv[1]).getroot()
namespace = {
"goi": "http://www.gtk.org/introspection/core/1.0"
}
# find all the enumerations/flags and make a dict for them
xml_enums = {}
for node in root.findall("goi:namespace/goi:enumeration", namespace):
xml_enums[node.get('name')] = node
xml_flags = {}
for node in root.findall("goi:namespace/goi:bitfield", namespace):
xml_flags[node.get('name')] = node
def remove_prefix(enum_str):
prefix = 'Vips'
if enum_str.startswith(prefix):
return enum_str[len(prefix):]
return enum_str
def rewrite_references(string):
"""Rewrite a gi-docgen references to RST style.
gi-docgen references look like this:
[func@version]
[class@Image]
[func@Image.bandjoin]
[meth@Image.add]
[ctor@Image.new_from_file]
[enum@SdfShape]
[enum@Vips.SdfShape.CIRCLE]
we look for the approximate patterns and rewrite in RST style, so:
:meth:`.version`
:class:`.Image`
:meth:`.Image.bandjoin`
:meth:`.Image.new_from_file`
:class:`.enums.SdfShape`
:class:`.enums.SdfShape.CIRCLE`
"""
import re
while True:
match = re.search(r"\[(.*?)@(.*?)\]", string)
if not match:
break
before = string[0:match.span(0)[0]]
type = match[1]
target = match[2]
after = string[match.span(0)[1]:]
if type in ["ctor", "meth", "method", "func"]:
python_type = "meth"
elif type in ["class", "enum", "flags"]:
python_type = "class"
else:
raise Exception(f'type "{type}" is unknown')
match = re.match("Vips.(.*)", target)
if match:
target = match[1]
if type == "enum":
target = f"enums.{target}"
string = f"{before}:{python_type}:`.{target}`{after}"
return string
def generate_enums():
all_nicknames = []
def add_nickname(gtype, a, b):
nickname = type_name(gtype)
all_nicknames.append(nickname)
type_map(gtype, add_nickname)
return ffi.NULL
type_map(type_from_name('GEnum'), add_nickname)
# Filter internal enums
blacklist = ['VipsDemandStyle']
all_nicknames = [name for name in all_nicknames if name not in blacklist]
for name in all_nicknames:
gtype = type_from_name(name)
python_name = remove_prefix(name)
if python_name not in xml_enums:
continue
node = xml_enums[python_name]
values = enum_dict(gtype)
enum_doc = node.find("goi:doc", namespace)
print('')
print('')
print(f'class {python_name}(object):')
print(f' """{python_name}.')
if enum_doc is not None:
print('')
print(f'{rewrite_references(enum_doc.text)}')
print('')
print('Attributes:')
print('')
for key, value in values.items():
python_name = key.replace('-', '_')
member = node.find(f"goi:member[@name='{python_name}']", namespace)
member_doc = member.find("goi:doc", namespace)
if member_doc is not None:
text = rewrite_references(member_doc.text)
print(f' {python_name.upper()} (str): {text}')
print('')
print(' """')
print('')
for key, value in values.items():
python_name = key.replace('-', '_').upper()
print(f' {python_name} = \'{key}\'')
def generate_flags():
all_nicknames = []
def add_nickname(gtype, a, b):
nickname = type_name(gtype)
all_nicknames.append(nickname)
type_map(gtype, add_nickname)
return ffi.NULL
type_map(type_from_name('GFlags'), add_nickname)
# Filter internal flags
blacklist = ['VipsForeignFlags']
all_nicknames = [name for name in all_nicknames if name not in blacklist]
for name in all_nicknames:
gtype = type_from_name(name)
python_name = remove_prefix(name)
if python_name not in xml_flags:
continue
node = xml_flags[python_name]
values = flags_dict(gtype)
enum_doc = node.find("goi:doc", namespace)
print('')
print('')
print(f'class {python_name}(object):')
print(f' """{python_name}.')
if enum_doc is not None:
print('')
print(f'{rewrite_references(enum_doc.text)}')
print('')
print('Attributes:')
print('')
for key, value in values.items():
python_name = key.replace('-', '_')
member = node.find(f"goi:member[@name='{python_name}']", namespace)
member_doc = member.find("goi:doc", namespace)
if member_doc is not None:
text = member_doc.text
print(f' {python_name.upper()} (int): '
f'{rewrite_references(text)}')
print('')
print(' """')
print('')
for key, value in values.items():
python_name = key.replace('-', '_').upper()
print(f' {python_name} = {value}')
if __name__ == "__main__":
print('# libvips enums -- this file is generated automatically')
print('# flake8: noqa: E501') # ignore line too long error
generate_enums()
generate_flags()
python-pyvips-3.1.1/examples/join-animation.py 0000775 0000000 0000000 00000001126 15222163673 0021503 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
if len(sys.argv) < 3:
print(f"usage: {sys.argv[0]} output-image frame1 frame2 ...")
sys.exit(1)
# the input images
# assume these are all the same size
images = [pyvips.Image.new_from_file(filename, access="sequential")
for filename in sys.argv[2:]]
animation = images[0].pagejoin(images[1:])
# frame delays are in milliseconds ... 300 is pretty slow!
delay_array = [300] * len(images)
animation.set_type(pyvips.GValue.array_int_type, "delay", delay_array)
print(f"writing {sys.argv[1]} ...")
animation.write_to_file(sys.argv[1])
python-pyvips-3.1.1/examples/orientation.py 0000775 0000000 0000000 00000000423 15222163673 0021121 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
a = pyvips.Image.new_from_file(sys.argv[1])
try:
orientation = a.get('exif-ifd0-Orientation')
a.set('orientation', int(orientation.split()[0]))
except Exception:
a.set('orientation', 0)
a.write_to_file(sys.argv[2])
python-pyvips-3.1.1/examples/pil-numpy-pyvips.py 0000775 0000000 0000000 00000001737 15222163673 0022061 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import time
import pyvips
from PIL import Image
import numpy as np
if len(sys.argv) != 3:
print(f'usage: {sys.argv[0]} input-filename output-filename')
sys.exit(-1)
# load with PIL
start_pillow = time.time()
pillow_img = np.asarray(Image.open(sys.argv[1]))
print('Pillow Time:', time.time() - start_pillow)
print('pil shape', pillow_img.shape)
# load with vips to a memory array
start_vips = time.time()
img = pyvips.Image.new_from_file(sys.argv[1])
np_3d = np.asarray(img) # or img.numpy()
print('Vips Time:', time.time() - start_vips)
print('vips shape', np_3d.shape)
# make a vips image from the PIL image
vi = pyvips.Image.new_from_array(pillow_img)
# verify we have the same result
# this can be non-zero for formats like jpg if the two libraries are using
# different libjpg versions ... try with png instead
print('Average pil/vips difference:', (vi - img).avg())
# and write back to disc for checking
vi.write_to_file(sys.argv[2])
python-pyvips-3.1.1/examples/progress.py 0000775 0000000 0000000 00000001674 15222163673 0020443 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import pyvips
def progress_print(name, progress):
print(f'signal {name}:')
print(f' run = {progress.run} (seconds of run time)')
print(f' eta = {progress.eta} (estimated seconds left)')
print(f' tpels = {progress.tpels} (total number of pels)')
print(f' npels = {progress.npels} (number of pels computed so far)')
print(f' percent = {progress.percent} (percent complete)')
def preeval_cb(image, progress):
progress_print('preeval', progress)
def eval_cb(image, progress):
progress_print('eval', progress)
# you can kill computation if necessary
if progress.percent > 50:
image.set_kill(True)
def posteval_cb(image, progress):
progress_print('posteval', progress)
image = pyvips.Image.black(1, 500)
image.set_progress(True)
image.signal_connect('preeval', preeval_cb)
image.signal_connect('eval', eval_cb)
image.signal_connect('posteval', posteval_cb)
image.avg()
python-pyvips-3.1.1/examples/read_profile.py 0000775 0000000 0000000 00000000421 15222163673 0021217 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
# import logging
# logging.basicConfig(level = logging.DEBUG)
# pyvips.cache_set_trace(True)
a = pyvips.Image.new_from_file(sys.argv[1])
profile = a.get("icc-profile-data")
with open('x.icm', 'w') as f:
f.write(profile)
python-pyvips-3.1.1/examples/shepard.py 0000775 0000000 0000000 00000002630 15222163673 0020216 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
# Shepard's distortion, from https://github.com/tourtiere/light-distortion
# with kind permission.
# Use a set of control points to distort an image.
# Usage:
# ./shepard.py ~/pics/k2.jpg x.jpg "300,400 300,500 300,1500 300,1100"
import re
import sys
from typing import Tuple, List
import pyvips
Point = Tuple[int, int]
Couple = Tuple[Point, Point]
def shepards(image: pyvips.Image, couples: List[Couple]) -> pyvips.Image:
"""Shepard's distortion.
Distort an image with a set of control points.
"""
index = pyvips.Image.xyz(image.width, image.height)
deltas = []
weights = []
for p1, p2 in couples:
diff = index - list(p2)
distance = (diff[0]**2 + diff[1]**2)
distance = distance.ifthenelse(distance, 0.1)
weight = 1.0 / distance
delta = [(p1[0] - p2[0]), (p1[1] - p2[1])] * weight
weights.append(weight)
deltas.append(delta)
# add, normalize
index += pyvips.Image.sum(deltas) / pyvips.Image.sum(weights)
return image.mapim(index, interpolate=pyvips.Interpolate.new('bicubic'))
if __name__ == '__main__':
image = pyvips.Image.new_from_file(sys.argv[1])
matches = re.findall(r'(\d+),(\d+) (\d+),(\d+)', sys.argv[3])
couples = [((int(m[0]), int(m[1])), (int(m[2]), int(m[3])))
for m in matches]
image = shepards(image, couples)
image.write_to_file(sys.argv[2])
python-pyvips-3.1.1/examples/soak-test.py 0000775 0000000 0000000 00000000424 15222163673 0020501 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
pyvips.leak_set(True)
pyvips.cache_set_max(0)
for i in range(1000):
print(f"loop {i} ...")
im = pyvips.Image.new_from_file(sys.argv[1])
im = im.embed(100, 100, 3000, 3000, extend="mirror")
im.write_to_file("x.v")
python-pyvips-3.1.1/examples/split-animation.py 0000775 0000000 0000000 00000001040 15222163673 0021672 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
if len(sys.argv) != 3:
print(f"usage: {sys.argv[0]} output-directory animated-image")
sys.exit(1)
# load the animation, chop into pages
image = pyvips.Image.new_from_file(sys.argv[2], n=-1, access="sequential")
delay = image.get("delay")
print(f"delay array = {delay}")
pages = image.pagesplit()
print(f"writing frames to {sys.argv[1]}/ ...")
for page_number in range(len(pages)):
filename = f"{sys.argv[1]}/frame-{page_number:04}.tif"
pages[page_number].write_to_file(filename)
python-pyvips-3.1.1/examples/stdio.py 0000775 0000000 0000000 00000000402 15222163673 0017705 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
source = pyvips.Source.new_from_descriptor(sys.stdin.fileno())
image = pyvips.Image.new_from_source(source, "")
target = pyvips.Target.new_to_descriptor(sys.stdout.fileno())
image.write_to_target(target, ".jpg")
python-pyvips-3.1.1/examples/stream.py 0000775 0000000 0000000 00000001212 15222163673 0020056 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
import sys
import requests
import pyvips
URL = "https://cdn.filestackcontent.com/bnTGtQw5ShqMPpxH2tMw"
URLS = [URL] * int(sys.argv[1])
session = requests.Session()
image = pyvips.Image.black(1500, 1500)
for i, url in enumerate(URLS):
print(f"loading {url} ...")
stream = session.get(url, stream=True).raw
source = pyvips.SourceCustom()
source.on_read((lambda stream: stream.read)(stream))
tile = pyvips.Image.new_from_source(source, "", access="sequential")
image = image.composite2(tile, "over", x=50 * (i + 1), y=50 * (i + 1))
print("writing output.jpg ...")
image.write_to_file("output.jpg")
python-pyvips-3.1.1/examples/thumb-dir.py 0000775 0000000 0000000 00000001401 15222163673 0020456 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
"""
example pyvips code to run thumbnail on a dir full of images
https://libvips.github.io/pyvips/vimage.html?highlight=thumbnail#pyvips.Image.thumbnail
"""
import os
import multiprocessing
import sys
import pyvips
def thumbnail(directory, filename):
try:
name, extension = os.path.splitext(filename)
thumb = pyvips.Image.thumbnail(f"{directory}/{filename}", 128)
thumb.write_to_file(f"{directory}/tn_{name}.jpg")
except pyvips.Error:
# ignore failures due to eg. not an image
pass
def all_files(path):
for (root, dirs, files) in os.walk(path):
for file in files:
yield root, file
with multiprocessing.Pool() as pool:
pool.starmap(thumbnail, all_files(sys.argv[1]))
python-pyvips-3.1.1/examples/try1.py 0000775 0000000 0000000 00000000445 15222163673 0017471 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
# uncomment to see startup log for pyvips
# import logging
# logging.basicConfig(level=logging.DEBUG)
import pyvips
print('test Image')
image = pyvips.Image.new_from_file(sys.argv[1])
print('image =', image)
print('image.width =', image.width)
print('\n''')
python-pyvips-3.1.1/examples/try10.py 0000775 0000000 0000000 00000000367 15222163673 0017554 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
# import logging
# logging.basicConfig(level = logging.DEBUG)
import pyvips
a = pyvips.Image.black(100, 100)
a = a.draw_circle(128, 50, 50, 20)
b = a.hough_circle(scale=1, min_radius=15, max_radius=25)
b.write_to_file("x.v")
python-pyvips-3.1.1/examples/try11.py 0000775 0000000 0000000 00000000377 15222163673 0017556 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
# import logging
# logging.basicConfig(level = logging.DEBUG)
a = pyvips.Image.new_from_file(sys.argv[1])
ipct = a.get("ipct-data")
print("ipct = ", ipct.get())
a.remove("ipct-data")
a.write_to_file("x.jpg")
python-pyvips-3.1.1/examples/try12.py 0000775 0000000 0000000 00000001007 15222163673 0017546 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
im = pyvips.Image.new_from_file(sys.argv[1], access="sequential")
footer = pyvips.Image.black(im.width, 150)
left_text = pyvips.Image.text("left corner", dpi=300)
right_text = pyvips.Image.text("right corner", dpi=300)
footer = footer.insert(left_text, 50, 50)
footer = footer.insert(right_text, im.width - right_text.width - 50, 50)
footer = footer.ifthenelse(0, [255, 0, 0], blend=True)
im = im.insert(footer, 0, im.height, expand=True)
im.write_to_file(sys.argv[2])
python-pyvips-3.1.1/examples/try13.py 0000775 0000000 0000000 00000000134 15222163673 0017547 0 ustar 00root root 0000000 0000000 #!/usr/bin/python
# import pyvips
import logging
logging.basicConfig(level=logging.DEBUG)
python-pyvips-3.1.1/examples/try14.py 0000775 0000000 0000000 00000000446 15222163673 0017556 0 ustar 00root root 0000000 0000000 #!/usr/bin/python
# import logging
# logging.basicConfig(level = logging.DEBUG)
import pyvips
a = pyvips.Image.black(100, 100)
b = a.bandjoin(2)
b.write_to_file("x.v")
txt = pyvips.Image.text("left corner", dpi=300)
c = txt.ifthenelse(2, [0, 255, 0], blend=True)
c.write_to_file("x2.v")
python-pyvips-3.1.1/examples/try16.py 0000775 0000000 0000000 00000000456 15222163673 0017561 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import logging
import sys
import pyvips
logging.basicConfig(level=logging.DEBUG)
# pyvips.cache_set_trace(True)
a = pyvips.Image.new_from_file(sys.argv[1])
x = a.erode([[128, 255, 128],
[255, 255, 255],
[128, 255, 128]])
x.write_to_file(sys.argv[2])
python-pyvips-3.1.1/examples/try17.py 0000775 0000000 0000000 00000000343 15222163673 0017555 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
# import logging
# logging.basicConfig(level = logging.DEBUG)
# pyvips.cache_set_trace(True)
a = pyvips.Image.new_from_file(sys.argv[1])
a = a[1:]
a.write_to_file(sys.argv[2])
python-pyvips-3.1.1/examples/try2.py 0000775 0000000 0000000 00000001034 15222163673 0017465 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import logging
import pyvips
logging.basicConfig(level=logging.DEBUG)
pyvips.cache_set_trace(True)
try:
a = pyvips.Image.new_from_file("/home/john/pics/babe.poop")
except pyvips.Error as e:
print(str(e))
a = pyvips.Image.new_from_file("/home/john/pics/babe.jpg")
b = pyvips.Image.new_from_file("/home/john/pics/k2.jpg")
print('a =', a)
print('b =', b)
out = pyvips.call("add", a, b)
print('out =', out)
out = a.add(b)
print('out =', out)
out = out.linear([1, 1, 1], [2, 2, 2])
out.write_to_file("x.v")
python-pyvips-3.1.1/examples/try3.py 0000775 0000000 0000000 00000000325 15222163673 0017470 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
# import logging
# logging.basicConfig(level = logging.DEBUG)
pyvips.cache_set_trace(True)
a = pyvips.Image.new_from_file(sys.argv[1])
print(a.max())
print(a.max())
python-pyvips-3.1.1/examples/try4.py 0000775 0000000 0000000 00000000612 15222163673 0017470 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
# import logging
# logging.basicConfig(level = logging.DEBUG)
a = pyvips.Image.new_from_file(sys.argv[1])
b = pyvips.Image.new_from_file(sys.argv[2])
c = a.join(b, pyvips.Direction.HORIZONTAL,
expand=True,
shim=100,
align=pyvips.Align.CENTRE,
background=[128, 255, 128])
c.write_to_file(sys.argv[3])
python-pyvips-3.1.1/examples/try5.py 0000775 0000000 0000000 00000002621 15222163673 0017473 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
# import logging
# logging.basicConfig(level = logging.DEBUG)
a = pyvips.Image.new_from_file(sys.argv[1])
def should_equal(test, a, b):
if abs(a - b) > 0.01:
print(f'{test}: seen {a:g} and {b:g}')
sys.exit(1)
def bandsplit(a):
return [a.extract_band(i) for i in range(0, a.bands)]
# test operator overloads
# addition
b = a + 12
should_equal('add constant', a.avg() + 12, b.avg())
b = a + [12, 0, 0]
x = map(lambda x: x.avg())
bandsplit(a)
y = map(lambda x: x.avg())
bandsplit(b)
x[0] += 12
should_equal('add multiband constant', sum(x), sum(y))
b = a + [12, 0, 0]
b = a + b
b = 12 + a
b = [12, 0, 0] + a
b = a - 12
b = a - [12, 0, 0]
b = a - b
b = 12 - a
b = [12, 0, 0] - a
b = a * 12
b = a * [12, 1, 1]
b = a * b
b = 12 * a
b = [12, 1, 1] * a
b = a / 12
b = a / [12, 1, 1]
b = 12 / a
b = [12, 1, 1] / a
b = a / b
b = a // 12
b = a // [12, 1, 1]
b = 12 // a
b = [12, 1, 1] // a
b = a // b
b = a % 12
b = a % [12, 1, 1]
b = a % b
b = a ** 12
b = a ** [12, 1, 1]
b = 12 ** a
b = [12, 1, 1] ** a
b = a ** b
b = a << 12
b = a << [12, 1, 1]
b = a << b
b = a >> 12
b = a >> [12, 1, 1]
b = a >> b
b = a & 12
b = a & [12, 1, 1]
b = 12 & a
b = [12, 1, 1] & a
b = a & b
b = a | 12
b = a | [12, 1, 1]
b = 12 | a
b = [12, 1, 1] | a
b = a | b
b = a ^ 12
b = a ^ [12, 1, 1]
b = 12 ^ a
b = [12, 1, 1] ^ a
b = a ^ b
b = -a
b = +a
b = abs(a)
b = ~a
python-pyvips-3.1.1/examples/try6.py 0000775 0000000 0000000 00000000341 15222163673 0017471 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
# import logging
# logging.basicConfig(level = logging.DEBUG)
a = pyvips.Image.new_from_file(sys.argv[1])
b = a.write_to_buffer(".jpg")
c = pyvips.Image.new_from_buffer(b, "")
python-pyvips-3.1.1/examples/try7.py 0000775 0000000 0000000 00000000426 15222163673 0017476 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
# import logging
# logging.basicConfig(level = logging.DEBUG)
a = pyvips.Image.new_from_file(sys.argv[1])
b = a.write_to_memory()
c = pyvips.Image.new_from_memory(b, a.width, a.height, a.bands, a.bandfmt)
c.write_to_file("x.v")
python-pyvips-3.1.1/examples/try8.py 0000775 0000000 0000000 00000000412 15222163673 0017472 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
# import logging
# logging.basicConfig(level = logging.DEBUG)
import pyvips
a = pyvips.Image.new_from_array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 8, 128)
print('scale =', a.get('scale'))
print('offset =', a.get('offset'))
a.write_to_file("x.v")
python-pyvips-3.1.1/examples/try9.py 0000775 0000000 0000000 00000000223 15222163673 0017473 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import logging
import pyvips
logging.basicConfig(level=logging.DEBUG)
a = pyvips.Image.black(100, 100)
a.write_to_file("x.v")
python-pyvips-3.1.1/examples/watermark.py 0000775 0000000 0000000 00000001661 15222163673 0020570 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
im = pyvips.Image.new_from_file(sys.argv[1], access="sequential")
text = pyvips.Image.text(f"{sys.argv[3]}",
width=500,
dpi=100,
align="centre",
rgba=True)
# scale the alpha down to make the text semi-transparent
text = (text * [1, 1, 1, 0.3]).cast("uchar")
text = text.rotate(45)
# tile to the size of the image page, then tile again to the full image size
text = text.embed(10, 10, text.width + 20, text.width + 20)
page_height = im.get_page_height()
text = text.replicate(1 + im.width / text.width, 1 + page_height / text.height)
text = text.crop(0, 0, im.width, page_height)
text = text.replicate(1, 1 + im.height / text.height)
text = text.crop(0, 0, im.width, im.height)
# composite the two layers
im = im.composite(text, "over")
im.write_to_file(sys.argv[2])
python-pyvips-3.1.1/examples/watermark_context.py 0000775 0000000 0000000 00000005356 15222163673 0022341 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
# watermark an image, but do it in a context-sensitive way, so we will write
# black if the area we are overlaying the text on is white, for example
# usage:
# ./watermark_context.py ~/pics/k2.jpg x.jpg "hello there!"
import sys
import pyvips
# zero-excluding average of an image ... return as an array, with the average
# for each band
def avgze(image):
# since we use histograms
if image.format != "uchar" and image.format != "ushort":
raise Exception("uchar and ushort images only")
# take the histogram, and set the count for 0 pixels to 0, removing them
histze = image.hist_find().insert(pyvips.Image.black(1, 1), 0, 0)
# number of non-zero pixels in each band
nnz = [histze[i].avg() * histze.width * histze.height
for i in range(histze.bands)]
# multiply by the identity function and we get the sum of non-zero
# pixels ... for 16-bit images, we need a larger identity
# function
totalze = histze * pyvips.Image.identity(ushort=histze.width > 256)
# find average value in each band
avgze = [totalze[i].avg() * histze.width * histze.height / nnz[i]
for i in range(totalze.bands)]
return avgze
# find an opposing colour ... we split the density range (0 .. mx) into three:
# values in the bottom third move to the top, values in the top third move to
# the bottom, and values in the middle also move to the bottom
def oppose(value, mx):
if value < mx / 3:
# bottom goes up
return mx / 3 - value + 2 * mx / 3
elif value < 2 * mx / 3:
# middle goes down
return 2 * mx / 3 - value
else:
# top goes down
return mx - value
im = pyvips.Image.new_from_file(sys.argv[1])
text = pyvips.Image.text(sys.argv[3], width=500, dpi=300, align="centre")
text = text.rotate(45)
# the position of the overlay in the image
left = 100
top = im.height - text.height - 100
# find the non-alpha image bands
if im.hasalpha():
no_alpha = im.extract_band(0, n=im.bands - 1)
else:
no_alpha = im
# the pixels we will render the overlay on top of
bg = no_alpha.crop(left, top, text.width, text.height)
# mask the background with the text, so all non-text areas become zero, and
# find the zero-excluding average
avg = avgze(text.ifthenelse(bg, 0))
# for each band, find the opposing value
mx = 255 if im.format == "uchar" else 65535
text_colour = [oppose(avg[i], mx) for i in range(len(avg))]
# make an overlay ... we put solid colour into the image and set a faded
# version of the text mask as the alpha
overlay = bg.new_from_image(text_colour)
overlay = overlay.bandjoin((text * 0.5).cast("uchar"))
# and composite that on to the original image
im = im.composite(overlay, "over", x=left, y=top)
im.write_to_file(sys.argv[2])
python-pyvips-3.1.1/examples/watermark_image.py 0000775 0000000 0000000 00000001050 15222163673 0021722 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import sys
import pyvips
image = pyvips.Image.new_from_file(sys.argv[1], access="sequential")
watermark = pyvips.Image.new_from_file(sys.argv[3], access="sequential")
# downsize the image by 50%
image = image.resize(0.5)
# set the watermark alpha to 20% (multiply A of RGBA by 0.2).
watermark *= [1, 1, 1, 0.2]
# overlay the watermark at the bottom left, with a 100 pixel margin
image = image.composite(watermark, "over",
x=100, y=image.height - watermark.height - 100)
image.write_to_file(sys.argv[2])
python-pyvips-3.1.1/pyproject.toml 0000664 0000000 0000000 00000004753 15222163673 0017321 0 ustar 00root root 0000000 0000000 [build-system]
requires = [
# First version of setuptools to support pyproject.toml configuration
"setuptools>=61.0.0",
# Must be kept in sync with `project.dependencies`
"cffi>=1.0.0",
"pkgconfig>=1.5",
]
build-backend = "setuptools.build_meta"
[project]
name = "pyvips"
authors = [
{name = "John Cupitt", email = "jcupitt@gmail.com"},
]
description = "binding for the libvips image processing library"
readme = "README.rst"
keywords = [
"image processing",
]
license = {text = "MIT"}
requires-python = ">=3.7"
classifiers = [
"Development Status :: 5 - Production/Stable",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"Topic :: Multimedia :: Graphics",
"Topic :: Multimedia :: Graphics :: Graphics Conversion",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
]
dependencies = [
# Must be kept in sync with `build-system.requires`
"cffi>=1.0.0",
]
dynamic = [
"version",
]
[project.urls]
changelog = "https://github.com/libvips/pyvips/blob/master/CHANGELOG.rst"
documentation = "https://libvips.github.io/pyvips/"
funding = "https://opencollective.com/libvips"
homepage = "https://github.com/libvips/pyvips"
issues = "https://github.com/libvips/pyvips/issues"
source = "https://github.com/libvips/pyvips"
[tool.setuptools]
# We try to compile as part of install, so we can't run in a ZIP
zip-safe = false
include-package-data = false
[tool.setuptools.dynamic]
version = {attr = "pyvips.version.__version__"}
[tool.setuptools.packages.find]
exclude = [
"doc*",
"examples*",
"tests*",
]
[project.optional-dependencies]
binary = ["pyvips-binary"]
# All the following are used for our own testing
tox = ["tox"]
test = [
"pytest",
"pyperf",
]
sdist = ["build"]
doc = [
"sphinx",
"sphinx_rtd_theme",
]
[tool.pytest.ini_options]
norecursedirs = ["tests/helpers"]
python-pyvips-3.1.1/pyvips/ 0000775 0000000 0000000 00000000000 15222163673 0015726 5 ustar 00root root 0000000 0000000 python-pyvips-3.1.1/pyvips/__init__.py 0000664 0000000 0000000 00000014242 15222163673 0020042 0 ustar 00root root 0000000 0000000 # flake8: noqa
import logging
import os
import sys
import atexit
logger = logging.getLogger(__name__)
# user code can override this null handler
logger.addHandler(logging.NullHandler())
def library_name(name, abi_number, lib_prefix='lib'):
is_windows = os.name == 'nt'
is_mac = sys.platform == 'darwin'
if is_windows:
return f'{lib_prefix}{name}-{abi_number}.dll'
elif is_mac:
return f'{lib_prefix}{name}.{abi_number}.dylib'
else:
return f'{lib_prefix}{name}.so.{abi_number}'
# pull in our module version number
from .version import __version__
# try to import our binary interface ... if that works, we are in API mode
API_mode = False
try:
import _libvips
logger.debug('Loaded binary module _libvips')
ffi = _libvips.ffi
vips_lib = _libvips.lib
glib_lib = _libvips.lib
gobject_lib = _libvips.lib
# now check that the binary wrapper is for the same version of libvips that
# we find ourseleves linking to at runtime ... if it isn't, we must fall
# back to ABI mode
lib_major = vips_lib.vips_version(0)
lib_minor = vips_lib.vips_version(1)
wrap_major = vips_lib.VIPS_MAJOR_VERSION
wrap_minor = vips_lib.VIPS_MINOR_VERSION
logger.debug(f'Module generated for libvips {wrap_major}.{wrap_minor}')
logger.debug(f'Linked to libvips {lib_major}.{lib_minor}')
if wrap_major != lib_major or wrap_minor != lib_minor:
raise Exception('bad wrapper version')
API_mode = True
except Exception as e:
logger.debug(f'Binary module load failed: {e}')
logger.debug('Falling back to ABI mode')
from cffi import FFI
ffi = FFI()
vips_lib = ffi.dlopen(library_name('vips', 42))
glib_lib = vips_lib
gobject_lib = vips_lib
logger.debug('Loaded lib %s', vips_lib)
ffi.cdef('''
int vips_init (const char* argv0);
int vips_version (int flag);
''')
if vips_lib.vips_init(sys.argv[0].encode()) != 0:
raise Exception('unable to init libvips')
logger.debug('Inited libvips')
if not API_mode:
from .vdecls import cdefs
major = vips_lib.vips_version(0)
minor = vips_lib.vips_version(1)
micro = vips_lib.vips_version(2)
features = {
'major': major,
'minor': minor,
'micro': micro,
'api': False,
}
ffi.cdef(cdefs(features))
# We can sometimes get dependent libraries from libvips -- either the platform
# will open dependencies for us automatically, or the libvips binary has been
# built to includes all main dependencies (common on windows, can happen
# elsewhere).
#
# We must get glib functions from libvips if we can, since it will be the
# one that libvips itself is using, and they will share runtime types.
try:
is_unified = gobject_lib.g_type_from_name(b'VipsImage') != 0
except Exception:
is_unified = False
if not is_unified:
try:
glib_lib = ffi.dlopen(library_name('glib-2.0', 0))
gobject_lib = ffi.dlopen(library_name('gobject-2.0', 0))
except Exception:
# on windows glib maybe named glib-2.0-0.dll instead of libglib-2.0-0.dll
glib_lib = ffi.dlopen(library_name('glib-2.0', 0, lib_prefix=''))
gobject_lib = ffi.dlopen(library_name('gobject-2.0', 0, lib_prefix=''))
logger.debug('Loaded lib %s', glib_lib)
logger.debug('Loaded lib %s', gobject_lib)
from .error import *
# redirect all vips warnings to logging
class GLogLevelFlags(object):
# log flags
FLAG_RECURSION = 1 << 0
FLAG_FATAL = 1 << 1
# GLib log levels
LEVEL_ERROR = 1 << 2 # always fatal
LEVEL_CRITICAL = 1 << 3
LEVEL_WARNING = 1 << 4
LEVEL_MESSAGE = 1 << 5
LEVEL_INFO = 1 << 6
LEVEL_DEBUG = 1 << 7
LEVEL_TO_LOGGER = {
LEVEL_DEBUG: 10,
LEVEL_INFO: 20,
LEVEL_MESSAGE: 20,
LEVEL_WARNING: 30,
LEVEL_ERROR: 40,
LEVEL_CRITICAL: 50,
}
if API_mode:
@ffi.def_extern()
def _log_handler_callback(domain, level, message, user_data):
logger.log(GLogLevelFlags.LEVEL_TO_LOGGER[level],
f'{_to_string(domain)}: {_to_string(message)}')
# keep a ref to the cb to stop it being GCd
_log_handler_cb = glib_lib._log_handler_callback
else:
def _log_handler_callback(domain, level, message, user_data):
logger.log(GLogLevelFlags.LEVEL_TO_LOGGER[level],
f'{_to_string(domain)}: {_to_string(message)}')
# keep a ref to the cb to stop it being GCd
_log_handler_cb = ffi.callback('GLogFunc', _log_handler_callback)
_log_handler_id = glib_lib.g_log_set_handler(_to_bytes('VIPS'),
GLogLevelFlags.LEVEL_DEBUG |
GLogLevelFlags.LEVEL_INFO |
GLogLevelFlags.LEVEL_MESSAGE |
GLogLevelFlags.LEVEL_WARNING |
GLogLevelFlags.LEVEL_CRITICAL |
GLogLevelFlags.LEVEL_ERROR |
GLogLevelFlags.FLAG_FATAL |
GLogLevelFlags.FLAG_RECURSION,
_log_handler_cb, ffi.NULL)
# ffi doesn't like us looking up methods during shutdown: make a note of the
# remove handler here
_remove_handler = glib_lib.g_log_remove_handler
# we must remove the handler on exit or libvips may try to run the callback
# during shutdown
def _remove_log_handler():
global _log_handler_id
global _remove_handler
if _log_handler_id:
_remove_handler(_to_bytes('VIPS'), _log_handler_id)
_log_handler_id = None
atexit.register(_remove_log_handler)
from .enums import *
from .base import *
from .gobject import *
from .gvalue import *
from .vobject import *
from .vinterpolate import *
from .vconnection import *
from .vsource import *
from .vsourcecustom import *
from .vtarget import *
from .vtargetcustom import *
from .voperation import *
from .vimage import *
from .vregion import *
__all__ = ['API_mode']
python-pyvips-3.1.1/pyvips/base.py 0000664 0000000 0000000 00000007663 15222163673 0017226 0 ustar 00root root 0000000 0000000 # basic defs and link to ffi
from pyvips import ffi, glib_lib, vips_lib, gobject_lib, \
_to_string, _to_bytes, Error
def leak_set(leak):
"""Enable or disable libvips leak checking.
With this enabled, libvips will check for object and area leaks on exit.
Enabling this option will make libvips run slightly more slowly.
"""
return vips_lib.vips_leak_set(leak)
def shutdown():
"""Shut libvips down."""
vips_lib.vips_shutdown()
def version(flag):
"""Get the major, minor or micro version number of the libvips library.
Args:
flag (int): Pass flag 0 to get the major version number, flag 1 to
get minor, flag 2 to get micro.
Returns:
The version number,
Raises:
:class:`.Error`
"""
value = vips_lib.vips_version(flag)
if value < 0:
raise Error('unable to get library version')
return value
def get_suffixes():
"""Get a list of all the filename suffixes supported by libvips.
Returns:
[string]
"""
names = []
if at_least_libvips(8, 8):
array = vips_lib.vips_foreign_get_suffixes()
i = 0
while array[i] != ffi.NULL:
name = _to_string(array[i])
if name not in names:
names.append(name)
glib_lib.g_free(array[i])
i += 1
glib_lib.g_free(array)
return names
# we need to define this before we import the declarations: they need to know
# which bits to make
def at_least_libvips(x, y):
"""Is this at least libvips x.y?"""
major = version(0)
minor = version(1)
return major > x or (major == x and minor >= y)
def type_find(basename, nickname):
"""Get the GType for a name.
Looks up the GType for a nickname. Types below basename in the type
hierarchy are searched.
"""
return vips_lib.vips_type_find(_to_bytes(basename), _to_bytes(nickname))
def type_name(gtype):
"""Return the name for a GType."""
return _to_string(gobject_lib.g_type_name(gtype))
def nickname_find(gtype):
"""Return the nickname for a GType."""
return _to_string(vips_lib.vips_nickname_find(gtype))
def type_from_name(name):
"""Return the GType for a name."""
return gobject_lib.g_type_from_name(_to_bytes(name))
def type_map(gtype, fn):
"""Map fn over all child types of gtype."""
cb = ffi.callback('VipsTypeMap2Fn', fn)
return vips_lib.vips_type_map(gtype, cb, ffi.NULL, ffi.NULL)
def values_for_enum(gtype):
"""Deprecated."""
g_type_class = gobject_lib.g_type_class_ref(gtype)
g_enum_class = ffi.cast('GEnumClass *', g_type_class)
return [_to_string(g_enum_class.values[i].value_nick)
for i in range(g_enum_class.n_values)]
def values_for_flag(gtype):
"""Deprecated."""
g_type_class = gobject_lib.g_type_class_ref(gtype)
g_flags_class = ffi.cast('GFlagsClass *', g_type_class)
return [_to_string(g_flags_class.values[i].value_nick)
for i in range(g_flags_class.n_values)]
def enum_dict(gtype):
"""Get name -> value dict for a enum (gtype)."""
g_type_class = gobject_lib.g_type_class_ref(gtype)
g_enum_class = ffi.cast('GEnumClass *', g_type_class)
return {_to_string(g_enum_class.values[i].value_nick):
g_enum_class.values[i].value
for i in range(g_enum_class.n_values)}
def flags_dict(gtype):
"""Get name -> value dict for a flags (gtype)."""
g_type_class = gobject_lib.g_type_class_ref(gtype)
g_flags_class = ffi.cast('GFlagsClass *', g_type_class)
return {_to_string(g_flags_class.values[i].value_nick):
g_flags_class.values[i].value
for i in range(g_flags_class.n_values)}
__all__ = [
'leak_set',
'shutdown',
'version',
'at_least_libvips',
'type_find',
'nickname_find',
'get_suffixes',
'type_name',
'type_map',
'type_from_name',
'values_for_enum',
'values_for_flag',
'enum_dict',
'flags_dict'
]
python-pyvips-3.1.1/pyvips/enums.py 0000664 0000000 0000000 00000064130 15222163673 0017433 0 ustar 00root root 0000000 0000000 # libvips enums -- this file is generated automatically
# flake8: noqa: E501
class BandFormat(object):
"""BandFormat.
The format used for each band element.
Each corresponds to a native C type for the current machine. For example,
:class:`.enums.BandFormat.USHORT` is `unsigned short`.
Attributes:
NOTSET (str): invalid setting
UCHAR (str): unsigned char format
CHAR (str): char format
USHORT (str): unsigned short format
SHORT (str): short format
UINT (str): unsigned int format
INT (str): int format
FLOAT (str): float format
COMPLEX (str): complex (two floats) format
DOUBLE (str): double float format
DPCOMPLEX (str): double complex (two double) format
"""
NOTSET = 'notset'
UCHAR = 'uchar'
CHAR = 'char'
USHORT = 'ushort'
SHORT = 'short'
UINT = 'uint'
INT = 'int'
FLOAT = 'float'
COMPLEX = 'complex'
DOUBLE = 'double'
DPCOMPLEX = 'dpcomplex'
class BlendMode(object):
"""BlendMode.
The various Porter-Duff and PDF blend modes. See :meth:`.Image.composite`,
for example.
The Cairo docs have [a nice explanation of all the blend
modes](https://www.cairographics.org/operators).
The non-separable modes are not implemented.
Attributes:
CLEAR (str): where the second object is drawn, the first is removed
SOURCE (str): the second object is drawn as if nothing were below
OVER (str): the image shows what you would expect if you held two semi-transparent slides on top of each other
IN (str): the first object is removed completely, the second is only drawn where the first was
OUT (str): the second is drawn only where the first isn't
ATOP (str): this leaves the first object mostly intact, but mixes both objects in the overlapping area
DEST (str): leaves the first object untouched, the second is discarded completely
DEST_OVER (str): like OVER, but swaps the arguments
DEST_IN (str): like IN, but swaps the arguments
DEST_OUT (str): like OUT, but swaps the arguments
DEST_ATOP (str): like ATOP, but swaps the arguments
XOR (str): something like a difference operator
ADD (str): a bit like adding the two images
SATURATE (str): a bit like the darker of the two
MULTIPLY (str): at least as dark as the darker of the two inputs
SCREEN (str): at least as light as the lighter of the inputs
OVERLAY (str): multiplies or screens colors, depending on the lightness
DARKEN (str): the darker of each component
LIGHTEN (str): the lighter of each component
COLOUR_DODGE (str): brighten first by a factor second
COLOUR_BURN (str): darken first by a factor of second
HARD_LIGHT (str): multiply or screen, depending on lightness
SOFT_LIGHT (str): darken or lighten, depending on lightness
DIFFERENCE (str): difference of the two
EXCLUSION (str): somewhat like DIFFERENCE, but lower-contrast
"""
CLEAR = 'clear'
SOURCE = 'source'
OVER = 'over'
IN = 'in'
OUT = 'out'
ATOP = 'atop'
DEST = 'dest'
DEST_OVER = 'dest-over'
DEST_IN = 'dest-in'
DEST_OUT = 'dest-out'
DEST_ATOP = 'dest-atop'
XOR = 'xor'
ADD = 'add'
SATURATE = 'saturate'
MULTIPLY = 'multiply'
SCREEN = 'screen'
OVERLAY = 'overlay'
DARKEN = 'darken'
LIGHTEN = 'lighten'
COLOUR_DODGE = 'colour-dodge'
COLOUR_BURN = 'colour-burn'
HARD_LIGHT = 'hard-light'
SOFT_LIGHT = 'soft-light'
DIFFERENCE = 'difference'
EXCLUSION = 'exclusion'
class Coding(object):
"""Coding.
How pixels are coded.
Normally, pixels are uncoded and can be manipulated as you would expect.
However some file formats code pixels for compression, and sometimes it's
useful to be able to manipulate images in the coded format.
The gaps in the numbering are historical and must be maintained. Allocate
new numbers from the end.
Attributes:
NONE (str): pixels are not coded
LABQ (str): pixels encode 3 float CIELAB values as 4 uchar
RAD (str): pixels encode 3 float RGB as 4 uchar (Radiance coding)
"""
ERROR = 'error'
NONE = 'none'
LABQ = 'labq'
RAD = 'rad'
class Interpretation(object):
"""Interpretation.
How the values in an image should be interpreted. For example, a
three-band float image of type :class:`.enums.Interpretation.LAB` should have its
pixels interpreted as coordinates in CIE Lab space.
RGB and sRGB are treated in the same way. Use the colourspace functions if
you want some other behaviour.
The gaps in numbering are historical and must be maintained. Allocate
new numbers from the end.
Attributes:
MULTIBAND (str): generic many-band image
B_W (str): some kind of single-band image
HISTOGRAM (str): a 1D image, eg. histogram or lookup table
XYZ (str): the first three bands are CIE XYZ
LAB (str): pixels are in CIE Lab space
CMYK (str): the first four bands are in CMYK space
LABQ (str): implies :class:`.enums.Coding.LABQ`
RGB (str): generic RGB space
CMC (str): a uniform colourspace based on CMC(1:1)
LCH (str): pixels are in CIE LCh space
LABS (str): CIE LAB coded as three signed 16-bit values
SRGB (str): pixels are sRGB
YXY (str): pixels are CIE Yxy
FOURIER (str): image is in fourier space
RGB16 (str): generic 16-bit RGB
GREY16 (str): generic 16-bit mono
MATRIX (str): a matrix
SCRGB (str): pixels are scRGB
HSV (str): pixels are HSV
OKLAB (str): pixels are in Oklab colourspace
OKLCH (str): pixels are in Oklch colourspace
"""
ERROR = 'error'
MULTIBAND = 'multiband'
B_W = 'b-w'
HISTOGRAM = 'histogram'
XYZ = 'xyz'
LAB = 'lab'
CMYK = 'cmyk'
LABQ = 'labq'
RGB = 'rgb'
CMC = 'cmc'
LCH = 'lch'
LABS = 'labs'
SRGB = 'srgb'
YXY = 'yxy'
FOURIER = 'fourier'
RGB16 = 'rgb16'
GREY16 = 'grey16'
MATRIX = 'matrix'
SCRGB = 'scrgb'
HSV = 'hsv'
OKLAB = 'oklab'
OKLCH = 'oklch'
class OperationRelational(object):
"""OperationRelational.
See also: :meth:`.Image.relational`.
Attributes:
EQUAL (str): `==`
NOTEQ (str): `!=`
LESS (str): `<`
LESSEQ (str): `<=`
MORE (str): `>`
MOREEQ (str): `>=`
"""
EQUAL = 'equal'
NOTEQ = 'noteq'
LESS = 'less'
LESSEQ = 'lesseq'
MORE = 'more'
MOREEQ = 'moreeq'
class OperationBoolean(object):
"""OperationBoolean.
See also: :meth:`.Image.boolean`.
Attributes:
AND (str): `&`
OR (str): `|`
EOR (str): `^`
LSHIFT (str): `>>`
RSHIFT (str): `<<`
"""
AND = 'and'
OR = 'or'
EOR = 'eor'
LSHIFT = 'lshift'
RSHIFT = 'rshift'
class OperationMath2(object):
"""OperationMath2.
See also: :meth:`.Image.math`.
Attributes:
POW (str): `pow(left, right)`
WOP (str): `pow(right, left)`
ATAN2 (str): `atan2(left, right)`
"""
POW = 'pow'
WOP = 'wop'
ATAN2 = 'atan2'
class OperationComplex2(object):
"""OperationComplex2.
See also: :meth:`.Image.complex2`.
Attributes:
CROSS_PHASE (str): convert to polar coordinates
"""
CROSS_PHASE = 'cross-phase'
class OperationMath(object):
"""OperationMath.
See also: :meth:`.Image.math`.
Attributes:
SIN (str): `sin()`, angles in degrees
COS (str): `cos()`, angles in degrees
TAN (str): `tan()`, angles in degrees
ASIN (str): `asin()`, angles in degrees
ACOS (str): `acos()`, angles in degrees
ATAN (str): `atan()`, angles in degrees
LOG (str): log base e
LOG10 (str): log base 10
EXP (str): e to the something
EXP10 (str): 10 to the something
SINH (str): `sinh()`, angles in radians
COSH (str): `cosh()`, angles in radians
TANH (str): `tanh()`, angles in radians
ASINH (str): `asinh()`, angles in radians
ACOSH (str): `acosh()`, angles in radians
ATANH (str): `atanh()`, angles in radians
"""
SIN = 'sin'
COS = 'cos'
TAN = 'tan'
ASIN = 'asin'
ACOS = 'acos'
ATAN = 'atan'
LOG = 'log'
LOG10 = 'log10'
EXP = 'exp'
EXP10 = 'exp10'
SINH = 'sinh'
COSH = 'cosh'
TANH = 'tanh'
ASINH = 'asinh'
ACOSH = 'acosh'
ATANH = 'atanh'
class OperationRound(object):
"""OperationRound.
See also: :meth:`.Image.round`.
Attributes:
RINT (str): round to nearest
CEIL (str): the smallest integral value not less than
FLOOR (str): largest integral value not greater than
"""
RINT = 'rint'
CEIL = 'ceil'
FLOOR = 'floor'
class OperationComplex(object):
"""OperationComplex.
See also: :meth:`.Image.complex`.
Attributes:
POLAR (str): convert to polar coordinates
RECT (str): convert to rectangular coordinates
CONJ (str): complex conjugate
"""
POLAR = 'polar'
RECT = 'rect'
CONJ = 'conj'
class OperationComplexget(object):
"""OperationComplexget.
See also: :meth:`.Image.complexget`.
Attributes:
REAL (str): get real component
IMAG (str): get imaginary component
"""
REAL = 'real'
IMAG = 'imag'
class Combine(object):
"""Combine.
How to combine values. See :meth:`.Image.compass`, for example.
Attributes:
MAX (str): take the maximum of the possible values
SUM (str): sum all the values
MIN (str): take the minimum value
"""
MAX = 'max'
SUM = 'sum'
MIN = 'min'
class Access(object):
"""Access.
The type of access an operation has to supply. See :meth:`.Image.tilecache`
and :class:`.Foreign`.
:class:`.enums.Access.RANDOM` means requests can come in any order.
:class:`.enums.Access.SEQUENTIAL` means requests will be top-to-bottom, but with some
amount of buffering behind the read point for small non-local accesses.
Attributes:
RANDOM (str): can read anywhere
SEQUENTIAL (str): top-to-bottom reading only, but with a small buffer
SEQUENTIAL_UNBUFFERED (str): deprecated, use :class:`.enums.Access.SEQUENTIAL` instead
"""
RANDOM = 'random'
SEQUENTIAL = 'sequential'
SEQUENTIAL_UNBUFFERED = 'sequential-unbuffered'
class Extend(object):
"""Extend.
See :meth:`.Image.embed`, :meth:`.Image.conv`, :meth:`.Image.affine` and so on.
When the edges of an image are extended, you can specify
how you want the extension done.
:class:`.enums.Extend.BLACK` -- new pixels are black, ie. all bits are zero.
:class:`.enums.Extend.COPY` -- each new pixel takes the value of the nearest edge
pixel
:class:`.enums.Extend.REPEAT` -- the image is tiled to fill the new area
:class:`.enums.Extend.MIRROR` -- the image is reflected and tiled to reduce hash
edges
:class:`.enums.Extend.WHITE` -- new pixels are white, ie. all bits are set
:class:`.enums.Extend.BACKGROUND` -- colour set from the @background property
We have to specify the exact value of each enum member since we have to
keep these frozen for back compat with vips7.
::: seealso
:meth:`.Image.embed`.
Attributes:
BLACK (str): extend with black (all 0) pixels
COPY (str): copy the image edges
REPEAT (str): repeat the whole image
MIRROR (str): mirror the whole image
WHITE (str): extend with white (all bits set) pixels
BACKGROUND (str): extend with colour from the @background property
"""
BLACK = 'black'
COPY = 'copy'
REPEAT = 'repeat'
MIRROR = 'mirror'
WHITE = 'white'
BACKGROUND = 'background'
class CompassDirection(object):
"""CompassDirection.
A direction on a compass. Used for :meth:`.Image.gravity`, for example.
Attributes:
CENTRE (str): centre
NORTH (str): north
EAST (str): east
SOUTH (str): south
WEST (str): west
NORTH_EAST (str): north-east
SOUTH_EAST (str): south-east
SOUTH_WEST (str): south-west
NORTH_WEST (str): north-west
"""
CENTRE = 'centre'
NORTH = 'north'
EAST = 'east'
SOUTH = 'south'
WEST = 'west'
NORTH_EAST = 'north-east'
SOUTH_EAST = 'south-east'
SOUTH_WEST = 'south-west'
NORTH_WEST = 'north-west'
class Direction(object):
"""Direction.
See :meth:`.Image.flip`, :meth:`.Image.join` and so on.
Operations like :meth:`.Image.flip` need to be told whether to flip left-right or
top-bottom.
::: seealso
:meth:`.Image.flip`, :meth:`.Image.join`.
Attributes:
HORIZONTAL (str): left-right
VERTICAL (str): top-bottom
"""
HORIZONTAL = 'horizontal'
VERTICAL = 'vertical'
class Align(object):
"""Align.
See :meth:`.Image.join` and so on.
Operations like :meth:`.Image.join` need to be told whether to align images on the
low or high coordinate edge, or centre.
::: seealso
:meth:`.Image.join`.
Attributes:
LOW (str): align low coordinate edge
CENTRE (str): align centre
HIGH (str): align high coordinate edge
"""
LOW = 'low'
CENTRE = 'centre'
HIGH = 'high'
class Interesting(object):
"""Interesting.
Pick the algorithm vips uses to decide image "interestingness". This is used
by :meth:`.Image.smartcrop`, for example, to decide what parts of the image to
keep.
:class:`.enums.Interesting.NONE` and :class:`.enums.Interesting.LOW` mean the same -- the
crop is positioned at the top or left. :class:`.enums.Interesting.HIGH` positions at
the bottom or right.
::: seealso
:meth:`.Image.smartcrop`.
Attributes:
NONE (str): do nothing
CENTRE (str): just take the centre
ENTROPY (str): use an entropy measure
ATTENTION (str): look for features likely to draw human attention
LOW (str): position the crop towards the low coordinate
HIGH (str): position the crop towards the high coordinate
ALL (str): everything is interesting
"""
NONE = 'none'
CENTRE = 'centre'
ENTROPY = 'entropy'
ATTENTION = 'attention'
LOW = 'low'
HIGH = 'high'
ALL = 'all'
class Angle(object):
"""Angle.
See :meth:`.Image.rot` and so on.
Fixed rotate angles.
::: seealso
:meth:`.Image.rot`.
Attributes:
D0 (str): no rotate
D90 (str): 90 degrees clockwise
D180 (str): 180 degree rotate
D270 (str): 90 degrees anti-clockwise
"""
D0 = 'd0'
D90 = 'd90'
D180 = 'd180'
D270 = 'd270'
class Angle45(object):
"""Angle45.
See :meth:`.Image.rot45` and so on.
Fixed rotate angles.
::: seealso
:meth:`.Image.rot45`.
Attributes:
D0 (str): no rotate
D45 (str): 45 degrees clockwise
D90 (str): 90 degrees clockwise
D135 (str): 135 degrees clockwise
D180 (str): 180 degrees
D225 (str): 135 degrees anti-clockwise
D270 (str): 90 degrees anti-clockwise
D315 (str): 45 degrees anti-clockwise
"""
D0 = 'd0'
D45 = 'd45'
D90 = 'd90'
D135 = 'd135'
D180 = 'd180'
D225 = 'd225'
D270 = 'd270'
D315 = 'd315'
class Precision(object):
"""Precision.
How accurate an operation should be.
Attributes:
INTEGER (str): int everywhere
FLOAT (str): float everywhere
APPROXIMATE (str): approximate integer output
"""
INTEGER = 'integer'
FLOAT = 'float'
APPROXIMATE = 'approximate'
class TextWrap(object):
"""TextWrap.
Sets the word wrapping style for :meth:`.Image.text` when used with a maximum
width.
::: seealso
:meth:`.Image.text`.
Attributes:
WORD (str): wrap at word boundaries
CHAR (str): wrap at character boundaries
WORD_CHAR (str): wrap at word boundaries, but fall back to character boundaries if there is not enough space for a full word
NONE (str): no wrapping
"""
WORD = 'word'
CHAR = 'char'
WORD_CHAR = 'word-char'
NONE = 'none'
class SdfShape(object):
"""SdfShape.
The SDF to generate,
::: seealso
:meth:`.Image.sdf`.
Attributes:
CIRCLE (str): a circle at @a, radius @r
BOX (str): a box from @a to @b
ROUNDED_BOX (str): a box with rounded @corners from @a to @b
LINE (str): a line from @a to @b
"""
CIRCLE = 'circle'
BOX = 'box'
ROUNDED_BOX = 'rounded-box'
LINE = 'line'
class FailOn(object):
"""FailOn.
How sensitive loaders are to errors, from never stop (very insensitive), to
stop on the smallest warning (very sensitive).
Each one implies the ones before it, so :class:`.enums.FailOn.ERROR` implies
:class:`.enums.FailOn.TRUNCATED`.
Attributes:
NONE (str): never stop
TRUNCATED (str): stop on image truncated, nothing else
ERROR (str): stop on serious error or truncation
WARNING (str): stop on anything, even warnings
"""
NONE = 'none'
TRUNCATED = 'truncated'
ERROR = 'error'
WARNING = 'warning'
class ForeignPdfPageBox(object):
"""ForeignPdfPageBox.
Each page of a PDF document can contain multiple page boxes,
also known as boundary boxes or print marks.
Each page box defines a region of the complete page that
should be rendered. The default region is the crop box.
Attributes:
MEDIA (str): media box
CROP (str): crop box
TRIM (str): trim box
BLEED (str): bleed box
ART (str): art box
"""
MEDIA = 'media'
CROP = 'crop'
TRIM = 'trim'
BLEED = 'bleed'
ART = 'art'
class ForeignPpmFormat(object):
"""ForeignPpmFormat.
The netpbm file format to save as.
:class:`.enums.ForeignPpmFormat.PBM` images are single bit.
:class:`.enums.ForeignPpmFormat.PGM` images are 8, 16, or 32-bits, one band.
:class:`.enums.ForeignPpmFormat.PPM` images are 8, 16, or 32-bits, three bands.
:class:`.enums.ForeignPpmFormat.PFM` images are 32-bit float pixels.
:class:`.enums.ForeignPpmFormat.PNM` images are anymap images -- the image format
is used to pick the saver.
Attributes:
PBM (str): portable bitmap
PGM (str): portable greymap
PPM (str): portable pixmap
PFM (str): portable float map
PNM (str): portable anymap
"""
PBM = 'pbm'
PGM = 'pgm'
PPM = 'ppm'
PFM = 'pfm'
PNM = 'pnm'
class ForeignSubsample(object):
"""ForeignSubsample.
Set subsampling mode.
Attributes:
AUTO (str): prevent subsampling when quality >= 90
ON (str): always perform subsampling
OFF (str): never perform subsampling
"""
AUTO = 'auto'
ON = 'on'
OFF = 'off'
class ForeignDzLayout(object):
"""ForeignDzLayout.
What directory layout and metadata standard to use.
Attributes:
DZ (str): use DeepZoom directory layout
ZOOMIFY (str): use Zoomify directory layout
GOOGLE (str): use Google maps directory layout
IIIF (str): use IIIF v2 directory layout
IIIF3 (str): use IIIF v3 directory layout
"""
DZ = 'dz'
ZOOMIFY = 'zoomify'
GOOGLE = 'google'
IIIF = 'iiif'
IIIF3 = 'iiif3'
class ForeignDzDepth(object):
"""ForeignDzDepth.
How many pyramid layers to create.
Attributes:
ONEPIXEL (str): create layers down to 1x1 pixel
ONETILE (str): create layers down to 1x1 tile
ONE (str): only create a single layer
"""
ONEPIXEL = 'onepixel'
ONETILE = 'onetile'
ONE = 'one'
class ForeignDzContainer(object):
"""ForeignDzContainer.
What container format to use.
Attributes:
FS (str): write tiles to the filesystem
ZIP (str): write tiles to a zip file
SZI (str): write to a szi file
"""
FS = 'fs'
ZIP = 'zip'
SZI = 'szi'
class RegionShrink(object):
"""RegionShrink.
How to calculate the output pixels when shrinking a 2x2 region.
Images with alpha (see :meth:`.Image.hasalpha`) always shrink with
:class:`.enums.RegionShrink.MEAN` and pixels scaled by alpha to avoid fringing.
Set the image interpretation to :class:`.enums.Interpretation.MULTIBAND` to
treat all bands equally.
Attributes:
MEAN (str): use the average
MEDIAN (str): use the median
MODE (str): use the mode
MAX (str): use the maximum
MIN (str): use the minimum
NEAREST (str): use the top-left pixel
"""
MEAN = 'mean'
MEDIAN = 'median'
MODE = 'mode'
MAX = 'max'
MIN = 'min'
NEAREST = 'nearest'
class ForeignWebpPreset(object):
"""ForeignWebpPreset.
Tune lossy encoder settings for different image types.
Attributes:
DEFAULT (str): default preset
PICTURE (str): digital picture, like portrait, inner shot
PHOTO (str): outdoor photograph, with natural lighting
DRAWING (str): hand or line drawing, with high-contrast details
ICON (str): small-sized colorful images
TEXT (str): text-like
"""
DEFAULT = 'default'
PICTURE = 'picture'
PHOTO = 'photo'
DRAWING = 'drawing'
ICON = 'icon'
TEXT = 'text'
class ForeignTiffCompression(object):
"""ForeignTiffCompression.
The compression types supported by the tiff writer.
Use @Q to set the jpeg compression level, default 75.
Use @predictor to set the lzw or deflate prediction, default horizontal.
Use @lossless to set WEBP lossless compression.
Use @level to set webp and zstd compression level.
Attributes:
NONE (str): no compression
JPEG (str): jpeg compression
DEFLATE (str): deflate (zip) compression
PACKBITS (str): packbits compression
CCITTFAX4 (str): fax4 compression
LZW (str): LZW compression
WEBP (str): WEBP compression
ZSTD (str): ZSTD compression
JP2K (str): JP2K compression
"""
NONE = 'none'
JPEG = 'jpeg'
DEFLATE = 'deflate'
PACKBITS = 'packbits'
CCITTFAX4 = 'ccittfax4'
LZW = 'lzw'
WEBP = 'webp'
ZSTD = 'zstd'
JP2K = 'jp2k'
class ForeignTiffPredictor(object):
"""ForeignTiffPredictor.
The predictor can help deflate and lzw compression. The values are fixed by
the tiff library.
Attributes:
NONE (str): no prediction
HORIZONTAL (str): horizontal differencing
FLOAT (str): float predictor
"""
NONE = 'none'
HORIZONTAL = 'horizontal'
FLOAT = 'float'
class ForeignTiffResunit(object):
"""ForeignTiffResunit.
Use inches or centimeters as the resolution unit for a tiff file.
Attributes:
CM (str): use centimeters
INCH (str): use inches
"""
CM = 'cm'
INCH = 'inch'
class ForeignHeifCompression(object):
"""ForeignHeifCompression.
The compression format to use inside a HEIF container.
This is assumed to use the same numbering as `heif_compression_format`.
Attributes:
HEVC (str): x265
AVC (str): x264
JPEG (str): jpeg
AV1 (str): aom
"""
HEVC = 'hevc'
AVC = 'avc'
JPEG = 'jpeg'
AV1 = 'av1'
class ForeignHeifEncoder(object):
"""ForeignHeifEncoder.
The selected encoder to use.
If libheif hasn't been compiled with the selected encoder,
we will fallback to the default encoder for the compression format.
Attributes:
AUTO (str): auto
AOM (str): aom
RAV1E (str): RAV1E
SVT (str): SVT-AV1
X265 (str): x265
"""
AUTO = 'auto'
AOM = 'aom'
RAV1E = 'rav1e'
SVT = 'svt'
X265 = 'x265'
class Size(object):
"""Size.
Controls whether an operation should upsize, downsize, both up and
downsize, or force a size.
::: seealso
:meth:`.Image.thumbnail`.
Attributes:
BOTH (str): size both up and down
UP (str): only upsize
DOWN (str): only downsize
FORCE (str): force size, that is, break aspect ratio
"""
BOTH = 'both'
UP = 'up'
DOWN = 'down'
FORCE = 'force'
class Intent(object):
"""Intent.
The rendering intent. :class:`.enums.Intent.ABSOLUTE` is best for
scientific work, :class:`.enums.Intent.RELATIVE` is usually best for
accurate communication with other imaging libraries.
Attributes:
PERCEPTUAL (str): perceptual rendering intent
RELATIVE (str): relative colorimetric rendering intent
SATURATION (str): saturation rendering intent
ABSOLUTE (str): absolute colorimetric rendering intent
AUTO (str): the rendering intent that the profile suggests
"""
PERCEPTUAL = 'perceptual'
RELATIVE = 'relative'
SATURATION = 'saturation'
ABSOLUTE = 'absolute'
AUTO = 'auto'
class Kernel(object):
"""Kernel.
The resampling kernels vips supports. See :meth:`.Image.reduce`, for example.
Attributes:
NEAREST (str): the nearest pixel to the point
LINEAR (str): convolve with a triangle filter
CUBIC (str): convolve with a cubic filter
MITCHELL (str): convolve with a Mitchell kernel
LANCZOS2 (str): convolve with a two-lobe Lanczos kernel
LANCZOS3 (str): convolve with a three-lobe Lanczos kernel
MKS2013 (str): convolve with Magic Kernel Sharp 2013
MKS2021 (str): convolve with Magic Kernel Sharp 2021
"""
NEAREST = 'nearest'
LINEAR = 'linear'
CUBIC = 'cubic'
MITCHELL = 'mitchell'
LANCZOS2 = 'lanczos2'
LANCZOS3 = 'lanczos3'
MKS2013 = 'mks2013'
MKS2021 = 'mks2021'
class PCS(object):
"""PCS.
Pick a Profile Connection Space for :meth:`.Image.icc_import` and
:meth:`.Image.icc_export`. LAB is usually best, XYZ can be more convenient in some
cases.
Attributes:
LAB (str): use CIELAB D65 as the Profile Connection Space
XYZ (str): use XYZ as the Profile Connection Space
"""
LAB = 'lab'
XYZ = 'xyz'
class OperationMorphology(object):
"""OperationMorphology.
More like hit-miss, really.
::: seealso
:meth:`.Image.morph`.
Attributes:
ERODE (str): true if all set
DILATE (str): true if one set
"""
ERODE = 'erode'
DILATE = 'dilate'
class CombineMode(object):
"""CombineMode.
See :meth:`.Image.draw_image` and so on.
Operations like :meth:`.Image.draw_image` need to be told how to combine images
from two sources.
::: seealso
:meth:`.Image.join`.
Attributes:
SET (str): set pixels to the new value
ADD (str): add pixels
"""
SET = 'set'
ADD = 'add'
class ForeignKeep(object):
"""ForeignKeep.
Which metadata to retain.
Attributes:
NONE (int): don't attach metadata
EXIF (int): keep Exif metadata
XMP (int): keep XMP metadata
IPTC (int): keep IPTC metadata
ICC (int): keep ICC metadata
OTHER (int): keep other metadata (e.g. PNG comments)
GAINMAP (int): keep the gainmap metadata
ALL (int): keep all metadata
"""
NONE = 0
EXIF = 1
XMP = 2
IPTC = 4
ICC = 8
OTHER = 16
GAINMAP = 32
ALL = 63
class ForeignPngFilter(object):
"""ForeignPngFilter.
http://www.w3.org/TR/PNG-Filters.html
The values mirror those of png.h in libpng.
Attributes:
NONE (int): no filtering
SUB (int): difference to the left
UP (int): difference up
AVG (int): average of left and up
PAETH (int): pick best neighbor predictor automatically
ALL (int): adaptive
"""
NONE = 8
SUB = 16
UP = 32
AVG = 64
PAETH = 128
ALL = 248
python-pyvips-3.1.1/pyvips/error.py 0000664 0000000 0000000 00000003366 15222163673 0017441 0 ustar 00root root 0000000 0000000 # errors from libvips
import logging
from pathlib import Path
from pyvips import ffi, vips_lib, glib_lib
logger = logging.getLogger(__name__)
def _to_bytes(x):
"""Convert to a byte string.
Convert a Python unicode string or a pathlib.Path to a utf-8-encoded
byte string. You must call this on strings you pass to libvips.
"""
if isinstance(x, (str, Path)):
# n.b. str also converts pathlib.Path objects
x = str(x).encode('utf-8')
return x
def _to_string(x):
"""Convert to a unicode string.
If x is a byte string, assume it is utf-8 and decode to a Python unicode
string. You must call this on text strings you get back from libvips.
"""
if x == ffi.NULL:
x = 'NULL'
else:
x = ffi.string(x)
if isinstance(x, bytes):
x = x.decode('utf-8')
return x
def _to_string_copy(x):
"""Convert to a unicode string, and auto-free.
As _to_string(), but also tag x as a pointer to a memory area that must
be freed with g_free().
"""
return _to_string(ffi.gc(x, glib_lib.g_free))
class Error(Exception):
"""An error from vips.
Attributes:
message (str): a high-level description of the error
detail (str): a string with some detailed diagnostics
"""
def __init__(self, message, detail=None):
self.message = message
if detail is None or detail == "":
detail = _to_string(vips_lib.vips_error_buffer())
vips_lib.vips_error_clear()
self.detail = detail
logger.debug('Error %s %s', self.message, self.detail)
def __str__(self):
return f'{self.message}\n {self.detail}'
__all__ = [
'_to_bytes',
'_to_string',
'_to_string_copy',
'Error'
]
python-pyvips-3.1.1/pyvips/gobject.py 0000664 0000000 0000000 00000015467 15222163673 0017732 0 ustar 00root root 0000000 0000000 import logging
import pyvips
from pyvips import ffi, gobject_lib, _to_bytes, Error, type_name, \
at_least_libvips
logger = logging.getLogger(__name__)
# the python marshalers for gobject signal handling
# - we keep a ref to each callback to stop them being GCd
# - I tried to make this less copy-paste, but failed -- check again
if pyvips.API_mode:
@ffi.def_extern()
def _marshal_image_progress(vi, pointer, handle):
gobject_lib.g_object_ref(vi)
image = pyvips.Image(vi)
callback = ffi.from_handle(handle)
progress = ffi.cast('VipsProgress*', pointer)
callback(image, progress)
_marshal_image_progress_cb = \
ffi.cast('GCallback', gobject_lib._marshal_image_progress)
else:
@ffi.callback('void(VipsImage*, void*, void*)')
def _marshal_image_progress(vi, pointer, handle):
gobject_lib.g_object_ref(vi)
image = pyvips.Image(vi)
callback = ffi.from_handle(handle)
progress = ffi.cast('VipsProgress*', pointer)
callback(image, progress)
_marshal_image_progress_cb = \
ffi.cast('GCallback', _marshal_image_progress)
_marshalers = {
'preeval': _marshal_image_progress_cb,
'eval': _marshal_image_progress_cb,
'posteval': _marshal_image_progress_cb,
}
if at_least_libvips(8, 9):
if pyvips.API_mode:
@ffi.def_extern()
def _marshal_read(gobject, pointer, length, handle):
buf = ffi.buffer(pointer, length)
callback = ffi.from_handle(handle)
return callback(buf)
_marshal_read_cb = ffi.cast('GCallback', gobject_lib._marshal_read)
else:
@ffi.callback('gint64(VipsSourceCustom*, void*, gint64, void*)')
def _marshal_read(gobject, pointer, length, handle):
buf = ffi.buffer(pointer, length)
callback = ffi.from_handle(handle)
return callback(buf)
_marshal_read_cb = ffi.cast('GCallback', _marshal_read)
_marshalers['read'] = _marshal_read_cb
if pyvips.API_mode:
@ffi.def_extern()
def _marshal_seek(gobject, offset, whence, handle):
callback = ffi.from_handle(handle)
return callback(offset, whence)
_marshal_seek_cb = \
ffi.cast('GCallback', gobject_lib._marshal_seek)
else:
@ffi.callback('gint64(VipsSourceCustom*, gint64, int, void*)')
def _marshal_seek(gobject, offset, whence, handle):
callback = ffi.from_handle(handle)
return callback(offset, whence)
_marshal_seek_cb = ffi.cast('GCallback', _marshal_seek)
_marshalers['seek'] = _marshal_seek_cb
if pyvips.API_mode:
@ffi.def_extern()
def _marshal_write(gobject, pointer, length, handle):
buf = ffi.buffer(pointer, length)
callback = ffi.from_handle(handle)
return callback(buf)
_marshal_write_cb = ffi.cast('GCallback', gobject_lib._marshal_write)
else:
@ffi.callback('gint64(VipsTargetCustom*, void*, gint64, void*)')
def _marshal_write(gobject, pointer, length, handle):
buf = ffi.buffer(pointer, length)
callback = ffi.from_handle(handle)
return callback(buf)
_marshal_write_cb = ffi.cast('GCallback', _marshal_write)
_marshalers['write'] = _marshal_write_cb
if pyvips.API_mode:
@ffi.def_extern()
def _marshal_finish(gobject, handle):
callback = ffi.from_handle(handle)
callback()
_marshal_finish_cb = ffi.cast('GCallback', gobject_lib._marshal_finish)
else:
@ffi.callback('void(VipsTargetCustom*, void*)')
def _marshal_finish(gobject, handle):
callback = ffi.from_handle(handle)
callback()
_marshal_finish_cb = ffi.cast('GCallback', _marshal_finish)
_marshalers['finish'] = _marshal_finish_cb
if at_least_libvips(8, 13):
if pyvips.API_mode:
@ffi.def_extern()
def _marshal_end(gobject, handle):
callback = ffi.from_handle(handle)
return callback()
_marshal_end_cb = ffi.cast('GCallback', gobject_lib._marshal_end)
else:
@ffi.callback('int(VipsTargetCustom*, void*)')
def _marshal_end(gobject, handle):
callback = ffi.from_handle(handle)
return callback()
_marshal_end_cb = ffi.cast('GCallback', _marshal_end)
_marshalers['end'] = _marshal_end_cb
class GObject(object):
"""Manage GObject lifetime.
"""
__slots__ = ('_handles', 'pointer')
def __init__(self, pointer):
"""Wrap around a pointer.
Wraps a GObject instance around an underlying pointer. When the
instance is garbage-collected, the underlying object is unreferenced.
"""
# we have to record all of the ffi.new_handle we make for callbacks on
# this object to prevent them being GC'd
self._handles = []
# record the pointer we were given to manage
# on GC, unref
self.pointer = ffi.gc(pointer, gobject_lib.g_object_unref)
# logger.debug('GObject.__init__: pointer = %s', str(self.pointer))
@staticmethod
def new_pointer_from_gtype(gtype):
"""Make a new GObject pointer from a gtype.
This is useful for subclasses which need to control the construction
process.
You can pass the result pointer to the Python constructor for the
object you are building. You will need to call VipsObject.build() to
finish construction.
Returns:
A pointer to a new GObject.
Raises:
:class:`.Error`
"""
pointer = gobject_lib.g_object_new(gtype, ffi.NULL)
if pointer == ffi.NULL:
raise Error(f"can't create {type_name(gtype)}")
return pointer
def signal_connect(self, name, callback):
"""Connect to a signal on this object.
The callback will be triggered every time this signal is issued on this
instance. It will be passed the image ('self' here), and a single
`void *` pointer from libvips.
The value of the pointer, if any, depends on the signal -- for
example, ::eval passes a pointer to a `VipsProgress` struct.
"""
if name not in _marshalers:
raise Error(f'unsupported signal "{name}"')
go = ffi.cast('GObject *', self.pointer)
handle = ffi.new_handle(callback)
# we need to keep refs to the ffi handle and the callback to prevent
# them being GCed
# the callback might be a bound method (a closure) rather than a simple
# function, so it can vanish
self._handles.append(handle)
self._handles.append(callback)
gobject_lib.g_signal_connect_data(go, _to_bytes(name),
_marshalers[name],
handle, ffi.NULL, 0)
__all__ = ['GObject']
python-pyvips-3.1.1/pyvips/gvalue.py 0000664 0000000 0000000 00000027557 15222163673 0017603 0 ustar 00root root 0000000 0000000 import logging
import numbers
import pyvips
from pyvips import ffi, vips_lib, gobject_lib, \
glib_lib, Error, _to_bytes, _to_string, type_name, type_from_name, \
at_least_libvips
logger = logging.getLogger(__name__)
class GValue(object):
"""Wrap GValue in a Python class.
This class wraps :class:`.GValue` in a convenient interface. You can use
instances of this class to get and set :class:`.GObject` properties.
On construction, :class:`.GValue` is all zero (empty). You can pass it to
a get function to have it filled by :class:`.GObject`, or use init to
set a type, set to set a value, then use it to set an object property.
GValue lifetime is managed automatically.
"""
__slots__ = ('pointer', 'gvalue')
# look up some common gtypes at init for speed
gbool_type = type_from_name('gboolean')
gint_type = type_from_name('gint')
guint64_type = type_from_name('guint64')
gdouble_type = type_from_name('gdouble')
gstr_type = type_from_name('gchararray')
genum_type = type_from_name('GEnum')
gflags_type = type_from_name('GFlags')
gobject_type = type_from_name('GObject')
image_type = type_from_name('VipsImage')
array_int_type = type_from_name('VipsArrayInt')
array_double_type = type_from_name('VipsArrayDouble')
array_image_type = type_from_name('VipsArrayImage')
refstr_type = type_from_name('VipsRefString')
blob_type = type_from_name('VipsBlob')
source_type = type_from_name('VipsSource')
target_type = type_from_name('VipsTarget')
pyvips.vips_lib.vips_band_format_get_type()
format_type = type_from_name('VipsBandFormat')
if at_least_libvips(8, 6):
pyvips.vips_lib.vips_blend_mode_get_type()
blend_mode_type = type_from_name('VipsBlendMode')
# map a gtype to the name of the corresponding Python type
_gtype_to_python = {
gbool_type: 'bool',
gint_type: 'int',
guint64_type: 'long', # Note: int and long are unified in Python 3
gdouble_type: 'float',
gstr_type: 'str',
refstr_type: 'str',
genum_type: 'str',
gflags_type: 'int',
gobject_type: 'GObject',
image_type: 'Image',
array_int_type: 'list[int]',
array_double_type: 'list[float]',
array_image_type: 'list[Image]',
blob_type: 'str',
source_type: 'Source',
target_type: 'Target',
}
@staticmethod
def gtype_to_python(gtype):
"""Map a gtype to the name of the Python type we use to represent it.
"""
fundamental = gobject_lib.g_type_fundamental(gtype)
# enums can be strings or class members ... we want to generate a union
# type
if fundamental == GValue.genum_type:
name = type_name(gtype)
if name.startswith('Vips'):
name = name[4:]
return f"Union[str, {name}]"
if gtype in GValue._gtype_to_python:
return GValue._gtype_to_python[gtype]
if fundamental in GValue._gtype_to_python:
return GValue._gtype_to_python[fundamental]
return ''
@staticmethod
def to_enum(gtype, value):
"""Turn a string into an enum value ready to be passed into libvips.
"""
if isinstance(value, str):
enum_value = vips_lib.vips_enum_from_nick(b'pyvips', gtype,
_to_bytes(value))
if enum_value < 0:
raise Error('no value {0} in gtype {1} ({2})'.
format(value, type_name(gtype), gtype))
else:
enum_value = value
return enum_value
@staticmethod
def from_enum(gtype, enum_value):
"""Turn an int back into an enum string.
"""
pointer = vips_lib.vips_enum_nick(gtype, enum_value)
if pointer == ffi.NULL:
raise Error('value not in enum')
return _to_string(pointer)
@staticmethod
def to_flag(gtype, value):
"""Turn a string into a flag value ready to be passed into libvips.
"""
if isinstance(value, str):
flag_value = vips_lib.vips_flags_from_nick(b'pyvips', gtype,
_to_bytes(value))
if flag_value < 0:
raise Error('no value {0} in gtype {1} ({2})'.
format(value, type_name(gtype), gtype))
else:
flag_value = value
return flag_value
def __init__(self):
# allocate memory for the gvalue which will be freed on GC
self.pointer = ffi.new('GValue *')
# logger.debug('GValue.__init__: pointer = %s', self.pointer)
# and tag it to be unset on GC as well
self.gvalue = ffi.gc(self.pointer, gobject_lib.g_value_unset)
# logger.debug('GValue.__init__: gvalue = %s', self.gvalue)
def set_type(self, gtype):
"""Set the type of a GValue.
GValues have a set type, fixed at creation time. Use set_type to set
the type of a GValue before assigning to it.
GTypes are 32 or 64-bit integers (depending on the platform). See
type_find.
"""
gobject_lib.g_value_init(self.gvalue, gtype)
def set(self, value):
"""Set a GValue.
The value is converted to the type of the GValue, if possible, and
assigned.
"""
# logger.debug('GValue.set: value = %s', value)
gtype = self.gvalue.g_type
fundamental = gobject_lib.g_type_fundamental(gtype)
if gtype == GValue.gbool_type:
gobject_lib.g_value_set_boolean(self.gvalue, value)
elif gtype == GValue.gint_type:
gobject_lib.g_value_set_int(self.gvalue, int(value))
elif gtype == GValue.guint64_type:
gobject_lib.g_value_set_uint64(self.gvalue, value)
elif gtype == GValue.gdouble_type:
gobject_lib.g_value_set_double(self.gvalue, value)
elif fundamental == GValue.genum_type:
gobject_lib.g_value_set_enum(self.gvalue,
GValue.to_enum(gtype, value))
elif fundamental == GValue.gflags_type:
gobject_lib.g_value_set_flags(self.gvalue,
GValue.to_flag(gtype, value))
elif gtype == GValue.gstr_type:
gobject_lib.g_value_set_string(self.gvalue, _to_bytes(value))
elif gtype == GValue.refstr_type:
vips_lib.vips_value_set_ref_string(self.gvalue, _to_bytes(value))
elif fundamental == GValue.gobject_type:
gobject_lib.g_value_set_object(self.gvalue, value.pointer)
elif gtype == GValue.array_int_type:
if isinstance(value, numbers.Number):
value = [value]
array = ffi.new('int[]', value)
vips_lib.vips_value_set_array_int(self.gvalue, array, len(value))
elif gtype == GValue.array_double_type:
if isinstance(value, numbers.Number):
value = [value]
array = ffi.new('double[]', value)
vips_lib.vips_value_set_array_double(self.gvalue, array,
len(value))
elif gtype == GValue.array_image_type:
if isinstance(value, pyvips.Image):
value = [value]
vips_lib.vips_value_set_array_image(self.gvalue, len(value))
array = vips_lib.vips_value_get_array_image(self.gvalue, ffi.NULL)
for i, image in enumerate(value):
gobject_lib.g_object_ref(image.pointer)
array[i] = image.pointer
elif gtype == GValue.blob_type:
# we need to set the blob to a copy of the string that vips_lib
# can own
memory = glib_lib.g_malloc(len(value))
ffi.memmove(memory, value, len(value))
# In API mode, we use set_blob_free in a backwards compatible way.
# For pre-8.6 libvipses, in ABI mode, we declare the type of the
# free func in set_blob incorrectly so that we can pass g_free
# at runtime without triggering an exception.
if pyvips.API_mode or at_least_libvips(8, 6):
vips_lib.vips_value_set_blob_free(self.gvalue,
memory, len(value))
else:
vips_lib.vips_value_set_blob(self.gvalue,
glib_lib.g_free,
memory, len(value))
else:
raise Error('unsupported gtype for set {0}, fundamental {1}'.
format(type_name(gtype), type_name(fundamental)))
def get(self):
"""Get the contents of a GValue.
The contents of the GValue are read out as a Python type.
"""
# logger.debug('GValue.get: self = %s', self)
gtype = self.gvalue.g_type
fundamental = gobject_lib.g_type_fundamental(gtype)
result = None
if gtype == GValue.gbool_type:
result = bool(gobject_lib.g_value_get_boolean(self.gvalue))
elif gtype == GValue.gint_type:
result = gobject_lib.g_value_get_int(self.gvalue)
elif gtype == GValue.guint64_type:
result = gobject_lib.g_value_get_uint64(self.gvalue)
elif gtype == GValue.gdouble_type:
result = gobject_lib.g_value_get_double(self.gvalue)
elif fundamental == GValue.genum_type:
return GValue.from_enum(gtype,
gobject_lib.g_value_get_enum(self.gvalue))
elif fundamental == GValue.gflags_type:
result = gobject_lib.g_value_get_flags(self.gvalue)
elif gtype == GValue.gstr_type:
pointer = gobject_lib.g_value_get_string(self.gvalue)
if pointer != ffi.NULL:
result = _to_string(pointer)
elif gtype == GValue.refstr_type:
psize = ffi.new('size_t *')
pointer = vips_lib.vips_value_get_ref_string(self.gvalue, psize)
# psize[0] will be number of bytes in string, but just assume it's
# NULL-terminated
result = _to_string(pointer)
elif gtype == GValue.image_type:
# g_value_get_object() will not add a ref ... that is
# held by the gvalue
go = gobject_lib.g_value_get_object(self.gvalue)
vi = ffi.cast('VipsImage *', go)
# we want a ref that will last with the life of the vimage:
# this ref is matched by the unref that's attached to finalize
# by Image()
gobject_lib.g_object_ref(vi)
result = pyvips.Image(vi)
elif gtype == GValue.array_int_type:
pint = ffi.new('int *')
array = vips_lib.vips_value_get_array_int(self.gvalue, pint)
result = []
for i in range(0, pint[0]):
result.append(array[i])
elif gtype == GValue.array_double_type:
pint = ffi.new('int *')
array = vips_lib.vips_value_get_array_double(self.gvalue, pint)
result = []
for i in range(0, pint[0]):
result.append(array[i])
elif gtype == GValue.array_image_type:
pint = ffi.new('int *')
array = vips_lib.vips_value_get_array_image(self.gvalue, pint)
result = []
for i in range(0, pint[0]):
vi = array[i]
gobject_lib.g_object_ref(vi)
image = pyvips.Image(vi)
result.append(image)
elif gtype == GValue.blob_type:
psize = ffi.new('size_t *')
array = vips_lib.vips_value_get_blob(self.gvalue, psize)
buf = ffi.cast('char*', array)
result = ffi.unpack(buf, psize[0])
else:
raise Error('unsupported gtype for get {0}'.
format(type_name(gtype)))
return result
__all__ = ['GValue']
python-pyvips-3.1.1/pyvips/pyvips_build.py 0000664 0000000 0000000 00000002372 15222163673 0021015 0 ustar 00root root 0000000 0000000 # flake8: noqa
import pkgconfig
from cffi import FFI
# we must have the vips package to be able to do anything
if not pkgconfig.exists('vips'):
raise Exception('unable to find pkg-config package "vips"')
if pkgconfig.installed('vips', '< 8.2'):
raise Exception('pkg-config "vips" is too old -- need libvips 8.2 or later')
major, minor, micro = [int(s) for s in pkgconfig.modversion('vips').split('.')]
ffibuilder = FFI()
# vips_value_set_blob_free and vips_area_free_cb compat for libvips < 8.6
compat = '''
int
vips_area_free_cb(void *mem, VipsArea *area)
{
g_free(mem);
return 0;
}
void
vips_value_set_blob_free(GValue* value, void* data, size_t length)
{
vips_value_set_blob(value, (VipsCallbackFn) vips_area_free_cb,
data, length);
}
''' if major == 8 and minor < 6 else ''
ffibuilder.set_source("_libvips",
f"""
#include
{compat}
""",
**pkgconfig.parse('vips'))
features = {
'major': major,
'minor': minor,
'micro': micro,
'api': True,
}
import vdecls
# handy for debugging
# with open('vips-source.txt','w') as f:
# c = vdecls.cdefs(features)
# f.write(c)
ffibuilder.cdef(vdecls.cdefs(features))
if __name__ == "__main__":
ffibuilder.compile(verbose=True)
python-pyvips-3.1.1/pyvips/vconnection.py 0000664 0000000 0000000 00000002111 15222163673 0020620 0 ustar 00root root 0000000 0000000 import logging
import pyvips
from pyvips import ffi, vips_lib, _to_string
logger = logging.getLogger(__name__)
class Connection(pyvips.VipsObject):
"""The abstract base Connection class.
"""
def __init__(self, pointer):
# logger.debug('Operation.__init__: pointer = %s', pointer)
super(Connection, self).__init__(pointer)
def filename(self):
"""Get the filename associated with a connection. Return None if there
is no associated file.
"""
so = ffi.cast('VipsConnection *', self.pointer)
pointer = vips_lib.vips_connection_filename(so)
if pointer == ffi.NULL:
return None
else:
return _to_string(pointer)
def nick(self):
"""Make a human-readable name for a connection suitable for error
messages.
"""
so = ffi.cast('VipsConnection *', self.pointer)
pointer = vips_lib.vips_connection_nick(so)
if pointer == ffi.NULL:
return None
else:
return _to_string(pointer)
__all__ = ['Connection']
python-pyvips-3.1.1/pyvips/vdecls.py 0000664 0000000 0000000 00000036431 15222163673 0017567 0 ustar 00root root 0000000 0000000 # all the C decls for pyvips
# we keep these together to make switching between ABI and API modes simpler
# we have to pass in the libvips version, since it can come from either
# pkg-config in compile.py (in API mode) or libvips itself in __init__.py
# (in ABI mode)
import sys
def _at_least(features, x, y):
return features['major'] > x or (features['major'] == x and
features['minor'] >= y)
def cdefs(features):
"""Return the C API declarations for libvips.
features is a dict with the features we want. Some features were only
added in later libvips, for example, and some need to be disabled in
some FFI modes.
"""
# we need the glib names for these types
code = '''
typedef uint32_t guint32;
typedef int32_t gint32;
typedef uint64_t guint64;
typedef int64_t gint64;
'''
# apparently the safest way to do this
is_64bits = sys.maxsize > 2 ** 32
# GType is an int the size of a pointer ... I don't think we can just use
# size_t, sadly
if is_64bits:
code += '''
typedef guint64 GType;
'''
else:
code += '''
typedef guint32 GType;
'''
# ... means opaque
code += '''
typedef void (*GLogFunc) (const char* log_domain,
int log_level,
const char* message, void* user_data);
int g_log_set_handler (const char* log_domain,
int log_levels,
GLogFunc log_func, void* user_data);
extern "Python" void _log_handler_callback (const char*, int,
const char*, void*);
void g_log_remove_handler (const char* log_domain, int handler_id);
typedef ... VipsImage;
void* g_malloc (size_t size);
void g_free (void* data);
void vips_leak_set (int leak);
GType vips_type_find (const char* basename, const char* nickname);
const char* vips_nickname_find (GType type);
const char* g_type_name (GType gtype);
GType g_type_from_name (const char* name);
typedef void* (*VipsTypeMap2Fn) (GType type, void* a, void* b);
void* vips_type_map (GType base, void* fn, void* a, void* b);
void vips_shutdown (void);
const char* vips_error_buffer (void);
void vips_error_clear (void);
void vips_error_freeze (void);
void vips_error_thaw (void);
typedef struct _GValue {
GType g_type;
union {
guint64 v_uint64;
// more
} data[2];
} GValue;
void g_value_init (GValue* value, GType gtype);
void g_value_unset (GValue* value);
GType g_type_fundamental (GType gtype);
int vips_enum_from_nick (const char* domain,
GType gtype, const char* str);
int vips_flags_from_nick (const char* domain,
GType gtype, const char* nick);
const char *vips_enum_nick (GType gtype, int value);
void g_value_set_boolean (GValue* value, int v_boolean);
void g_value_set_int (GValue* value, int i);
void g_value_set_uint64 (GValue* value, guint64 ull);
void g_value_set_double (GValue* value, double d);
void g_value_set_enum (GValue* value, int e);
void g_value_set_flags (GValue* value, unsigned int f);
void g_value_set_string (GValue* value, const char* str);
void vips_value_set_ref_string (GValue* value, const char* str);
void g_value_set_object (GValue* value, void* object);
void vips_value_set_array_double (GValue* value,
const double* array, int n );
void vips_value_set_array_int (GValue* value,
const int* array, int n );
void vips_value_set_array_image (GValue *value, int n);
int g_value_get_boolean (const GValue* value);
int g_value_get_int (GValue* value);
guint64 g_value_get_uint64 (GValue* value);
double g_value_get_double (GValue* value);
int g_value_get_enum (GValue* value);
unsigned int g_value_get_flags (GValue* value);
const char* g_value_get_string (GValue* value);
const char* vips_value_get_ref_string (const GValue* value,
size_t* length);
void* g_value_get_object (GValue* value);
double* vips_value_get_array_double (const GValue* value, int* n);
int* vips_value_get_array_int (const GValue* value, int* n);
VipsImage** vips_value_get_array_image (const GValue* value, int* n);
void* vips_value_get_blob (const GValue* value, size_t* length);
// need to make some of these by hand
GType vips_interpretation_get_type (void);
GType vips_operation_flags_get_type (void);
GType vips_band_format_get_type (void);
typedef ... GData;
typedef struct _GTypeClass {
GType g_type;
} GTypeClass;
typedef struct _GTypeInstance {
GTypeClass *g_class;
} GTypeInstance;
typedef struct _GObject {
GTypeInstance g_type_instance;
unsigned int ref_count;
GData *qdata;
} GObject;
typedef struct _GParamSpec {
GTypeInstance g_type_instance;
const char* name;
unsigned int flags;
GType value_type;
GType owner_type;
// private, but cffi in API mode needs these to be able to get the
// offset of any member
char* _nick;
char* _blurb;
GData* qdata;
unsigned int ref_count;
unsigned int param_id;
} GParamSpec;
typedef struct _GEnumValue {
int value;
const char *value_name;
const char *value_nick;
} GEnumValue;
typedef struct _GEnumClass {
GTypeClass g_type_class;
int minimum;
int maximum;
unsigned int n_values;
GEnumValue *values;
} GEnumClass;
typedef struct _GFlagsValue {
unsigned int value;
const char *value_name;
const char *value_nick;
} GFlagsValue;
typedef struct _GFlagsClass {
GTypeClass g_type_class;
unsigned int mask;
unsigned int n_values;
GFlagsValue *values;
} GFlagsClass;
void* g_type_class_ref (GType type);
void* g_object_new (GType type, void*);
void g_object_ref (void* object);
void g_object_unref (void* object);
void g_object_set_property (GObject* object,
const char *name, GValue* value);
void g_object_get_property (GObject* object,
const char* name, GValue* value);
void vips_image_invalidate_all (VipsImage* image);
typedef void (*GCallback)(void);
typedef void (*GClosureNotify)(void* data, struct _GClosure *);
long g_signal_connect_data (GObject* object,
const char* detailed_signal,
GCallback c_handler,
void* data,
GClosureNotify destroy_data,
int connect_flags);
extern "Python" void _marshal_image_progress (VipsImage*,
void*, void*);
void vips_image_set_progress (VipsImage* image, int progress);
void vips_image_set_kill (VipsImage* image, int kill);
typedef ... GTimer;
typedef struct _VipsProgress {
VipsImage* im;
int run;
int eta;
gint64 tpels;
gint64 npels;
int percent;
GTimer* start;
} VipsProgress;
typedef ... VipsObject;
typedef ... VipsObjectClass;
typedef struct _VipsArgument {
GParamSpec *pspec;
} VipsArgument;
typedef struct _VipsArgumentInstance {
VipsArgument parent;
// more
} VipsArgumentInstance;
typedef enum _VipsArgumentFlags {
VIPS_ARGUMENT_NONE = 0,
VIPS_ARGUMENT_REQUIRED = 1,
VIPS_ARGUMENT_CONSTRUCT = 2,
VIPS_ARGUMENT_SET_ONCE = 4,
VIPS_ARGUMENT_SET_ALWAYS = 8,
VIPS_ARGUMENT_INPUT = 16,
VIPS_ARGUMENT_OUTPUT = 32,
VIPS_ARGUMENT_DEPRECATED = 64,
VIPS_ARGUMENT_MODIFY = 128
} VipsArgumentFlags;
typedef struct _VipsArgumentClass {
VipsArgument parent;
VipsObjectClass *object_class;
VipsArgumentFlags flags;
int priority;
unsigned int offset;
} VipsArgumentClass;
int vips_object_get_argument (VipsObject* object,
const char *name, GParamSpec** pspec,
VipsArgumentClass** argument_class,
VipsArgumentInstance** argument_instance);
void vips_object_print_all (void);
int vips_object_set_from_string (VipsObject* object,
const char* options);
const char* vips_object_get_description (VipsObject* object);
const char* g_param_spec_get_blurb (GParamSpec* pspec);
const char* vips_foreign_find_load (const char* name);
const char* vips_foreign_find_load_buffer (const void* data,
size_t size);
const char* vips_foreign_find_save (const char* name);
const char* vips_foreign_find_save_buffer (const char* suffix);
VipsImage* vips_image_new_matrix_from_array (int width, int height,
const double* array, int size);
VipsImage* vips_image_new_from_memory (const void* data, size_t size,
int width, int height, int bands, int format);
VipsImage* vips_image_copy_memory (VipsImage* image);
GType vips_image_get_typeof (const VipsImage* image,
const char* name);
int vips_image_get (const VipsImage* image,
const char* name, GValue* value_copy);
void vips_image_set (VipsImage* image,
const char* name, GValue* value);
int vips_image_remove (VipsImage* image, const char* name);
char* vips_filename_get_filename (const char* vips_filename);
char* vips_filename_get_options (const char* vips_filename);
VipsImage* vips_image_new_temp_file (const char* format);
int vips_image_write (VipsImage* image, VipsImage* out);
void* vips_image_write_to_memory (VipsImage* in, size_t* size_out);
typedef ... VipsInterpolate;
VipsInterpolate* vips_interpolate_new (const char* name);
typedef ... VipsOperation;
VipsOperation* vips_operation_new (const char* name);
typedef void* (*VipsArgumentMapFn) (VipsObject* object,
GParamSpec* pspec,
VipsArgumentClass* argument_class,
VipsArgumentInstance* argument_instance,
void* a, void* b);
void* vips_argument_map (VipsObject* object,
VipsArgumentMapFn fn, void* a, void* b);
typedef ... VipsRegion;
VipsRegion* vips_region_new (VipsImage*);
VipsOperation* vips_cache_operation_build (VipsOperation* operation);
void vips_object_unref_outputs (VipsObject* object);
int vips_operation_get_flags (VipsOperation* operation);
void vips_cache_set_max (int max);
void vips_cache_set_max_mem (size_t max_mem);
void vips_cache_set_max_files (int max_files);
void vips_cache_set_trace (int trace);
int vips_cache_get_max();
int vips_cache_get_size();
size_t vips_cache_get_max_mem();
int vips_cache_get_max_files();
'''
# we must only define this in ABI mode ... in API mode we use
# vips_value_set_blob_free in a backwards compatible way
if not features['api']:
code += '''
typedef void (*FreeFn)(void* a);
void vips_value_set_blob (GValue* value,
FreeFn free_fn, void* data, size_t length);
'''
if _at_least(features, 8, 5):
code += '''
char** vips_image_get_fields (VipsImage* image);
int vips_image_hasalpha (VipsImage* image);
'''
if _at_least(features, 8, 6):
code += '''
GType vips_blend_mode_get_type (void);
void vips_value_set_blob_free (GValue* value,
void* data, size_t length);
'''
if _at_least(features, 8, 7):
code += '''
int vips_object_get_args (VipsObject* object,
const char*** names, int** flags, int* n_args);
'''
if _at_least(features, 8, 8):
code += '''
char** vips_foreign_get_suffixes (void);
void* vips_region_fetch (VipsRegion*, int, int, int, int,
size_t* length);
int vips_region_width (VipsRegion*);
int vips_region_height (VipsRegion*);
int vips_image_get_page_height (VipsImage*);
int vips_image_get_n_pages (VipsImage*);
'''
if _at_least(features, 8, 9):
code += '''
typedef ... VipsConnection;
const char* vips_connection_filename (VipsConnection* stream);
const char* vips_connection_nick (VipsConnection* stream);
typedef ... VipsSource;
VipsSource* vips_source_new_from_descriptor (int descriptor);
VipsSource* vips_source_new_from_file (const char* filename);
VipsSource* vips_source_new_from_memory (const void* data,
size_t size);
typedef ... VipsSourceCustom;
VipsSourceCustom* vips_source_custom_new (void);
extern "Python" gint64 _marshal_read (VipsSource*,
void*, gint64, void*);
extern "Python" gint64 _marshal_seek (VipsSource*,
gint64, int, void*);
typedef ... VipsTarget;
VipsTarget* vips_target_new_to_descriptor (int descriptor);
VipsTarget* vips_target_new_to_file (const char* filename);
VipsTarget* vips_target_new_to_memory (void);
typedef ... VipsTargetCustom;
VipsTargetCustom* vips_target_custom_new (void);
extern "Python" gint64 _marshal_write (VipsTarget*,
void*, gint64, void*);
extern "Python" void _marshal_finish (VipsTarget*,
void*);
const char* vips_foreign_find_load_source (VipsSource *source);
const char* vips_foreign_find_save_target (const char* suffix);
'''
if _at_least(features, 8, 13):
code += '''
extern "Python" int _marshal_end (VipsTarget*,
void*);
void vips_block_untrusted_set (int state);
void vips_operation_block_set (const char *name, int state);
'''
if _at_least(features, 8, 18):
code += '''
VipsImage *vips_image_get_gainmap(VipsImage *image);
'''
# we must only define these in API mode ... in ABI mode we need to call
# these things earlier
if features['api']:
code += '''
int vips_init (const char* argv0);
int vips_version (int flag);
'''
# ... means inherit from C defines
code += '''
#define VIPS_MAJOR_VERSION ...
#define VIPS_MINOR_VERSION ...
#define VIPS_MICRO_VERSION ...
'''
# add contents of features as a comment ... handy for debugging
for key, value in features.items():
code += f'//{key} = {value}\n'
return code
__all__ = ['cdefs']
python-pyvips-3.1.1/pyvips/version.py 0000664 0000000 0000000 00000000160 15222163673 0017762 0 ustar 00root root 0000000 0000000 # this is used in pyproject.toml and imported into __init__.py
__version__ = '3.1.1'
__all__ = ['__version__']
python-pyvips-3.1.1/pyvips/vimage.py 0000664 0000000 0000000 00000170441 15222163673 0017557 0 ustar 00root root 0000000 0000000 # wrap VipsImage
import numbers
import struct
import pyvips
from pyvips import ffi, glib_lib, vips_lib, Error, _to_bytes, \
_to_string, _to_string_copy, GValue, at_least_libvips, Introspect
# either a single number, or a table of numbers
def _is_pixel(value):
return (isinstance(value, numbers.Number) or
(isinstance(value, list) and not
isinstance(value, pyvips.Image)))
# test for rectangular array of something
def _is_2D(array):
if not isinstance(array, list):
return False
for x in array:
if not isinstance(x, list):
return False
if len(x) != len(array[0]):
return False
return True
# apply a function to a thing, or map over a list
# we often need to do something like (1.0 / other) and need to work for lists
# as well as scalars
def _smap(func, x):
if isinstance(x, list):
return list(map(func, x))
else:
return func(x)
def _call_enum(image, other, base, operation):
if _is_pixel(other):
return pyvips.Operation.call(base + '_const', image, operation, other)
else:
return pyvips.Operation.call(base, image, other, operation)
def _run_cmplx(fn, image):
"""Run a complex function on a non-complex image.
The image needs to be complex, or have an even number of bands. The input
can be int, the output is always float or double.
"""
original_format = image.format
if image.format != 'complex' and image.format != 'dpcomplex':
if image.bands % 2 != 0:
raise Error('not an even number of bands')
if image.format != 'float' and image.format != 'double':
image = image.cast('float')
if image.format == 'double':
new_format = 'dpcomplex'
else:
new_format = 'complex'
image = image.copy(format=new_format, bands=image.bands / 2)
image = fn(image)
if original_format != 'complex' and original_format != 'dpcomplex':
if image.format == 'dpcomplex':
new_format = 'double'
else:
new_format = 'float'
image = image.copy(format=new_format, bands=image.bands * 2)
return image
# decorator to set docstring
def _add_doc(name):
try:
docstring = pyvips.Operation.generate_docstring(name)
except Error:
docstring = None
def _doc(func):
func.__doc__ = docstring
return func
return _doc
# decorator to set deprecated
def _deprecated(note):
def _dep(func):
func.__deprecated__ = note
return func
return _dep
# Rules for the mapping between numpy typestrings and libvips formats
# b1: bool. Above u1 so that rev. map is uchar->u1
TYPESTR_TO_FORMAT = {'|b1': 'uchar',
'|u1': 'uchar',
'|i1': 'char',
'`_.
If `__array_interface__` is not available, `__array__` is used as a
fallback.
The behavior for input objects with different dimensions is summarized
as::
| array ndim | array shape | Image w | Image h | Image bands |
|------------|-------------|---------|---------|-------------|
| 0 | () | 1 | 1 | 1 |
| 1 | (W,) | W | 1 | 1 |
| 2 | (H, W) | W | H | 1 |
| 3 | (H, W, C) | W | H | C |
Args:
obj (list or object width `__array_interface__` or `__array__`):
The object to convert to an image.
If the input object is a list, `Image.new_from_list` is used
with the given `scale` and `offset`
If the input object is an array-like object, a new image is
created from the object's data and shape. The memory is shared
except in the following cases:
- The object's memory is not contiguous. In this case, a copy
is made by attempting to call the object's `tobytes()` method
or its `tostring()` method.
- The object is an array of bools, in which case it is
converted to a pyvips uchar image with True values becoming
255 and False values becoming 0.
scale (float): Default to 1.0. **Ignored for non-list inputs**.
What to divide each pixel by after convolution. Useful for
integer convolution masks.
offset (float): Default to 0.0. **Ignored for non-list inputs**.
What to subtract from each pixel after convolution. Useful for
integer convolution masks.
interpretation (str, optional): **Ignored for list inputs** The
libvips interpretation of the array. If None, the
interpretation defaults to the pyvips one for
`Image.new_from_memory`.
If 'auto', a heuristic is used to determine a best-guess
interpretation as defined in the `_guess_interpretation`
function.
Must be one of None, 'auto', 'error', 'multiband', 'b-w',
'histogram', 'xyz', 'lab', 'cmyk', 'labq', 'rgb', 'cmc', 'lch',
'labs', 'srgb', 'yxy', 'fourier', 'rgb16', 'grey16', 'matrix',
'scrgb', or 'hsv'
Returns:
The new image.
See Also:
:func:`_guess_interpretation`
"""
if isinstance(obj, list):
return cls.new_from_list(obj, scale, offset)
if hasattr(obj, '__array_interface__'):
a = obj.__array_interface__
shape = a['shape']
typestr = a['typestr']
ndim = len(shape)
# strides is optional
strides = a.get('strides', None)
if ndim > 3:
raise ValueError('array has more than 3 dimensions')
if typestr not in TYPESTR_TO_FORMAT:
raise ValueError(f'conversion from {typestr} not supported')
if ndim == 0:
width = 1
height = 1
bands = 1
elif ndim == 1:
width = shape[0]
height = 1
bands = 1
elif ndim == 2:
height, width = shape
bands = 1
elif ndim == 3:
height, width, bands = shape
format = TYPESTR_TO_FORMAT[typestr]
if strides is None and hasattr(obj, 'data'):
data = obj.data
else:
# To obtain something with a contiguous memory layout
if hasattr(obj, 'tobytes'):
data = obj.tobytes()
elif hasattr(obj, 'tostring'):
data = obj.tostring()
else:
raise TypeError('object has no .tobytes or .tostring')
im = cls.new_from_memory(
data,
width,
height,
bands,
format
)
if typestr == '|b1':
# special case for bool: true in vips is uchar(255)
im = im.ifthenelse(255, 0)
if interpretation is not None:
if interpretation == 'auto':
interpretation = _guess_interpretation(bands, format)
im = im.copy(interpretation=interpretation)
return im
elif hasattr(obj, '__array__'):
# make it into something that *does* define __array_interface__
return cls.new_from_array(obj.__array__())
else:
raise TypeError('does not define __array_interface__ '
'or __array__')
@staticmethod
def new_from_memory(data, width, height, bands, format):
"""Wrap an image around a memory array.
Wraps an Image around an area of memory containing a C-style array. For
example, if the ``data`` memory array contains four bytes with the
values 1, 2, 3, 4, you can make a one-band, 2x2 uchar image from
it like this::
image = Image.new_from_memory(data, 2, 2, 1, 'uchar')
A reference is kept to the data object, so it will not be
garbage-collected until the returned image is garbage-collected.
This method is useful for efficiently transferring images from PIL or
NumPy into libvips.
See :meth:`.write_to_memory` for the opposite operation.
Use :meth:`.copy` to set other image attributes.
Args:
data (bytes): A memoryview or buffer object.
width (int): Image width in pixels.
height (int): Image height in pixels.
bands (int): Number of bands.
format (BandFormat): Band format.
Returns:
A new :class:`Image`.
Raises:
:class:`.Error`
"""
format_value = GValue.to_enum(GValue.format_type, format)
pointer = ffi.from_buffer(data)
nbytes = data.nbytes if hasattr(data, 'nbytes') else len(data)
vi = vips_lib.vips_image_new_from_memory(pointer,
nbytes,
width, height, bands,
format_value)
if vi == ffi.NULL:
raise Error('unable to make image from memory')
image = pyvips.Image(vi)
# keep a secret ref to the underlying object .. this reference will be
# inherited by things that in turn depend on us, so the memory we are
# using will not be freed
image._references.append(data)
return image
@staticmethod
def new_from_source(source, options, **kwargs):
"""Load a formatted image from a source.
This behaves exactly as :meth:`new_from_file`, but the image is
loaded from the source rather than from a file.
Args:
source (Source): The source to load the image from.
options (str): Load options as a string. Use ``""`` for no options.
All loaders support at least the following options:
Keyword args:
access (Access): Hint the expected access pattern for the image.
fail (bool): If set True, the loader will fail with an error on the
first serious error in the image. By default, libvips will
attempt to read everything it can from a damaged image.
Returns:
A new :class:`Image`.
Raises:
:class:`.Error`
"""
pointer = vips_lib.vips_foreign_find_load_source(source.pointer)
if pointer == ffi.NULL:
raise Error('unable to load from source')
name = _to_string(pointer)
image = pyvips.Operation.call(name, source,
string_options=options, **kwargs)
# keep a secret ref to the source object .. we need that to stay
# alive, since it might be a custom source that triggers a python
# callback
image._references.append(source)
return image
@staticmethod
def new_temp_file(format):
"""Make a new temporary image.
Returns an image backed by a temporary file. When written to with
:func:`Image.write`, a temporary file will be created on disc in the
specified format. When the image is closed, the file will be deleted
automatically.
The file is created in the temporary directory. This is set with
the environment variable ``TMPDIR``. If this is not set, then on
Unix systems, vips will default to ``/tmp``. On Windows, vips uses
``GetTempPath()`` to find the temporary directory.
vips uses ``g_mkstemp()`` to make the temporary filename. They
generally look something like ``"vips-12-EJKJFGH.v"``.
Args:
format (str): The format for the temp file, for example
``"%s.v"`` for a vips format file. The ``%s`` is
substituted by the file path.
Returns:
A new :class:`Image`.
Raises:
:class:`.Error`
"""
vi = vips_lib.vips_image_new_temp_file(_to_bytes(format))
if vi == ffi.NULL:
raise Error('unable to make temp file')
return pyvips.Image(vi)
def new_from_image(self, value):
"""Make a new image from an existing one.
A new image is created which has the same size, format, interpretation
and resolution as ``self``, but with every pixel set to ``value``.
Args:
value (float, list[float]): The value for the pixels. Use a
single number to make a one-band image; use an array constant
to make a many-band image.
Returns:
A new :class:`Image`.
Raises:
:class:`.Error`
"""
pixel = (Image.black(1, 1) + value).cast(self.format)
image = pixel.embed(0, 0, self.width, self.height,
extend='copy')
image = image.copy(interpretation=self.interpretation,
xres=self.xres,
yres=self.yres,
xoffset=self.xoffset,
yoffset=self.yoffset)
return image
def copy_memory(self):
"""Copy an image to memory.
A large area of memory is allocated, the image is rendered to that
memory area, and a new image is returned which wraps that large memory
area.
Returns:
A new :class:`Image`.
Raises:
:class:`.Error`
"""
vi = vips_lib.vips_image_copy_memory(self.pointer)
if vi == ffi.NULL:
raise Error('unable to copy to memory')
return pyvips.Image(vi)
# writers
def write_to_file(self, vips_filename, **kwargs):
"""Write an image to a file on disc.
This method can save images in any format supported by vips. The format
is selected from the filename suffix. The filename can include embedded
save options, see :func:`Image.new_from_file`.
For example::
image.write_to_file('fred.jpg[Q=95]')
You can also supply options as keyword arguments, for example::
image.write_to_file('fred.jpg', Q=95)
The full set of options available depend upon the load operation that
will be executed. Try something like::
$ vips jpegsave
at the command-line to see a summary of the available options for the
JPEG saver.
Args:
vips_filename (str): The disc file to save the image to, with
optional appended arguments.
Other arguments depend upon the save operation.
Returns:
None
Raises:
:class:`.Error`
"""
vips_filename = _to_bytes(vips_filename)
pointer = vips_lib.vips_filename_get_filename(vips_filename)
filename = _to_string_copy(pointer)
pointer = vips_lib.vips_filename_get_options(vips_filename)
options = _to_string_copy(pointer)
pointer = vips_lib.vips_foreign_find_save(vips_filename)
if pointer == ffi.NULL:
raise Error(f'unable to write to file {vips_filename}')
name = _to_string(pointer)
return pyvips.Operation.call(name, self, filename,
string_options=options, **kwargs)
def write_to_buffer(self, format_string, **kwargs):
"""Write an image to memory.
This method can save images in any format supported by vips. The format
is selected from the suffix in the format string. This can include
embedded save options, see :func:`Image.write_to_file`.
For example::
data = image.write_to_buffer('.jpg[Q=95]')
You can also supply options as keyword arguments, for example::
data = image.write_to_buffer('.jpg', Q=95)
The full set of options available depend upon the load operation that
will be executed. Try something like::
$ vips jpegsave_buffer
at the command-line to see a summary of the available options for the
JPEG saver.
Args:
format_string (str): The suffix, plus any string-form arguments.
Other arguments depend upon the save operation.
Returns:
A byte string.
Raises:
:class:`.Error`
"""
format_string = _to_bytes(format_string)
filename = vips_lib.vips_filename_get_filename(format_string)
filename = ffi.gc(filename, glib_lib.g_free)
pointer = vips_lib.vips_filename_get_options(format_string)
options = _to_string_copy(pointer)
pointer = ffi.NULL
if at_least_libvips(8, 9):
vips_lib.vips_error_freeze()
pointer = vips_lib.vips_foreign_find_save_target(filename)
vips_lib.vips_error_thaw()
if pointer != ffi.NULL:
name = _to_string(pointer)
target = pyvips.Target.new_to_memory()
pyvips.Operation.call(name, self, target,
string_options=options, **kwargs)
buffer = target.get("blob")
else:
pointer = vips_lib.vips_foreign_find_save_buffer(filename)
if pointer == ffi.NULL:
raise Error('unable to write to buffer')
name = _to_string(pointer)
buffer = pyvips.Operation.call(name, self,
string_options=options, **kwargs)
return buffer
def write_to_target(self, target, format_string, **kwargs):
"""Write an image to a target.
This method will write the image to the target in the format
specified in the suffix in the format string. This can include
embedded save options, see :func:`Image.write_to_file`.
For example::
image.write_to_target(target, '.jpg[Q=95]')
You can also supply options as keyword arguments, for example::
image.write_to_target(target, '.jpg', Q=95)
The full set of options available depend upon the save operation that
will be executed. Try something like::
$ vips jpegsave_target
at the command-line to see a summary of the available options for the
JPEG saver.
Args:
target (Target): The target to write the image to
format_string (str): The suffix, plus any string-form arguments.
Other arguments depend upon the save operation.
Returns:
None
Raises:
:class:`.Error`
"""
format_string = _to_bytes(format_string)
pointer = vips_lib.vips_filename_get_options(format_string)
options = _to_string_copy(pointer)
pointer = vips_lib.vips_foreign_find_save_target(format_string)
if pointer == ffi.NULL:
raise Error('unable to write to target')
name = _to_string(pointer)
return pyvips.Operation.call(name, self, target,
string_options=options, **kwargs)
def write_to_memory(self):
"""Write the image to a large memory array.
A large area of memory is allocated, the image is rendered to that
memory array, and the array is returned as a buffer.
For example, if you have a 2x2 uchar image containing the bytes 1, 2,
3, 4, read left-to-right, top-to-bottom, then::
buf = image.write_to_memory()
will return a four byte buffer containing the values 1, 2, 3, 4.
Returns:
buffer
Raises:
:class:`.Error`
"""
psize = ffi.new('size_t *')
pointer = vips_lib.vips_image_write_to_memory(self.pointer, psize)
if pointer == ffi.NULL:
raise Error('unable to write to memory')
pointer = ffi.gc(pointer, glib_lib.g_free)
return ffi.buffer(pointer, psize[0])
def write(self, other):
"""Write an image to another image.
This function writes ``self`` to another image. Use something like
:func:`Image.new_temp_file` to make an image that can be written to.
Args:
other (Image): The :class:`Image` to write to,
Returns:
None
Raises:
:class:`.Error`
"""
result = vips_lib.vips_image_write(self.pointer, other.pointer)
if result != 0:
raise Error('unable to write to image')
def invalidate(self):
"""Drop caches on an image, and any downstream images.
This method drops all pixel caches on an image and on all downstream
images. Any operations which depend on this image, directly or
indirectly, are also dropped from the libvips operation cache.
This method can be useful if you wrap a libvips image around an area
of memory with :meth:`.new_from_memory` and then change some bytes
without libvips knowing.
Returns:
None
"""
vips_lib.vips_image_invalidate_all(self.pointer)
def set_progress(self, progress):
"""Enable progress reporting on an image.
When progress reporting is enabled, evaluation of the most downstream
image from this image will report progress using the ::preeval, ::eval,
and ::posteval signals.
"""
vips_lib.vips_image_set_progress(self.pointer, progress)
def set_kill(self, kill):
"""Kill processing of an image.
Use this to kill evaluation of an image. You can call it from one of
the progress signals, for example. See :meth:`.set_progress`.
"""
vips_lib.vips_image_set_kill(self.pointer, kill)
# get/set metadata
def get_gainmap(self):
"""Get the image gainmap, if any.
Get the gainmap associated with this image, or None for no gainmap.
After updating the gainmap, use :meth:`.set_type` to update the
`"gainmap"` metadata item.
Returns:
The gainmap image.
Raises:
None
"""
if not at_least_libvips(8, 18):
return None
else:
pointer = vips_lib.vips_image_get_gainmap(self.pointer)
if pointer == ffi.NULL:
return None
else:
return pyvips.Image(pointer)
def get_typeof(self, name):
"""Get the GType of an item of metadata.
Fetch the GType of a piece of metadata, or 0 if the named item does not
exist. See :class:`GValue`.
Args:
name (str): The name of the piece of metadata to get the type of.
Returns:
The ``GType``, or 0.
Raises:
None
"""
# on libvips before 8.5, property types must be fetched separately,
# since built-in enums were reported as ints
if not at_least_libvips(8, 5):
gtype = super(Image, self).get_typeof(name)
if gtype != 0:
return gtype
return vips_lib.vips_image_get_typeof(self.pointer, _to_bytes(name))
def get(self, name):
"""Get an item of metadata.
Fetches an item of metadata as a Python value. For example::
orientation = image.get('orientation')
would fetch the image orientation.
Args:
name (str): The name of the piece of metadata to get.
Returns:
The metadata item as a Python value.
Raises:
:class:`.Error`
"""
# with old libvips, we must fetch properties (as opposed to
# metadata) via VipsObject
if not at_least_libvips(8, 5):
gtype = super(Image, self).get_typeof(name)
if gtype != 0:
return super(Image, self).get(name)
gv = GValue()
result = vips_lib.vips_image_get(self.pointer, _to_bytes(name),
gv.pointer)
if result != 0:
raise Error(f'unable to get {name}')
return gv.get()
def get_fields(self):
"""Get a list of all the metadata fields on an image.
Returns:
[string]
"""
names = []
if at_least_libvips(8, 5):
array = vips_lib.vips_image_get_fields(self.pointer)
i = 0
while array[i] != ffi.NULL:
name = _to_string(array[i])
names.append(name)
glib_lib.g_free(array[i])
i += 1
glib_lib.g_free(array)
return names
def set_type(self, gtype, name, value):
"""Set the type and value of an item of metadata.
Sets the type and value of an item of metadata. Any old item of the
same name is removed. See :class:`GValue` for types.
Args:
gtype (int): The GType of the metadata item to create.
name (str): The name of the piece of metadata to create.
value (mixed): The value to set as a Python value. It is
converted to the ``gtype``, if possible.
Returns:
None
Raises:
None
"""
gv = GValue()
gv.set_type(gtype)
gv.set(value)
vips_lib.vips_image_set(self.pointer, _to_bytes(name), gv.pointer)
def set(self, name, value):
"""Set the value of an item of metadata.
Sets the value of an item of metadata. The metadata item must already
exist.
Args:
name (str): The name of the piece of metadata to set the value of.
value (mixed): The value to set as a Python value. It is
converted to the type of the metadata item, if possible.
Returns:
None
Raises:
:class:`.Error`
"""
gtype = self.get_typeof(name)
if gtype == 0:
raise Error(f'metadata item {name} does not exist -'
' use set_type() to create and set')
self.set_type(gtype, name, value)
def remove(self, name):
"""Remove an item of metadata.
The named metadata item is removed.
Args:
name (str): The name of the piece of metadata to remove.
Returns:
None
Raises:
None
"""
return vips_lib.vips_image_remove(self.pointer, _to_bytes(name)) != 0
def tolist(self):
"""Return a single-band image as a list of lists.
Returns:
list of lists of values
"""
if not self.bands == 1:
raise NotImplementedError('tolist only implemented for ' +
'single-band images')
is_complex = self.format in ['complex', 'dpcomplex']
row_els = self.width if not is_complex else 2 * self.width
rowfmt = f'{row_els}{FORMAT_TO_PYFORMAT[self.format]}'
buf = self.write_to_memory()
lst = [list(row) for row in struct.iter_unpack(rowfmt, buf)]
if is_complex:
lst = [[r[i] + 1j*r[i+1] for i in range(0, row_els, 2)]
for r in lst]
return lst
# Following will be relevant if we expose the buffer interface:
# @property
# def __array_interface__(self):
# """Return a numpy-standard __array_interface__ dictionary.
#
# This is used by some libraries (PIL, e.g.) to interpret the image
# as an array.
#
# See https://numpy.org/doc/stable/reference/arrays.interface.html for
# more info.
#
# """
# if self.bands == 1:
# shape = (self.height, self.width)
# else:
# shape = (self.height, self.width, self.bands)
#
# typestr = FORMAT_TO_TYPESTR[self.format]
#
# interface = {
# 'shape': shape,
# 'strides': None,
# 'descr': [('', typestr)],
# 'typestr': typestr,
# 'version': 3
# }
#
# return interface
def __array__(self, dtype=None, copy=None):
"""Conversion to a NumPy array.
Args:
dtype (str or numpy dtype, optional) The dtype to use for the
numpy array. If None, the default dtype of the image is used
as defined the global `FORMAT_TO_TYPESTR` dictionary.
copy (bool, optional) If True, always copy the data; if None, copy
if required; if False, never copy.
Returns:
numpy.ndarray: The array representation of the image.
* Single-band images lose their channel axis.
* Single-pixel single-band images are converted to a 0D array.
See https://numpy.org/devdocs/user/basics.dispatch.html for more
details.
This enables a :class:`Image` to be used where a numpy array is
expected, including in plotting and conversion to other array
container types (pytorch, JAX, dask, etc.), for example.
`numpy` is a runtime dependency of this function.
See Also `Image.new_from_array` for the inverse operation. #TODO
"""
import numpy as np
# we always generate a new image, so if copy is False, we can't work
if copy is False:
raise ValueError
arr = (
np.frombuffer(self.write_to_memory(),
dtype=FORMAT_TO_TYPESTR[self.format])
.reshape(self.height, self.width, self.bands)
)
if self.bands == 1:
# flatten single-band images
arr = arr.squeeze(axis=-1)
if self.width == 1 and self.height == 1:
# flatten single-pixel single-band images
arr = arr.squeeze(axis=(0, 1))
if dtype is not None:
arr = arr.astype(dtype)
return arr
def numpy(self, dtype=None):
"""Convenience function to allow numpy conversion to be at the end
of a method chain.
This mimics the behavior of pytorch: ``arr = im.op1().op2().numpy()``
numpy is a runtime dependency of this function.
Args:
dtype (str or numpy dtype): The dtype to use for the numpy array.
If None, the default dtype of the image is used.
Returns:
numpy.ndarray: The image as a numpy array.
See Also:
- :meth:`.__array__`
- `FORMAT_TO_TYPESTR`: Global dictionary mapping libvips format
strings to numpy dtype strings.
"""
return self.__array__(dtype=dtype)
def __repr__(self):
if (
self.interpretation == "matrix"
and self.width < 20
and self.height < 20
and self.bands == 1
):
array = self.tolist()
return repr(array)
else:
return (f'')
def __getattr__(self, name):
"""Divert unknown names to libvips.
Unknown attributes are first looked up in the image properties as
accessors, for example::
width = image.width
and then in the libvips operation table, where they become method
calls, for example::
new_image = image.invert()
Use :func:`get` to fetch image metadata.
A ``__getattr__`` on the metatype lets you call static members in the
same way.
Args:
name (str): The name of the piece of metadata to get.
Returns:
Mixed.
Raises:
:class:`.Error`
"""
# logger.debug('Image.__getattr__ %s', name)
# scale and offset have default values
if name == 'scale':
if self.get_typeof('scale') != 0:
return self.get('scale')
else:
return 1.0
if name == 'offset':
if self.get_typeof('offset') != 0:
return self.get('offset')
else:
return 0.0
# look up in props first (but not metadata)
if super(Image, self).get_typeof(name) != 0:
return super(Image, self).get(name)
# does the method exist in libvips?
try:
# this will throw an exception if not
Introspect.get(name)
except Error:
# we need to throw this exception for missing methods, eg. numpy
# checks for this
raise AttributeError
@_add_doc(name)
def call_function(*args, **kwargs):
return pyvips.Operation.call(name, self, *args, **kwargs)
return call_function
# compatibility methods
@_deprecated('use Image.get() instead')
def get_value(self, name):
return self.get(name)
@_deprecated('use Image.set() instead')
def set_value(self, name, value):
self.set(name, value)
@_deprecated('use Image.scale instead')
def get_scale(self):
return self.scale
@_deprecated('use Image.offset instead')
def get_offset(self):
return self.offset
# support with in the most trivial way
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
pass
def __getitem__(self, arg):
"""Overload [] to pull out band elements from an image.
The following arguments types are accepted:
* int::
green = rgb_image[1]
Will make a new one-band image from band 1 (the middle band).
* slice::
last_two = rgb_image[1:]
last_band = rgb_image[-1]
middle_few = multiband[1:-2]
reversed = multiband[::-1]
every_other = multiband[::2]
other_every_other = multiband[1::2]
* list of int::
# list of integers
desired_bands = [1, 2, 2, -1]
four_band = multiband[desired_bands]
* list of bool::
wanted_bands = [True, False, True, True, False]
three_band = five_band[wanted_bands]
In the case of integer or slice arguments, the semantics of slicing
exactly match those of slicing `range(self.bands)`.
In the case of list arguments, the semantics match those of numpy's
extended slicing syntax. Thus, lists of booleans must have as many
elements as there are bands in the image.
"""
if isinstance(arg, int):
# raises IndexError for bad integer indices
i = range(self.bands)[arg]
n = 1
elif isinstance(arg, slice):
band_seq = range(self.bands)[arg]
if len(band_seq) == 0:
raise IndexError('empty slice')
i = band_seq[0]
n = len(band_seq)
elif isinstance(arg, list):
if not arg:
raise IndexError('empty list')
# n.b. We don't use isinstance because isinstance(True, int)
# is True!
if not (all(type(x) == int for x in arg) or # noqa: E721
all(type(x) == bool for x in arg)): # noqa: E721
raise IndexError('list must contain only ints or only bools')
if isinstance(arg[0], bool):
if len(arg) != self.bands:
raise IndexError('boolean index must have same ' +
'length as bands')
band_seq = [i for i, x in enumerate(arg) if x]
n = len(band_seq)
if n == 0:
raise IndexError('empty boolean index')
if n == 1:
i = band_seq[0]
else:
all_bands = range(self.bands)
# raises IndexError for bad int indices
band_seq = [all_bands[i] for i in arg]
n = len(band_seq)
if n == 1:
i = band_seq[0]
else:
raise IndexError('argument must be an int, slice, ' +
'list of ints, or list of bools')
if n == 1:
# int or 1-element selection
return self.extract_band(i)
elif isinstance(arg, slice) and arg.step == 1:
# sequential multi-band slice
return self.extract_band(i, n=n)
else:
# nonsequential slice, list of ints, or list of bools
bands = [self.extract_band(x) for x in band_seq]
return bands[0].bandjoin(bands[1:])
# overload () to mean fetch pixel
def __call__(self, x, y):
"""Fetch a pixel value.
Args:
x (int): The x coordinate to fetch.
y (int): The y coordinate to fetch.
Returns:
Pixel as an array of floating point numbers.
Raises:
:class:`.Error`
"""
return self.getpoint(x, y)
# operator overloads
def __add__(self, other):
if isinstance(other, pyvips.Image):
return self.add(other)
else:
return self.linear(1, other)
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
if isinstance(other, pyvips.Image):
return self.subtract(other)
else:
return self.linear(1, _smap(lambda x: -1 * x, other))
def __rsub__(self, other):
return self.linear(-1, other)
def __mul__(self, other):
if isinstance(other, Image):
return self.multiply(other)
else:
return self.linear(other, 0)
def __rmul__(self, other):
return self.__mul__(other)
# a / const has always been a float in vips, so div and truediv are the
# same
def __div__(self, other):
if isinstance(other, pyvips.Image):
return self.divide(other)
else:
return self.linear(_smap(lambda x: 1.0 / x, other), 0)
def __rdiv__(self, other):
return (self ** -1) * other
def __truediv__(self, other):
return self.__div__(other)
def __rtruediv__(self, other):
return self.__rdiv__(other)
def __floordiv__(self, other):
if isinstance(other, pyvips.Image):
return self.divide(other).floor()
else:
return self.linear(_smap(lambda x: 1.0 / x, other), 0).floor()
def __rfloordiv__(self, other):
return ((self ** -1) * other).floor()
def __mod__(self, other):
if isinstance(other, pyvips.Image):
return self.remainder(other)
else:
return self.remainder_const(other)
def __pow__(self, other):
return _call_enum(self, other, 'math2', 'pow')
def __rpow__(self, other):
return _call_enum(self, other, 'math2', 'wop')
def __abs__(self):
return self.abs()
def __lshift__(self, other):
return _call_enum(self, other, 'boolean', 'lshift')
def __rshift__(self, other):
return _call_enum(self, other, 'boolean', 'rshift')
def __and__(self, other):
return _call_enum(self, other, 'boolean', 'and')
def __rand__(self, other):
return self.__and__(other)
def __or__(self, other):
return _call_enum(self, other, 'boolean', 'or')
def __ror__(self, other):
return self.__or__(other)
def __xor__(self, other):
return _call_enum(self, other, 'boolean', 'eor')
def __rxor__(self, other):
return self.__xor__(other)
def __neg__(self):
return -1 * self
def __pos__(self):
return self
def __invert__(self):
return self ^ -1
def __gt__(self, other):
return _call_enum(self, other, 'relational', 'more')
def __ge__(self, other):
return _call_enum(self, other, 'relational', 'moreeq')
def __lt__(self, other):
return _call_enum(self, other, 'relational', 'less')
def __le__(self, other):
return _call_enum(self, other, 'relational', 'lesseq')
def __eq__(self, other):
# _eq version allows comparison to None
if other is None:
return False
return _call_enum(self, other, 'relational', 'equal')
def __ne__(self, other):
# _eq version allows comparison to None
if other is None:
return True
return _call_enum(self, other, 'relational', 'noteq')
def floor(self):
"""Return the largest integral value not greater than the argument."""
return self.round('floor')
def ceil(self):
"""Return the smallest integral value not less than the argument."""
return self.round('ceil')
def rint(self):
"""Return the nearest integral value."""
return self.round('rint')
def bandand(self):
"""AND image bands together."""
return self.bandbool('and')
def bandor(self):
"""OR image bands together."""
return self.bandbool('or')
def bandeor(self):
"""EOR image bands together."""
return self.bandbool('eor')
def bandsplit(self):
"""Split an n-band image into n separate images."""
return [x for x in self]
def bandjoin(self, other):
"""Append a set of images or constants bandwise."""
if not isinstance(other, list):
other = [other]
# guard against empty list
if not other:
return self
# if [other] is all numbers, we can use bandjoin_const
non_number = next((x for x in other
if not isinstance(x, numbers.Number)),
None)
if non_number is None:
return self.bandjoin_const(other)
else:
return pyvips.Operation.call('bandjoin', [self] + other)
def atan2(self, other):
return _call_enum(self, other, 'math2', 'atan2')
def get_n_pages(self):
"""Get the number of pages in an image file, or 1.
This is the number of pages in the file the image was loaded from, not
the number of pages in the image.
To get the number of pages in an image, divide the image height by
the page height.
"""
if at_least_libvips(8, 8):
return vips_lib.vips_image_get_n_pages(self.pointer)
else:
return self.get("n-pages") \
if self.get_typeof("n-pages") != 0 else 1
def get_page_height(self):
"""Get the page height in a many-page image, or height.
"""
if at_least_libvips(8, 8):
return vips_lib.vips_image_get_page_height(self.pointer)
else:
if self.get_typeof("page-height") != 0:
page_height = self.get("page-height")
else:
page_height = self.height
if page_height > 0 and \
page_height <= self.height and \
self.height % page_height == 0:
return page_height
else:
return self.height
def pagesplit(self):
"""Split an N-page image into a list of N separate images.
"""
page_height = self.get_page_height()
return [self.crop(0, y, self.width, page_height)
for y in range(0, self.height, page_height)]
def pagejoin(self, other):
"""Join a set of pages vertically to make a multipage image.
Also sets the page-height property on the result.
"""
if not isinstance(other, list):
other = [other]
n_pages = 1 + len(other)
image = Image.arrayjoin([self] + other, across=1)
image = image.copy()
image.set_type(GValue.gint_type, 'page-height', image.height / n_pages)
return image
def composite(self, other, mode, **kwargs):
"""Composite a set of images with a set of modes."""
if not isinstance(other, list):
other = [other]
if not isinstance(mode, list):
mode = [mode]
# modes are VipsBlendMode enums, but we have to pass as array of int --
# we need to map str->int by hand
mode = [GValue.to_enum(GValue.blend_mode_type, x) for x in mode]
return pyvips.Operation.call('composite', [self] + other, mode,
**kwargs)
def bandrank(self, other, **kwargs):
"""Band-wise rank filter a set of images."""
if not isinstance(other, list):
other = [other]
return pyvips.Operation.call('bandrank', [self] + other, **kwargs)
def maxpos(self):
"""Return the coordinates of the image maximum."""
v, opts = self.max(x=True, y=True)
x = opts['x']
y = opts['y']
return v, x, y
def minpos(self):
"""Return the coordinates of the image minimum."""
v, opts = self.min(x=True, y=True)
x = opts['x']
y = opts['y']
return v, x, y
def real(self):
"""Return the real part of a complex image."""
return self.complexget('real')
def imag(self):
"""Return the imaginary part of a complex image."""
return self.complexget('imag')
def polar(self):
"""Return an image converted to polar coordinates."""
return _run_cmplx(lambda x: x.complex('polar'), self)
def rect(self):
"""Return an image converted to rectangular coordinates."""
return _run_cmplx(lambda x: x.complex('rect'), self)
def conj(self):
"""Return the complex conjugate of an image."""
return self.complex('conj')
def sin(self):
"""Return the sine of an image in degrees."""
return self.math('sin')
def cos(self):
"""Return the cosine of an image in degrees."""
return self.math('cos')
def tan(self):
"""Return the tangent of an image in degrees."""
return self.math('tan')
def asin(self):
"""Return the inverse sine of an image in degrees."""
return self.math('asin')
def acos(self):
"""Return the inverse cosine of an image in degrees."""
return self.math('acos')
def atan(self):
"""Return the inverse tangent of an image in degrees."""
return self.math('atan')
def sinh(self):
"""Return the hyperbolic sine of an image in radians."""
return self.math('sinh')
def cosh(self):
"""Return the hyperbolic cosine of an image in radians."""
return self.math('cosh')
def tanh(self):
"""Return the hyperbolic tangent of an image in radians."""
return self.math('tanh')
def asinh(self):
"""Return the inverse hyperbolic sine of an image in radians."""
return self.math('asinh')
def acosh(self):
"""Return the inverse hyperbolic cosine of an image in radians."""
return self.math('acosh')
def atanh(self):
"""Return the inverse hyperbolic tangent of an image in radians."""
return self.math('atanh')
def log(self):
"""Return the natural log of an image."""
return self.math('log')
def log10(self):
"""Return the log base 10 of an image."""
return self.math('log10')
def exp(self):
"""Return e ** pixel."""
return self.math('exp')
def exp10(self):
"""Return 10 ** pixel."""
return self.math('exp10')
def erode(self, mask):
"""Erode with a structuring element."""
return self.morph(mask, 'erode')
def dilate(self, mask):
"""Dilate with a structuring element."""
return self.morph(mask, 'dilate')
def median(self, size):
"""size x size median filter."""
return self.rank(size, size, (size * size) / 2)
def fliphor(self):
"""Flip horizontally."""
return self.flip('horizontal')
def flipver(self):
"""Flip vertically."""
return self.flip('vertical')
def rot90(self):
"""Rotate 90 degrees clockwise."""
return self.rot('d90')
def rot180(self):
"""Rotate 180 degrees."""
return self.rot('d180')
def rot270(self):
"""Rotate 270 degrees clockwise."""
return self.rot('d270')
def hasalpha(self):
"""True if the image has an alpha channel."""
return vips_lib.vips_image_hasalpha(self.pointer)
def addalpha(self):
"""Add an alpha channel."""
if self.interpretation == 'grey16' or self.interpretation == 'rgb16':
max_alpha = 65535
elif self.interpretation == 'scrgb':
max_alpha = 1.0
else:
max_alpha = 255
return self.bandjoin(max_alpha)
# we need different _imageize rules for this operator ... we need to
# _imageize in1 and in2 to match each other first
@_add_doc('ifthenelse')
def ifthenelse(self, in1, in2, **kwargs):
for match_image in [in1, in2, self]:
if isinstance(match_image, pyvips.Image):
break
if not isinstance(in1, pyvips.Image):
in1 = Image._imageize(match_image, in1)
if not isinstance(in2, pyvips.Image):
in2 = Image._imageize(match_image, in2)
return pyvips.Operation.call('ifthenelse', self, in1, in2, **kwargs)
def scaleimage(self, **kwargs):
"""Scale an image to 0 - 255.
This is the libvips ``scale`` operation, renamed to avoid a clash with
the ``scale`` for convolution masks.
Keyword args:
exp (float): Exponent for log scale.
log (bool): Switch to turn on log scaling.
Returns:
A new :class:`Image`.
Raises:
:class:`.Error`
"""
return pyvips.Operation.call('scale', self, **kwargs)
__all__ = ['Image']
python-pyvips-3.1.1/pyvips/vinterpolate.py 0000664 0000000 0000000 00000002042 15222163673 0021012 0 ustar 00root root 0000000 0000000 import pyvips
from pyvips import ffi, vips_lib, Error, _to_bytes
# import logging
# logger = logging.getLogger(__name__)
class Interpolate(pyvips.VipsObject):
"""Make interpolators for operators like :meth:`.affine`.
"""
def __init__(self, pointer):
# logger.debug('Operation.__init__: pointer = %s', pointer)
super(Interpolate, self).__init__(pointer)
@staticmethod
def new(name):
"""Make a new interpolator by name.
Make a new interpolator from the libvips class nickname. For example::
inter = pyvips.Interpolator.new('bicubic')
You can get a list of all supported interpolators from the command-line
with::
$ vips -l interpolate
See for example :meth:`.affine`.
"""
# logger.debug('VipsInterpolate.new: name = %s', name)
vi = vips_lib.vips_interpolate_new(_to_bytes(name))
if vi == ffi.NULL:
raise Error(f'no such interpolator {name}')
return Interpolate(vi)
__all__ = ['Interpolate']
python-pyvips-3.1.1/pyvips/vobject.py 0000664 0000000 0000000 00000007734 15222163673 0017747 0 ustar 00root root 0000000 0000000 # wrap VipsObject
import logging
import pyvips
from pyvips import ffi, vips_lib, gobject_lib, Error, _to_bytes, _to_string
logger = logging.getLogger(__name__)
class VipsObject(pyvips.GObject):
"""Manage a VipsObject."""
__slots__ = ('vobject', 'gobject')
_pspec_cache = {}
def __init__(self, pointer):
# logger.debug('VipsObject.__init__: pointer = %s', pointer)
super(VipsObject, self).__init__(pointer)
self.vobject = ffi.cast('VipsObject*', pointer)
self.gobject = ffi.cast('GObject*', pointer)
@staticmethod
def print_all():
"""Print all objects.
Print a table of all active libvips objects. Handy for debugging.
"""
vips_lib.vips_object_print_all()
def _get_pspec(self, name):
# logger.debug('VipsObject.get_typeof: self = %s, name = %s',
# str(self), name)
# this is pretty slow, and used a lot, so we cache results
# this cache makes the libvips test suite about 10% faster
class_pointer = self.gobject.g_type_instance.g_class
cache = VipsObject._pspec_cache
if class_pointer not in cache:
cache[class_pointer] = {}
if name not in cache[class_pointer]:
pspec = ffi.new('GParamSpec **')
argument_class = ffi.new('VipsArgumentClass **')
argument_instance = ffi.new('VipsArgumentInstance **')
result = vips_lib.vips_object_get_argument(self.vobject,
_to_bytes(name),
pspec, argument_class,
argument_instance)
if result != 0:
return None
cache[class_pointer][name] = pspec[0]
return cache[class_pointer][name]
def get_typeof(self, name):
"""Get the GType of a GObject property.
This function returns 0 if the property does not exist.
"""
# logger.debug('VipsObject.get_typeof: self = %s, name = %s',
# str(self), name)
pspec = self._get_pspec(name)
if pspec is None:
# need to clear any error, this is horrible
Error('')
return 0
return pspec.value_type
def get_blurb(self, name):
"""Get the blurb for a GObject property."""
c_str = gobject_lib.g_param_spec_get_blurb(self._get_pspec(name))
return _to_string(c_str)
def get(self, name):
"""Get a GObject property.
The value of the property is converted to a Python value.
"""
logger.debug('VipsObject.get: name = %s', name)
pspec = self._get_pspec(name)
if pspec is None:
raise Error('Property not found.')
gtype = pspec.value_type
gv = pyvips.GValue()
gv.set_type(gtype)
go = ffi.cast('GObject *', self.pointer)
gobject_lib.g_object_get_property(go, _to_bytes(name), gv.pointer)
return gv.get()
def set(self, name, value):
"""Set a GObject property.
The value is converted to the property type, if possible.
"""
logger.debug('VipsObject.set: name = %s, value = %s', name, value)
gtype = self.get_typeof(name)
gv = pyvips.GValue()
gv.set_type(gtype)
gv.set(value)
go = ffi.cast('GObject *', self.pointer)
gobject_lib.g_object_set_property(go, _to_bytes(name), gv.pointer)
def set_string(self, string_options):
"""Set a series of properties using a string.
For example::
'fred=12, tile'
'[fred=12]'
"""
cstr = _to_bytes(string_options)
result = vips_lib.vips_object_set_from_string(self.vobject, cstr)
return result == 0
def get_description(self):
"""Get the description of a GObject."""
return _to_string(vips_lib.vips_object_get_description(self.vobject))
__all__ = ['VipsObject']
python-pyvips-3.1.1/pyvips/voperation.py 0000664 0000000 0000000 00000047741 15222163673 0020503 0 ustar 00root root 0000000 0000000 import logging
import pyvips
from pyvips import ffi, vips_lib, Error, _to_bytes, _to_string, GValue, \
type_map, type_from_name, nickname_find, at_least_libvips
logger = logging.getLogger(__name__)
# values for VipsArgumentFlags
_REQUIRED = 1
_CONSTRUCT = 2
_SET_ONCE = 4
_SET_ALWAYS = 8
_INPUT = 16
_OUTPUT = 32
_DEPRECATED = 64
_MODIFY = 128
# for VipsOperationFlags
_OPERATION_NOCACHE = 4
_OPERATION_DEPRECATED = 8
class Introspect(object):
"""Build introspection data for operations.
Make an operation, introspect it, and build a structure representing
everything we know about it.
"""
__slots__ = ('description', 'flags', 'details',
'required_input', 'optional_input',
'required_output', 'optional_output',
'doc_optional_input', 'doc_optional_output',
'member_x', 'method_args')
def __init__(self, operation_name):
op = Operation.new_from_name(operation_name)
self.description = op.get_description()
self.flags = vips_lib.vips_operation_get_flags(op.pointer)
# build a list of constructor arg [name, flags] pairs in arg order
arguments = []
def add_args(name, flags):
if (flags & _CONSTRUCT) != 0:
# libvips uses '-' to separate parts of arg names, but we
# need '_' for Python
name = name.replace('-', '_')
arguments.append([name, flags])
if at_least_libvips(8, 7):
p_names = ffi.new('char**[1]')
p_flags = ffi.new('int*[1]')
p_n_args = ffi.new('int[1]')
result = vips_lib.vips_object_get_args(op.vobject,
p_names, p_flags, p_n_args)
if result != 0:
raise Error('unable to get arguments from operation')
p_names = p_names[0]
p_flags = p_flags[0]
n_args = p_n_args[0]
for i in range(0, n_args):
add_args(_to_string(p_names[i]), p_flags[i])
else:
def add_construct(self, pspec, argument_class,
argument_instance, a, b):
add_args(_to_string(pspec.name), argument_class.flags)
return ffi.NULL
cb = ffi.callback('VipsArgumentMapFn', add_construct)
vips_lib.vips_argument_map(op.vobject, cb, ffi.NULL, ffi.NULL)
# logger.debug('arguments = %s', self.arguments)
# build a hash from arg name to detailed arg information
self.details = {}
for name, flags in arguments:
self.details[name] = {
"name": name,
"flags": flags,
"blurb": op.get_blurb(name),
"type": op.get_typeof(name)
}
# lists of arg names by category
self.required_input = []
self.optional_input = []
self.required_output = []
self.optional_output = []
# same, but with deprecated args filtered out ... this is the set we
# show in documentation
self.doc_optional_input = []
self.doc_optional_output = []
for name, flags in arguments:
if ((flags & _INPUT) != 0 and
(flags & _REQUIRED) != 0 and
(flags & _DEPRECATED) == 0):
self.required_input.append(name)
# required inputs which we MODIFY are also required outputs
if (flags & _MODIFY) != 0:
self.required_output.append(name)
if ((flags & _OUTPUT) != 0 and
(flags & _REQUIRED) != 0 and
(flags & _DEPRECATED) == 0):
self.required_output.append(name)
# deprecated optional args get on to the main arg lists, but are
# filtered from the documented set
if ((flags & _INPUT) != 0 and
(flags & _REQUIRED) == 0):
self.optional_input.append(name)
if (flags & _DEPRECATED) == 0:
self.doc_optional_input.append(name)
if ((flags & _OUTPUT) != 0 and
(flags & _REQUIRED) == 0):
self.optional_output.append(name)
if (flags & _DEPRECATED) == 0:
self.doc_optional_output.append(name)
# find the first required input image arg, if any ... that will be self
self.member_x = None
for name in self.required_input:
details = self.details[name]
if details['type'] == GValue.image_type:
self.member_x = name
break
# method args are required args, but without the image they are a
# method on
if self.member_x is not None:
self.method_args = list(self.required_input)
self.method_args.remove(self.member_x)
else:
self.method_args = self.required_input
# a hash mapping operation names to introspection data
_introspect_cache = {}
@classmethod
def get(cls, operation_name):
if operation_name not in cls._introspect_cache:
cls._introspect_cache[operation_name] = Introspect(operation_name)
return cls._introspect_cache[operation_name]
# search an array with a predicate, recursing into subarrays as we see them
# used to find the match_image for an operation
def _find_inside(pred, thing):
if pred(thing):
return thing
if isinstance(thing, list) or isinstance(thing, tuple):
for x in thing:
result = _find_inside(pred, x)
if result is not None:
return result
return None
class Operation(pyvips.VipsObject):
"""Call libvips operations.
This class wraps the libvips VipsOperation class.
"""
__slots__ = ()
# cache nickname -> docstring here
_docstring_cache = {}
def __init__(self, pointer):
# logger.debug('Operation.__init__: pointer = %s', pointer)
super(Operation, self).__init__(pointer)
@staticmethod
def new_from_name(operation_name):
vop = vips_lib.vips_operation_new(_to_bytes(operation_name))
if vop == ffi.NULL:
raise Error(f'no such operation {operation_name}')
return Operation(vop)
def set(self, name, flags, match_image, value):
# if the object wants an image and we have a constant, _imageize it
#
# if the object wants an image array, _imageize any constants in the
# array
if match_image:
gtype = self.get_typeof(name)
if gtype == pyvips.GValue.image_type:
value = pyvips.Image._imageize(match_image, value)
elif gtype == pyvips.GValue.array_image_type:
value = [pyvips.Image._imageize(match_image, x)
for x in value]
# MODIFY args need to be copied before they are set
if (flags & _MODIFY) != 0:
# logger.debug('copying MODIFY arg %s', name)
# make sure we have a unique copy
value = value.copy().copy_memory()
super(Operation, self).set(name, value)
@staticmethod
def call(operation_name, *args, **kwargs):
"""Call a libvips operation.
Use this method to call any libvips operation. For example::
black_image = pyvips.Operation.call('black', 10, 10)
See the Introduction for notes on how this works.
"""
logger.debug('VipsOperation.call: operation_name = %s', operation_name)
# logger.debug('VipsOperation.call: args = %s, kwargs =%s',
# args, kwargs)
intro = Introspect.get(operation_name)
if len(intro.required_input) != len(args):
raise Error(f'{operation_name} needs {len(intro.required_input)} '
f'arguments, but {len(args)} given')
op = Operation.new_from_name(operation_name)
# set any string options before any args so they can't be
# overridden
string_options = kwargs.pop('string_options', '')
if not op.set_string(string_options):
raise Error(f'unable to call {operation_name}')
# the first image argument is the thing we expand constants to
# match ... look inside tables for images, since we may be passing
# an array of images as a single param
match_image = _find_inside(lambda x: isinstance(x, pyvips.Image),
args)
logger.debug('VipsOperation.call: match_image = %s', match_image)
# collect a list of all input references here
# we can't use a set because set elements are unique under "==", and
# Python checks memoryview equality with hash functions, not pointer
# equality
references = []
# does a list contain an element using pointer equality
# we can't use "in" since that uses "==", which means hash equality
def contains(array, x):
for y in array:
if id(x) == id(y):
return True
return False
def add_reference(x):
if isinstance(x, pyvips.Image):
for i in x._references:
if not contains(references, i):
references.append(i)
return False
# set required input args
for name, value in zip(intro.required_input, args):
_find_inside(add_reference, value)
op.set(name, intro.details[name]['flags'], match_image, value)
# set any optional args
for name in kwargs:
if (name not in intro.optional_input and
name not in intro.optional_output):
raise Error(f'{operation_name} does not support optional '
f'argument {name}')
value = kwargs[name]
details = intro.details[name]
if (details['flags'] & _DEPRECATED) != 0:
logger.info('%s argument %s is deprecated',
operation_name, name)
_find_inside(add_reference, value)
op.set(name, details['flags'], match_image, value)
# build operation
vop = vips_lib.vips_cache_operation_build(op.pointer)
if vop == ffi.NULL:
vips_lib.vips_object_unref_outputs(op.vobject)
raise Error(f'unable to call {operation_name}')
op = Operation(vop)
# attach all input refs to output x
def set_reference(x):
if isinstance(x, pyvips.Image):
x._references.extend(references)
return False
# fetch required output args (plus modified input images)
result = []
for name in intro.required_output:
value = op.get(name)
_find_inside(set_reference, value)
result.append(value)
# fetch optional output args
opts = {}
for name in intro.optional_output:
if name in kwargs:
value = op.get(name)
_find_inside(set_reference, value)
opts[name] = value
if len(opts) > 0:
result.append(opts)
vips_lib.vips_object_unref_outputs(op.vobject)
if len(result) == 0:
result = None
elif len(result) == 1:
result = result[0]
logger.debug('VipsOperation.call: result = %s', result)
return result
@staticmethod
def generate_docstring(operation_name):
"""Make a google-style docstring.
This is used to generate help() output.
"""
# we cache these to save regeneration
if operation_name in Operation._docstring_cache:
return Operation._docstring_cache[operation_name]
intro = Introspect.get(operation_name)
if (intro.flags & _OPERATION_DEPRECATED) != 0:
raise Error('No such operator.',
f'operator "{operation_name}" is deprecated')
result = intro.description[0].upper() + intro.description[1:] + '.\n\n'
result += 'Example:\n'
result += ' ' + ', '.join(intro.required_output) + ' = '
if intro.member_x is not None:
result += intro.member_x + '.' + operation_name + '('
else:
result += 'pyvips.Image.' + operation_name + '('
args = []
args += intro.method_args
args += [x + '=' + GValue.gtype_to_python(intro.details[x]['type'])
for x in intro.doc_optional_input]
args += [x + '=bool'
for x in intro.doc_optional_output]
result += ", ".join(args) + ')\n'
def argstr(name):
details = intro.details[name]
return (u' {0} ({1}): {2}\n'.
format(name,
GValue.gtype_to_python(details['type']),
details['blurb']))
result += '\nReturns:\n'
for name in intro.required_output:
result += argstr(name)
result += '\nArgs:\n'
if intro.member_x is not None:
result += argstr(intro.member_x)
for name in intro.method_args:
result += argstr(name)
if len(intro.doc_optional_input) > 0:
result += '\nKeyword args:\n'
for name in intro.doc_optional_input:
result += argstr(name)
if len(intro.doc_optional_output) > 0:
result += '\nOther Parameters:\n'
for name in intro.doc_optional_output:
result += argstr(name)
result += '\nRaises:\n :class:`.Error`\n'
# add to cache to save building again
Operation._docstring_cache[operation_name] = result
return result
@staticmethod
def generate_sphinx(operation_name):
"""Make a sphinx-style docstring.
This is used to generate the off-line docs.
"""
intro = Introspect.get(operation_name)
if (intro.flags & _OPERATION_DEPRECATED) != 0:
raise Error('No such operator.',
f'operator "{operation_name}" is deprecated')
# drop "revalidate" flag from buffer loaders and operations marked
# "nocache" as they are already uncached
doc_optional_input = [name for name in intro.doc_optional_input if
name != 'revalidate' or
('_buffer' not in operation_name and
(intro.flags & _OPERATION_NOCACHE) == 0)]
if intro.member_x is not None:
result = '.. method:: '
else:
result = '.. staticmethod:: '
args = []
args += intro.method_args
args += [x + '=' + GValue.gtype_to_python(intro.details[x]['type'])
for x in doc_optional_input]
args += [x + '=bool'
for x in intro.doc_optional_output]
result += operation_name + '(' + ", ".join(args) + ')\n\n'
result += intro.description[0].upper() + \
intro.description[1:] + '.\n\n'
result += 'Example:\n'
result += ' '
if len(intro.required_output) > 0:
result += ', '.join(intro.required_output) + ' = '
if intro.member_x is not None:
result += intro.member_x + "." + operation_name + '('
else:
result += 'pyvips.Image.' + operation_name + '('
args = []
args += intro.method_args
args += [x + '=' + GValue.gtype_to_python(intro.details[x]['type'])
for x in doc_optional_input]
result += ', '.join(args)
result += ')\n\n'
for name in intro.method_args + doc_optional_input:
details = intro.details[name]
result += f':param {name}: {details["blurb"]}\n'
result += (f':type {name}: '
f'{GValue.gtype_to_python(details["type"])}\n')
for name in intro.doc_optional_output:
result += (f':param {name}: '
f'enable output: {intro.details[name]["blurb"]}\n')
result += f':type {name}: bool\n'
output_types = [GValue.gtype_to_python(intro.details[name]['type'])
for name in intro.required_output]
if len(output_types) == 1:
output_type = output_types[0]
else:
output_type = 'list[' + ', '.join(output_types) + ']'
if len(intro.doc_optional_output) > 0:
output_types += ['Dict[str, mixed]']
output_type += ' or list[' + ', '.join(output_types) + ']'
result += ':rtype: ' + output_type + '\n'
result += ':raises Error:\n'
return result
@staticmethod
def generate_sphinx_all():
"""Generate sphinx documentation.
This generates a .rst file for all auto-generated image methods. Use it
to regenerate the docs with something like::
$ python -c \
"import pyvips; pyvips.Operation.generate_sphinx_all()" > x
And copy-paste the file contents into doc/vimage.rst in the appropriate
place.
"""
# these names are aliased
alias = ["crop"]
alias_gtypes = {}
for name in alias:
gtype = pyvips.type_find("VipsOperation", name)
alias_gtypes[gtype] = name
# all names we can generate docstrings for
all_names = []
def add_name(gtype, a, b):
if gtype in alias_gtypes:
name = alias_gtypes[gtype]
else:
name = nickname_find(gtype)
try:
Operation.generate_sphinx(name)
all_names.append(name)
except Error:
pass
type_map(gtype, add_name)
return ffi.NULL
type_map(type_from_name('VipsOperation'), add_name)
all_names.sort()
# remove operations we have to wrap by hand
exclude = ['scale', 'ifthenelse', 'bandjoin', 'bandrank']
all_names = [x for x in all_names if x not in exclude]
# Output summary table
print('.. class:: Image')
print(' :noindex:\n')
print(' .. rubric:: Methods\n')
print(' .. autosummary::')
print(' :nosignatures:\n')
for name in all_names:
print(f' ~{name}')
print()
# Output docs
print()
for name in all_names:
docstr = Operation.generate_sphinx(name)
docstr = docstr.replace('\n', '\n ')
print(' ' + docstr)
def cache_set_max(mx):
"""Set the maximum number of operations libvips will cache."""
vips_lib.vips_cache_set_max(mx)
def cache_set_max_mem(mx):
"""Limit the operation cache by memory use."""
vips_lib.vips_cache_set_max_mem(mx)
def cache_set_max_files(mx):
"""Limit the operation cache by number of open files."""
vips_lib.vips_cache_set_max_files(mx)
def cache_set_trace(trace):
"""Turn on libvips cache tracing."""
vips_lib.vips_cache_set_trace(trace)
def cache_get_max():
"""Get the maximum number of operations libvips will cache."""
return vips_lib.vips_cache_get_max()
def cache_get_size():
"""Get the current size of the operations cache."""
return vips_lib.vips_cache_get_size()
def cache_get_max_mem():
"""Get the operation cache limit by memory use."""
return vips_lib.vips_cache_get_max_mem()
def cache_get_max_files():
"""Get the operation cache limit by number of open files."""
return vips_lib.vips_cache_get_max_files()
def block_untrusted_set(state):
"""Set the block state for all untrusted operations."""
if at_least_libvips(8, 13):
vips_lib.vips_block_untrusted_set(state)
def operation_block_set(name, state):
"""Set the block state for a named operation."""
if at_least_libvips(8, 13):
vips_lib.vips_operation_block_set(_to_bytes(name), state)
__all__ = [
'Introspect',
'Operation',
'cache_set_max',
'cache_set_max_mem',
'cache_set_max_files',
'cache_set_trace',
'cache_get_max',
'cache_get_max_mem',
'cache_get_max_files',
'cache_get_size',
'block_untrusted_set',
'operation_block_set'
]
python-pyvips-3.1.1/pyvips/vregion.py 0000664 0000000 0000000 00000003322 15222163673 0017751 0 ustar 00root root 0000000 0000000 # wrap VipsRegion
import pyvips
from pyvips import ffi, glib_lib, vips_lib, Error, at_least_libvips
class Region(pyvips.VipsObject):
"""Wrap a VipsRegion object.
"""
def __init__(self, pointer):
# logger.debug('Image.__init__: pointer = %s', pointer)
super(Region, self).__init__(pointer)
# constructors
@staticmethod
def new(image):
"""Make a region on an image.
Returns:
A new :class:`.Region`.
Raises:
:class:`.Error`
"""
pointer = vips_lib.vips_region_new(image.pointer)
if pointer == ffi.NULL:
raise Error('unable to make region')
return pyvips.Region(pointer)
def width(self):
"""Width of pixels held by region."""
if not at_least_libvips(8, 8):
raise Error('libvips too old')
return vips_lib.vips_region_width(self.pointer)
def height(self):
"""Height of pixels held by region."""
if not at_least_libvips(8, 8):
raise Error('libvips too old')
return vips_lib.vips_region_height(self.pointer)
def fetch(self, x, y, w, h):
"""Fill a region with pixel data.
Pixels are filled with data!
Returns:
Pixel data.
Raises:
:class:`.Error`
"""
if not at_least_libvips(8, 8):
raise Error('libvips too old')
psize = ffi.new('size_t *')
pointer = vips_lib.vips_region_fetch(self.pointer, x, y, w, h, psize)
if pointer == ffi.NULL:
raise Error('unable to fetch from region')
pointer = ffi.gc(pointer, glib_lib.g_free)
return ffi.buffer(pointer, psize[0])
__all__ = ['Region']
python-pyvips-3.1.1/pyvips/vsource.py 0000664 0000000 0000000 00000005243 15222163673 0017772 0 ustar 00root root 0000000 0000000 import logging
import pyvips
from pyvips import ffi, vips_lib, Error, _to_bytes
logger = logging.getLogger(__name__)
class Source(pyvips.Connection):
"""An input connection.
"""
def __init__(self, pointer):
# logger.debug('Operation.__init__: pointer = %s', pointer)
super(Source, self).__init__(pointer)
@staticmethod
def new_from_descriptor(descriptor):
"""Make a new source from a file descriptor (a small integer).
Make a new source that is attached to the descriptor. For example::
source = pyvips.Source.new_from_descriptor(0)
Makes a descriptor attached to stdin.
You can pass this source to (for example) :meth:`new_from_source`.
"""
# logger.debug('VipsSource.new_from_descriptor: descriptor = %d',
# descriptor)
# sources are mutable, so we can't use the cache
pointer = vips_lib.vips_source_new_from_descriptor(descriptor)
if pointer == ffi.NULL:
raise Error(f"can't create source from descriptor {descriptor}")
return Source(pointer)
@staticmethod
def new_from_file(filename):
"""Make a new source from a filename.
Make a new source that is attached to the named file. For example::
source = pyvips.Source.new_from_file("myfile.jpg")
You can pass this source to (for example) :meth:`new_from_source`.
"""
# logger.debug('VipsSource.new_from_file: filename = %s',
# filename)
pointer = vips_lib.vips_source_new_from_file(_to_bytes(filename))
if pointer == ffi.NULL:
raise Error(f"can't create source from filename {filename}")
return Source(pointer)
@staticmethod
def new_from_memory(data):
"""Make a new source from a memory object.
Make a new source that is attached to the memory object. For example::
source = pyvips.Source.new_from_memory("myfile.jpg")
You can pass this source to (for example) :meth:`new_from_source`.
The memory object can be anything that supports the Python buffer or
memoryview protocol.
"""
# logger.debug('VipsSource.new_from_memory:')
start = ffi.from_buffer(data)
nbytes = data.nbytes if hasattr(data, 'nbytes') else len(data)
pointer = vips_lib.vips_source_new_from_memory(start, nbytes)
if pointer == ffi.NULL:
raise Error("can't create input source from memory")
source = Source(pointer)
# keep a secret reference to the input data to make sure it's not GCed
source._references = [data]
return source
__all__ = ['Source']
python-pyvips-3.1.1/pyvips/vsourcecustom.py 0000664 0000000 0000000 00000003476 15222163673 0021233 0 ustar 00root root 0000000 0000000 import logging
import pyvips
from pyvips import ffi, vips_lib
logger = logging.getLogger(__name__)
class SourceCustom(pyvips.Source):
"""Custom sources allow reading data from otherwise unsupported sources.
Requires libvips `>= 8.9.0`.
To use, create a SourceCustom object, then provide callbacks to
:meth:`on_read` and :meth:`on_seek`.
"""
def __init__(self):
"""Make a new custom source.
You can pass this source to (for example) :meth:`new_from_source`.
"""
source = ffi.cast('VipsSource*', vips_lib.vips_source_custom_new())
super(SourceCustom, self).__init__(source)
def on_read(self, handler):
"""Attach a read handler.
The interface is exactly as io.read(). The handler is given a number
of bytes to fetch, and should return a bytes-like object containing up
to that number of bytes. If there is no more data available, it should
return None.
"""
def interface_handler(buf):
chunk = handler(len(buf))
if chunk is None:
return 0
bytes_read = len(chunk)
buf[:bytes_read] = chunk
return bytes_read
self.signal_connect("read", interface_handler)
def on_seek(self, handler):
"""Attach a seek handler.
The interface is the same as io.seek(), so the handler is passed
parameters for offset and whence with the same meanings.
However, the handler MUST return the new seek position. A simple way
to do this is to call io.tell() and return that result.
Seek handlers are optional. If you do not set one, your source will be
treated as unseekable and libvips will do extra caching.
"""
self.signal_connect("seek", handler)
__all__ = ['SourceCustom']
python-pyvips-3.1.1/pyvips/vtarget.py 0000664 0000000 0000000 00000004634 15222163673 0017763 0 ustar 00root root 0000000 0000000 import logging
import pyvips
from pyvips import ffi, vips_lib, Error, _to_bytes
logger = logging.getLogger(__name__)
class Target(pyvips.Connection):
"""An output connection.
"""
def __init__(self, pointer):
# logger.debug('Operation.__init__: pointer = %s', pointer)
super(Target, self).__init__(pointer)
@staticmethod
def new_to_descriptor(descriptor):
"""Make a new target to write to a file descriptor (a small
integer).
Make a new target that is attached to the descriptor. For example::
target = pyvips.Target.new_to_descriptor(1)
Makes a descriptor attached to stdout.
You can pass this target to (for example) :meth:`write_to_target`.
"""
# logger.debug('VipsTarget.new_to_descriptor: descriptor = %d',
# descriptor)
# targets are mutable, so we can't use the cache
pointer = vips_lib.vips_target_new_to_descriptor(descriptor)
if pointer == ffi.NULL:
raise Error(f"can't create output target from descriptor "
f'{descriptor}')
return Target(pointer)
@staticmethod
def new_to_file(filename):
"""Make a new target to write to a file.
Make a new target that will write to the named file. For example::
target = pyvips.Target.new_to_file("myfile.jpg")
You can pass this target to (for example) :meth:`write_to_target`.
"""
# logger.debug('VipsTarget.new_to_file: filename = %s', filename)
pointer = vips_lib.vips_target_new_to_file(_to_bytes(filename))
if pointer == ffi.NULL:
raise Error(f"can't create output target from filename {filename}")
return Target(pointer)
@staticmethod
def new_to_memory():
"""Make a new target to write to an area of memory.
Make a new target that will write to memory. For example::
target = pyvips.Target.new_to_memory()
You can pass this target to (for example) :meth:`write_to_target`.
After writing to the target, fetch the bytes from the target object
with `target.get("blob")`.
"""
# logger.debug('VipsTarget.new_to_memory:')
pointer = vips_lib.vips_target_new_to_memory()
if pointer == ffi.NULL:
raise Error("can't create output target from memory")
return Target(pointer)
__all__ = ['Target']
python-pyvips-3.1.1/pyvips/vtargetcustom.py 0000664 0000000 0000000 00000006073 15222163673 0021215 0 ustar 00root root 0000000 0000000 import logging
import pyvips
from pyvips import ffi, vips_lib, at_least_libvips
logger = logging.getLogger(__name__)
class TargetCustom(pyvips.Target):
"""An output target you can connect action signals to to implement
behaviour.
"""
def __init__(self):
"""Make a new target you can customise.
You can pass this target to (for example) :meth:`write_to_target`.
"""
target = ffi.cast('VipsTarget*', vips_lib.vips_target_custom_new())
super(TargetCustom, self).__init__(target)
def on_write(self, handler):
"""Attach a write handler.
The interface is exactly as io.write(). The handler is given a
bytes-like object to write, and should return the number of bytes
written.
"""
def interface_handler(buf):
return handler(buf)
self.signal_connect("write", interface_handler)
def on_read(self, handler):
"""Attach a read handler.
The interface is exactly as io.read(). The handler is given a number
of bytes to fetch, and should return a bytes-like object containing up
to that number of bytes. If there is no more data available, it should
return None.
Read handlers are optional for targets. If you do not set one, your
target will be treated as unreadable and libvips will be unable to
write some file types (just TIFF, as of the time of writing).
"""
def interface_handler(buf):
chunk = handler(len(buf))
if chunk is None:
return 0
bytes_read = len(chunk)
buf[:bytes_read] = chunk
return bytes_read
if at_least_libvips(8, 13):
self.signal_connect("read", interface_handler)
def on_seek(self, handler):
"""Attach a seek handler.
The interface is the same as io.seek(), so the handler is passed
parameters for offset and whence with the same meanings.
However, the handler MUST return the new seek position. A simple way
to do this is to call io.tell() and return that result.
Seek handlers are optional. If you do not set one, your target will be
treated as unseekable and libvips will be unable to write some file
types (just TIFF, as of the time of writing).
"""
if at_least_libvips(8, 13):
self.signal_connect("seek", handler)
def on_end(self, handler):
"""Attach an end handler.
This optional handler is called at the end of write. It should do any
cleaning up necessary, and return 0 on success and -1 on error.
"""
if not at_least_libvips(8, 13):
# fall back for older libvips
self.on_finish(handler)
else:
self.signal_connect("end", handler)
def on_finish(self, handler):
"""Attach a finish handler.
For libvips 8.13 and later, this method is deprecated in favour of
:meth:`on_end`.
"""
self.signal_connect("finish", handler)
__all__ = ['TargetCustom']
python-pyvips-3.1.1/setup.py 0000664 0000000 0000000 00000001251 15222163673 0016105 0 ustar 00root root 0000000 0000000 import sys
from os import path
from setuptools import setup
base_dir = path.dirname(__file__)
src_dir = path.join(base_dir, 'pyvips')
# When executing the setup.py, we need to be able to import ourselves, this
# means that we need to add the pyvips/ directory to the sys.path.
sys.path.insert(0, src_dir)
# Try to install in API mode first, then if that fails, fall back to ABI
# API mode requires a working C compiler plus all the libvips headers whereas
# ABI only needs the libvips shared library to be on the system
try:
setup(cffi_modules=['pyvips/pyvips_build.py:ffibuilder'])
except Exception as e:
print(f'Falling back to ABI mode. Details: {e}')
setup()
python-pyvips-3.1.1/tests/ 0000775 0000000 0000000 00000000000 15222163673 0015536 5 ustar 00root root 0000000 0000000 python-pyvips-3.1.1/tests/__init__.py 0000664 0000000 0000000 00000000000 15222163673 0017635 0 ustar 00root root 0000000 0000000 python-pyvips-3.1.1/tests/conftest.py 0000664 0000000 0000000 00000000132 15222163673 0017731 0 ustar 00root root 0000000 0000000 import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'helpers'))
python-pyvips-3.1.1/tests/helpers/ 0000775 0000000 0000000 00000000000 15222163673 0017200 5 ustar 00root root 0000000 0000000 python-pyvips-3.1.1/tests/helpers/helpers.py 0000664 0000000 0000000 00000010157 15222163673 0021220 0 ustar 00root root 0000000 0000000 # vim: set fileencoding=utf-8 :
# test helpers
import os
import tempfile
import pytest
import pyvips
IMAGES = os.path.join(os.path.dirname(__file__), os.pardir, 'images')
JPEG_FILE = os.path.join(IMAGES, "sample.jpg")
WEBP_FILE = os.path.join(IMAGES, "sample.webp")
SVG_FILE = os.path.join(IMAGES, "logo.svg")
UHDR_FILE = os.path.join(IMAGES, "ultra-hdr.jpg")
# an expanding zip ... if either of the args is a scalar or a one-element list,
# duplicate it down the other side
def zip_expand(x, y):
# handle singleton list case
if isinstance(x, list) and len(x) == 1:
x = x[0]
if isinstance(y, list) and len(y) == 1:
y = y[0]
if isinstance(x, list) and isinstance(y, list):
return list(zip(x, y))
elif isinstance(x, list):
return [[i, y] for i in x]
elif isinstance(y, list):
return [[x, j] for j in y]
else:
return [[x, y]]
# run a 1-ary function on a thing -- loop over elements if the
# thing is a list
def run_fn(fn, x):
if isinstance(x, list):
return [fn(i) for i in x]
else:
return fn(x)
# make a temp filename with the specified suffix and in the
# specified directory
def temp_filename(directory, suffix):
temp_name = next(tempfile._get_candidate_names())
filename = os.path.join(directory, temp_name + suffix)
return filename
# test for an operator exists
def have(name):
return pyvips.type_find("VipsOperation", name) != 0
# use as @skip_if_no('jpegload')
def skip_if_no(operator_name):
return pytest.mark.skipif(not have(operator_name),
reason=('no {}, skipping test'.
format(operator_name)))
# run a 2-ary function on two things -- loop over elements pairwise if the
# things are lists
def run_fn2(fn, x, y):
if isinstance(x, pyvips.Image) or isinstance(y, pyvips.Image):
return fn(x, y)
elif isinstance(x, list) or isinstance(y, list):
return [fn(i, j) for i, j in zip_expand(x, y)]
else:
return fn(x, y)
# test a pair of things which can be lists for approx. equality
def assert_almost_equal_objects(a, b, threshold=0.0001, msg=''):
# print(f'assertAlmostEqualObjects {a} = {b}')
assert all([pytest.approx(x, abs=threshold) == y
for x, y in zip_expand(a, b)]), msg
# test a pair of things which can be lists for equality
def assert_equal_objects(a, b, msg=''):
# print(f'assertEqualObjects {a} = {b}')
assert all([x == y for x, y in zip_expand(a, b)]), msg
# test a pair of things which can be lists for difference less than a
# threshold
def assert_less_threshold(a, b, diff):
assert all([abs(x - y) < diff for x, y in zip_expand(a, b)])
# run a function on an image and on a single pixel, the results
# should match
def run_cmp(message, im, x, y, fn):
a = im(x, y)
v1 = fn(a)
im2 = fn(im)
v2 = im2(x, y)
assert_almost_equal_objects(v1, v2, msg=message)
# run a function on an image,
# 50,50 and 10,10 should have different values on the test image
def run_image(message, im, fn):
run_cmp(message, im, 50, 50, fn)
run_cmp(message, im, 10, 10, fn)
# run a function on (image, constant), and on (constant, image).
# 50,50 and 10,10 should have different values on the test image
def run_const(message, fn, im, c):
run_cmp(message, im, 50, 50, lambda x: run_fn2(fn, x, c))
run_cmp(message, im, 50, 50, lambda x: run_fn2(fn, c, x))
run_cmp(message, im, 10, 10, lambda x: run_fn2(fn, x, c))
run_cmp(message, im, 10, 10, lambda x: run_fn2(fn, c, x))
# run a function on a pair of images and on a pair of pixels, the results
# should match
def run_cmp2(message, left, right, x, y, fn):
a = left(x, y)
b = right(x, y)
v1 = fn(a, b)
after = fn(left, right)
v2 = after(x, y)
assert_almost_equal_objects(v1, v2, msg=message)
# run a function on a pair of images
# 50,50 and 10,10 should have different values on the test image
def run_image2(message, left, right, fn):
run_cmp2(message, left, right, 50, 50,
lambda x, y: run_fn2(fn, x, y))
run_cmp2(message, left, right, 10, 10,
lambda x, y: run_fn2(fn, x, y))
python-pyvips-3.1.1/tests/images/ 0000775 0000000 0000000 00000000000 15222163673 0017003 5 ustar 00root root 0000000 0000000 python-pyvips-3.1.1/tests/images/logo.svg 0000664 0000000 0000000 00000011134 15222163673 0020464 0 ustar 00root root 0000000 0000000
python-pyvips-3.1.1/tests/images/sample.jpg 0000664 0000000 0000000 00000540673 15222163673 0021005 0 ustar 00root root 0000000 0000000 ÿØÿáäExif MM *
ª Ê Ð ä ì( 1 ô2 <