matplotlib-rs 0.0.8__cp315-cp315-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- docs/releases/0.0.1.md +268 -0
- docs/releases/0.0.2.md +69 -0
- docs/releases/0.0.3.md +80 -0
- docs/releases/0.0.4.md +73 -0
- docs/releases/0.0.5.md +24 -0
- docs/releases/0.0.6.md +24 -0
- docs/releases/0.0.7.md +24 -0
- docs/releases/0.0.8.md +16 -0
- licenses/LICENSE_CONTOURPY +29 -0
- licenses/LICENSE_CYCLER +27 -0
- licenses/LICENSE_DATEUTIL +54 -0
- licenses/LICENSE_KIWISOLVER +71 -0
- licenses/LICENSE_LIBWEBP +56 -0
- licenses/LICENSE_MATPLOTLIB +1253 -0
- licenses/LICENSE_PYPARSING +20 -0
- licenses/LICENSE_QHULL +39 -0
- licenses/LICENSE_SIX +18 -0
- matplotlib_rs/__init__.py +1683 -0
- matplotlib_rs/__main__.py +27 -0
- matplotlib_rs/_afm.py +500 -0
- matplotlib_rs/_animation_data.py +263 -0
- matplotlib_rs/_api/__init__.py +495 -0
- matplotlib_rs/_api/deprecation.py +534 -0
- matplotlib_rs/_axis_py.py +2991 -0
- matplotlib_rs/_blocking_input.py +31 -0
- matplotlib_rs/_cm.py +1500 -0
- matplotlib_rs/_cm_bivar.py +1289 -0
- matplotlib_rs/_cm_listed.py +2848 -0
- matplotlib_rs/_cm_multivar.py +167 -0
- matplotlib_rs/_color_data.py +1142 -0
- matplotlib_rs/_colormap.py +132 -0
- matplotlib_rs/_constrained_layout.py +825 -0
- matplotlib_rs/_contour.py +108 -0
- matplotlib_rs/_doc_cache.py +12214 -0
- matplotlib_rs/_docstring.py +142 -0
- matplotlib_rs/_enums.py +178 -0
- matplotlib_rs/_figure_rs.py +294 -0
- matplotlib_rs/_fontconfig_pattern.py +129 -0
- matplotlib_rs/_foreign.py +220 -0
- matplotlib_rs/_hook.py +94 -0
- matplotlib_rs/_image.py +160 -0
- matplotlib_rs/_imageio.py +229 -0
- matplotlib_rs/_internal_utils.py +65 -0
- matplotlib_rs/_kiwi.py +484 -0
- matplotlib_rs/_layoutgrid.py +549 -0
- matplotlib_rs/_live.py +192 -0
- matplotlib_rs/_mathtext.py +3103 -0
- matplotlib_rs/_mathtext_data.py +1811 -0
- matplotlib_rs/_mplrs.cp315-win_amd64.pyd +0 -0
- matplotlib_rs/_path.py +25 -0
- matplotlib_rs/_png.py +162 -0
- matplotlib_rs/_pylab_helpers.py +137 -0
- matplotlib_rs/_qhull.py +66 -0
- matplotlib_rs/_rcpush.py +84 -0
- matplotlib_rs/_spines_rs.py +108 -0
- matplotlib_rs/_style_helpers.py +52 -0
- matplotlib_rs/_text_helpers.py +51 -0
- matplotlib_rs/_tight_bbox.py +85 -0
- matplotlib_rs/_tight_layout.py +302 -0
- matplotlib_rs/_tri.py +140 -0
- matplotlib_rs/_type1font.py +1228 -0
- matplotlib_rs/_vendor/__init__.py +8 -0
- matplotlib_rs/_vendor/cycler.py +574 -0
- matplotlib_rs/_vendor/dateutil/__init__.py +27 -0
- matplotlib_rs/_vendor/dateutil/_common.py +44 -0
- matplotlib_rs/_vendor/dateutil/_tzdata_impl.py +148 -0
- matplotlib_rs/_vendor/dateutil/_version.py +5 -0
- matplotlib_rs/_vendor/dateutil/easter.py +90 -0
- matplotlib_rs/_vendor/dateutil/parser/__init__.py +62 -0
- matplotlib_rs/_vendor/dateutil/parser/_parser.py +1614 -0
- matplotlib_rs/_vendor/dateutil/parser/isoparser.py +417 -0
- matplotlib_rs/_vendor/dateutil/relativedelta.py +597 -0
- matplotlib_rs/_vendor/dateutil/rrule.py +1765 -0
- matplotlib_rs/_vendor/dateutil/tz/__init__.py +61 -0
- matplotlib_rs/_vendor/dateutil/tz/_common.py +420 -0
- matplotlib_rs/_vendor/dateutil/tz/_factories.py +81 -0
- matplotlib_rs/_vendor/dateutil/tz/_tzfile.py +1429 -0
- matplotlib_rs/_vendor/dateutil/tz/_tzpath.py +105 -0
- matplotlib_rs/_vendor/dateutil/tz/tz.py +1473 -0
- matplotlib_rs/_vendor/dateutil/tz/win.py +371 -0
- matplotlib_rs/_vendor/dateutil/tzwin.py +3 -0
- matplotlib_rs/_vendor/dateutil/utils.py +72 -0
- matplotlib_rs/_vendor/dateutil/zoneinfo/__init__.py +234 -0
- matplotlib_rs/_vendor/pyparsing/__init__.py +414 -0
- matplotlib_rs/_vendor/pyparsing/actions.py +265 -0
- matplotlib_rs/_vendor/pyparsing/common.py +571 -0
- matplotlib_rs/_vendor/pyparsing/core.py +6973 -0
- matplotlib_rs/_vendor/pyparsing/exceptions.py +354 -0
- matplotlib_rs/_vendor/pyparsing/helpers.py +1770 -0
- matplotlib_rs/_vendor/pyparsing/results.py +929 -0
- matplotlib_rs/_vendor/pyparsing/testing.py +399 -0
- matplotlib_rs/_vendor/pyparsing/unicode.py +357 -0
- matplotlib_rs/_vendor/pyparsing/util.py +515 -0
- matplotlib_rs/_vendor/pyparsing/warnings.py +11 -0
- matplotlib_rs/_vendor/six.py +1004 -0
- matplotlib_rs/animation.py +1843 -0
- matplotlib_rs/artist.py +2302 -0
- matplotlib_rs/axes/__init__.py +19 -0
- matplotlib_rs/axes/_axes.py +9402 -0
- matplotlib_rs/axes/_bar.py +185 -0
- matplotlib_rs/axes/_base.py +5236 -0
- matplotlib_rs/axes/_base_rs.py +727 -0
- matplotlib_rs/axes/_boxplot.py +391 -0
- matplotlib_rs/axes/_hist.py +99 -0
- matplotlib_rs/axes/_secondary_axes.py +357 -0
- matplotlib_rs/axis.py +1963 -0
- matplotlib_rs/backend_bases.py +3760 -0
- matplotlib_rs/backend_managers.py +388 -0
- matplotlib_rs/backend_tools.py +1002 -0
- matplotlib_rs/backends/__init__.py +6 -0
- matplotlib_rs/backends/_backend_pdf_ps.py +451 -0
- matplotlib_rs/backends/backend_agg.py +552 -0
- matplotlib_rs/backends/backend_mixed.py +123 -0
- matplotlib_rs/backends/backend_pdf.py +2711 -0
- matplotlib_rs/backends/backend_pgf.py +1031 -0
- matplotlib_rs/backends/backend_ps.py +1491 -0
- matplotlib_rs/backends/backend_svg.py +1395 -0
- matplotlib_rs/backends/backend_template.py +214 -0
- matplotlib_rs/backends/registry.py +423 -0
- matplotlib_rs/bezier.py +691 -0
- matplotlib_rs/category.py +236 -0
- matplotlib_rs/cbook.py +2762 -0
- matplotlib_rs/cm.py +251 -0
- matplotlib_rs/collections.py +2711 -0
- matplotlib_rs/colorbar.py +1586 -0
- matplotlib_rs/colorizer.py +909 -0
- matplotlib_rs/colors.py +4278 -0
- matplotlib_rs/container.py +256 -0
- matplotlib_rs/contour.py +1756 -0
- matplotlib_rs/dates.py +1847 -0
- matplotlib_rs/dviread.py +1386 -0
- matplotlib_rs/figure.py +3815 -0
- matplotlib_rs/font_manager.py +1855 -0
- matplotlib_rs/ft2font.py +515 -0
- matplotlib_rs/gridspec.py +808 -0
- matplotlib_rs/hatch.py +244 -0
- matplotlib_rs/image.py +1863 -0
- matplotlib_rs/inset.py +291 -0
- matplotlib_rs/layout_engine.py +310 -0
- matplotlib_rs/legend.py +1480 -0
- matplotlib_rs/legend_handler.py +812 -0
- matplotlib_rs/lines.py +1886 -0
- matplotlib_rs/markers.py +908 -0
- matplotlib_rs/mathtext.py +141 -0
- matplotlib_rs/mlab.py +959 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansDisplay.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerifDisplay.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/LICENSE_DEJAVU +99 -0
- matplotlib_rs/mpl-data/fonts/ttf/LICENSE_STIX +124 -0
- matplotlib_rs/mpl-data/fonts/ttf/LastResortHE-Regular.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXGeneral.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralItalic.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXNonUni.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBolIta.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniIta.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizFiveSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmb10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmex10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmmi10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmr10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmss10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmsy10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmti10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmtt10.ttf +0 -0
- matplotlib_rs/mpl-data/images/back-symbolic.svg +46 -0
- matplotlib_rs/mpl-data/images/back.pdf +0 -0
- matplotlib_rs/mpl-data/images/back.png +0 -0
- matplotlib_rs/mpl-data/images/back.svg +46 -0
- matplotlib_rs/mpl-data/images/back_large.png +0 -0
- matplotlib_rs/mpl-data/images/filesave-symbolic.svg +68 -0
- matplotlib_rs/mpl-data/images/filesave.pdf +72 -0
- matplotlib_rs/mpl-data/images/filesave.png +0 -0
- matplotlib_rs/mpl-data/images/filesave.svg +68 -0
- matplotlib_rs/mpl-data/images/filesave_large.png +0 -0
- matplotlib_rs/mpl-data/images/forward-symbolic.svg +46 -0
- matplotlib_rs/mpl-data/images/forward.pdf +0 -0
- matplotlib_rs/mpl-data/images/forward.png +0 -0
- matplotlib_rs/mpl-data/images/forward.svg +46 -0
- matplotlib_rs/mpl-data/images/forward_large.png +0 -0
- matplotlib_rs/mpl-data/images/hand.pdf +0 -0
- matplotlib_rs/mpl-data/images/hand.png +0 -0
- matplotlib_rs/mpl-data/images/hand.svg +130 -0
- matplotlib_rs/mpl-data/images/help-symbolic.svg +52 -0
- matplotlib_rs/mpl-data/images/help.pdf +71 -0
- matplotlib_rs/mpl-data/images/help.png +0 -0
- matplotlib_rs/mpl-data/images/help.svg +52 -0
- matplotlib_rs/mpl-data/images/help_large.png +0 -0
- matplotlib_rs/mpl-data/images/home-symbolic.svg +59 -0
- matplotlib_rs/mpl-data/images/home.pdf +0 -0
- matplotlib_rs/mpl-data/images/home.png +0 -0
- matplotlib_rs/mpl-data/images/home.svg +59 -0
- matplotlib_rs/mpl-data/images/home_large.png +0 -0
- matplotlib_rs/mpl-data/images/matplotlib.pdf +0 -0
- matplotlib_rs/mpl-data/images/matplotlib.png +0 -0
- matplotlib_rs/mpl-data/images/matplotlib.svg +3171 -0
- matplotlib_rs/mpl-data/images/matplotlib_large.png +0 -0
- matplotlib_rs/mpl-data/images/move-symbolic.svg +73 -0
- matplotlib_rs/mpl-data/images/move.pdf +0 -0
- matplotlib_rs/mpl-data/images/move.png +0 -0
- matplotlib_rs/mpl-data/images/move.svg +73 -0
- matplotlib_rs/mpl-data/images/move_large.png +0 -0
- matplotlib_rs/mpl-data/images/qt4_editor_options.pdf +0 -0
- matplotlib_rs/mpl-data/images/qt4_editor_options.png +0 -0
- matplotlib_rs/mpl-data/images/qt4_editor_options.svg +48 -0
- matplotlib_rs/mpl-data/images/qt4_editor_options_large.png +0 -0
- matplotlib_rs/mpl-data/images/subplots-symbolic.svg +81 -0
- matplotlib_rs/mpl-data/images/subplots.pdf +0 -0
- matplotlib_rs/mpl-data/images/subplots.png +0 -0
- matplotlib_rs/mpl-data/images/subplots.svg +81 -0
- matplotlib_rs/mpl-data/images/subplots_large.png +0 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect-symbolic.svg +40 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect.pdf +69 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect.png +0 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect.svg +40 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect_large.png +0 -0
- matplotlib_rs/mpl-data/kpsewhich.lua +4 -0
- matplotlib_rs/mpl-data/matplotlibrc +849 -0
- matplotlib_rs/mpl-data/plot_directive/plot_directive.css +16 -0
- matplotlib_rs/mpl-data/sample_data/Minduka_Present_Blue_Pack.png +0 -0
- matplotlib_rs/mpl-data/sample_data/README.txt +2 -0
- matplotlib_rs/mpl-data/sample_data/Stocks.csv +526 -0
- matplotlib_rs/mpl-data/sample_data/axes_grid/bivariate_normal.npy +0 -0
- matplotlib_rs/mpl-data/sample_data/data_x_x2_x3.csv +11 -0
- matplotlib_rs/mpl-data/sample_data/eeg.dat +0 -0
- matplotlib_rs/mpl-data/sample_data/embedding_in_wx3.xrc +65 -0
- matplotlib_rs/mpl-data/sample_data/goog.npz +0 -0
- matplotlib_rs/mpl-data/sample_data/grace_hopper.jpg +0 -0
- matplotlib_rs/mpl-data/sample_data/jacksboro_fault_dem.npz +0 -0
- matplotlib_rs/mpl-data/sample_data/logo2.png +0 -0
- matplotlib_rs/mpl-data/sample_data/membrane.dat +0 -0
- matplotlib_rs/mpl-data/sample_data/msft.csv +66 -0
- matplotlib_rs/mpl-data/sample_data/s1045.ima.gz +0 -0
- matplotlib_rs/mpl-data/sample_data/topobathy.npz +0 -0
- matplotlib_rs/mpl-data/stylelib/Solarize_Light2.mplstyle +53 -0
- matplotlib_rs/mpl-data/stylelib/_classic_test_patch.mplstyle +8 -0
- matplotlib_rs/mpl-data/stylelib/_mpl-gallery-nogrid.mplstyle +19 -0
- matplotlib_rs/mpl-data/stylelib/_mpl-gallery.mplstyle +19 -0
- matplotlib_rs/mpl-data/stylelib/bmh.mplstyle +27 -0
- matplotlib_rs/mpl-data/stylelib/classic.mplstyle +491 -0
- matplotlib_rs/mpl-data/stylelib/dark_background.mplstyle +26 -0
- matplotlib_rs/mpl-data/stylelib/fast.mplstyle +11 -0
- matplotlib_rs/mpl-data/stylelib/fivethirtyeight.mplstyle +37 -0
- matplotlib_rs/mpl-data/stylelib/ggplot.mplstyle +39 -0
- matplotlib_rs/mpl-data/stylelib/grayscale.mplstyle +29 -0
- matplotlib_rs/mpl-data/stylelib/petroff10.mplstyle +5 -0
- matplotlib_rs/mpl-data/stylelib/petroff6.mplstyle +5 -0
- matplotlib_rs/mpl-data/stylelib/petroff8.mplstyle +5 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-bright.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-colorblind.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark-palette.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-darkgrid.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-deep.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-muted.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-notebook.mplstyle +21 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-paper.mplstyle +21 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-pastel.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-poster.mplstyle +21 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-talk.mplstyle +21 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-ticks.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-white.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-whitegrid.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8.mplstyle +57 -0
- matplotlib_rs/mpl-data/stylelib/tableau-colorblind10.mplstyle +3 -0
- matplotlib_rs/mpl_toolkits/__init__.py +3 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/__init__.py +11 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/anchored_artists.py +415 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/axes_divider.py +619 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/axes_grid.py +565 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/axes_rgb.py +158 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/axes_size.py +272 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/inset_locator.py +525 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/mpl_axes.py +129 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/parasite_axes.py +261 -0
- matplotlib_rs/mpl_toolkits/axisartist/__init__.py +15 -0
- matplotlib_rs/mpl_toolkits/axisartist/angle_helper.py +396 -0
- matplotlib_rs/mpl_toolkits/axisartist/axes_divider.py +3 -0
- matplotlib_rs/mpl_toolkits/axisartist/axis_artist.py +1148 -0
- matplotlib_rs/mpl_toolkits/axisartist/axisline_style.py +193 -0
- matplotlib_rs/mpl_toolkits/axisartist/axislines.py +475 -0
- matplotlib_rs/mpl_toolkits/axisartist/floating_axes.py +265 -0
- matplotlib_rs/mpl_toolkits/axisartist/grid_finder.py +329 -0
- matplotlib_rs/mpl_toolkits/axisartist/grid_helper_curvelinear.py +353 -0
- matplotlib_rs/mpl_toolkits/axisartist/parasite_axes.py +8 -0
- matplotlib_rs/mpl_toolkits/mplot3d/__init__.py +4 -0
- matplotlib_rs/mpl_toolkits/mplot3d/art3d.py +1758 -0
- matplotlib_rs/mpl_toolkits/mplot3d/axes3d.py +4462 -0
- matplotlib_rs/mpl_toolkits/mplot3d/axis3d.py +807 -0
- matplotlib_rs/mpl_toolkits/mplot3d/proj3d.py +270 -0
- matplotlib_rs/offsetbox.py +1726 -0
- matplotlib_rs/patches.py +5049 -0
- matplotlib_rs/path.py +1147 -0
- matplotlib_rs/patheffects.py +512 -0
- matplotlib_rs/projections/__init__.py +126 -0
- matplotlib_rs/projections/geo.py +512 -0
- matplotlib_rs/projections/polar.py +1518 -0
- matplotlib_rs/pylab.py +68 -0
- matplotlib_rs/pyplot.py +4834 -0
- matplotlib_rs/quiver.py +1236 -0
- matplotlib_rs/rcsetup.py +3435 -0
- matplotlib_rs/sankey.py +815 -0
- matplotlib_rs/scale.py +1002 -0
- matplotlib_rs/spines.py +618 -0
- matplotlib_rs/stackplot.py +144 -0
- matplotlib_rs/streamplot.py +768 -0
- matplotlib_rs/style/__init__.py +269 -0
- matplotlib_rs/style/core.py +28 -0
- matplotlib_rs/table.py +860 -0
- matplotlib_rs/texmanager.py +375 -0
- matplotlib_rs/text.py +2412 -0
- matplotlib_rs/textpath.py +377 -0
- matplotlib_rs/ticker.py +3111 -0
- matplotlib_rs/transforms.py +3069 -0
- matplotlib_rs/tri/__init__.py +24 -0
- matplotlib_rs/tri/_triangulation.py +248 -0
- matplotlib_rs/tri/_tricontour.py +271 -0
- matplotlib_rs/tri/_trifinder.py +97 -0
- matplotlib_rs/tri/_triinterpolate.py +1575 -0
- matplotlib_rs/tri/_tripcolor.py +170 -0
- matplotlib_rs/tri/_triplot.py +87 -0
- matplotlib_rs/tri/_trirefine.py +308 -0
- matplotlib_rs/tri/_tritools.py +264 -0
- matplotlib_rs/typing.py +597 -0
- matplotlib_rs/units.py +196 -0
- matplotlib_rs/widgets.py +4455 -0
- matplotlib_rs-0.0.8.dist-info/METADATA +392 -0
- matplotlib_rs-0.0.8.dist-info/RECORD +352 -0
- matplotlib_rs-0.0.8.dist-info/WHEEL +4 -0
- matplotlib_rs-0.0.8.dist-info/sboms/matplotlib-rs.cyclonedx.json +4390 -0
matplotlib_rs/image.py
ADDED
|
@@ -0,0 +1,1863 @@
|
|
|
1
|
+
# Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
|
|
2
|
+
"""
|
|
3
|
+
The image module supports basic image loading, rescaling and display
|
|
4
|
+
operations.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import logging
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import warnings
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
import sys
|
|
14
|
+
|
|
15
|
+
# Pillow is never imported: image files are read and written by the Rust
|
|
16
|
+
# core (matplotlib_rs._imageio); PIL images passed in are still accepted.
|
|
17
|
+
import matplotlib_rs as mpl
|
|
18
|
+
from matplotlib_rs import _api, _colormap, _imageio, _png, cbook
|
|
19
|
+
# For clarity, names from _image are given explicitly in this module
|
|
20
|
+
from matplotlib_rs import _image
|
|
21
|
+
# For user convenience, the names from _image are also imported into
|
|
22
|
+
# the image namespace
|
|
23
|
+
from matplotlib_rs._image import * # noqa: F401, F403
|
|
24
|
+
import matplotlib_rs.artist as martist
|
|
25
|
+
import matplotlib_rs.colorizer as mcolorizer
|
|
26
|
+
from matplotlib_rs.backend_bases import FigureCanvasBase
|
|
27
|
+
import matplotlib_rs.colors as mcolors
|
|
28
|
+
from matplotlib_rs.transforms import (
|
|
29
|
+
Affine2D, BboxBase, Bbox, BboxTransform, BboxTransformTo,
|
|
30
|
+
IdentityTransform, TransformedBbox)
|
|
31
|
+
|
|
32
|
+
_log = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
# map interpolation strings to module constants
|
|
35
|
+
_interpd_ = {
|
|
36
|
+
'auto': _image.NEAREST, # this will use nearest or Hanning...
|
|
37
|
+
'none': _image.NEAREST, # fall back to nearest when not supported
|
|
38
|
+
'nearest': _image.NEAREST,
|
|
39
|
+
'bilinear': _image.BILINEAR,
|
|
40
|
+
'bicubic': _image.BICUBIC,
|
|
41
|
+
'spline16': _image.SPLINE16,
|
|
42
|
+
'spline36': _image.SPLINE36,
|
|
43
|
+
'hanning': _image.HANNING,
|
|
44
|
+
'hamming': _image.HAMMING,
|
|
45
|
+
'hermite': _image.HERMITE,
|
|
46
|
+
'kaiser': _image.KAISER,
|
|
47
|
+
'quadric': _image.QUADRIC,
|
|
48
|
+
'catrom': _image.CATROM,
|
|
49
|
+
'gaussian': _image.GAUSSIAN,
|
|
50
|
+
'bessel': _image.BESSEL,
|
|
51
|
+
'mitchell': _image.MITCHELL,
|
|
52
|
+
'sinc': _image.SINC,
|
|
53
|
+
'lanczos': _image.LANCZOS,
|
|
54
|
+
'blackman': _image.BLACKMAN,
|
|
55
|
+
'antialiased': _image.NEAREST, # this will use nearest or Hanning...
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
interpolations_names = set(_interpd_)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def composite_images(images, renderer, magnification=1.0):
|
|
62
|
+
"""
|
|
63
|
+
Composite a number of RGBA images into one. The images are
|
|
64
|
+
composited in the order in which they appear in the *images* list.
|
|
65
|
+
|
|
66
|
+
Parameters
|
|
67
|
+
----------
|
|
68
|
+
images : list of Images
|
|
69
|
+
Each must have a `!make_image` method. For each image,
|
|
70
|
+
`!can_composite` should return `True`, though this is not
|
|
71
|
+
enforced by this function. Each image must have a purely
|
|
72
|
+
affine transformation with no shear.
|
|
73
|
+
|
|
74
|
+
renderer : `.RendererBase`
|
|
75
|
+
|
|
76
|
+
magnification : float, default: 1
|
|
77
|
+
The additional magnification to apply for the renderer in use.
|
|
78
|
+
|
|
79
|
+
Returns
|
|
80
|
+
-------
|
|
81
|
+
image : (M, N, 4) `numpy.uint8` array
|
|
82
|
+
The composited RGBA image.
|
|
83
|
+
offset_x, offset_y : float
|
|
84
|
+
The (left, bottom) offset where the composited image should be placed
|
|
85
|
+
in the output figure.
|
|
86
|
+
"""
|
|
87
|
+
if len(images) == 0:
|
|
88
|
+
return np.empty((0, 0, 4), dtype=np.uint8), 0, 0
|
|
89
|
+
|
|
90
|
+
parts = []
|
|
91
|
+
bboxes = []
|
|
92
|
+
for image in images:
|
|
93
|
+
data, x, y, trans = image.make_image(renderer, magnification)
|
|
94
|
+
if data is not None:
|
|
95
|
+
x *= magnification
|
|
96
|
+
y *= magnification
|
|
97
|
+
parts.append((data, x, y, image._get_scalar_alpha()))
|
|
98
|
+
bboxes.append(
|
|
99
|
+
Bbox([[x, y], [x + data.shape[1], y + data.shape[0]]]))
|
|
100
|
+
|
|
101
|
+
if len(parts) == 0:
|
|
102
|
+
return np.empty((0, 0, 4), dtype=np.uint8), 0, 0
|
|
103
|
+
|
|
104
|
+
bbox = Bbox.union(bboxes)
|
|
105
|
+
|
|
106
|
+
output = np.zeros(
|
|
107
|
+
(int(bbox.height), int(bbox.width), 4), dtype=np.uint8)
|
|
108
|
+
|
|
109
|
+
for data, x, y, alpha in parts:
|
|
110
|
+
trans = Affine2D().translate(x - bbox.x0, y - bbox.y0)
|
|
111
|
+
_image.resample(data, output, trans, _image.NEAREST,
|
|
112
|
+
resample=False, alpha=alpha)
|
|
113
|
+
|
|
114
|
+
return output, bbox.x0 / magnification, bbox.y0 / magnification
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _draw_list_compositing_images(
|
|
118
|
+
renderer, parent, artists, suppress_composite=None):
|
|
119
|
+
"""
|
|
120
|
+
Draw a sorted list of artists, compositing images into a single
|
|
121
|
+
image where possible.
|
|
122
|
+
|
|
123
|
+
For internal Matplotlib use only: It is here to reduce duplication
|
|
124
|
+
between `Figure.draw` and `Axes.draw`, but otherwise should not be
|
|
125
|
+
generally useful.
|
|
126
|
+
"""
|
|
127
|
+
has_images = any(isinstance(x, _ImageBase) for x in artists)
|
|
128
|
+
|
|
129
|
+
# override the renderer default if suppressComposite is not None
|
|
130
|
+
not_composite = (suppress_composite if suppress_composite is not None
|
|
131
|
+
else renderer.option_image_nocomposite())
|
|
132
|
+
|
|
133
|
+
if not_composite or not has_images:
|
|
134
|
+
for a in artists:
|
|
135
|
+
a.draw(renderer)
|
|
136
|
+
else:
|
|
137
|
+
# Composite any adjacent images together
|
|
138
|
+
image_group = []
|
|
139
|
+
mag = renderer.get_image_magnification()
|
|
140
|
+
|
|
141
|
+
def flush_images():
|
|
142
|
+
if len(image_group) == 1:
|
|
143
|
+
image_group[0].draw(renderer)
|
|
144
|
+
elif len(image_group) > 1:
|
|
145
|
+
data, l, b = composite_images(image_group, renderer, mag)
|
|
146
|
+
if data.size != 0:
|
|
147
|
+
gc = renderer.new_gc()
|
|
148
|
+
gc.set_clip_rectangle(parent.bbox)
|
|
149
|
+
gc.set_clip_path(parent.get_clip_path())
|
|
150
|
+
renderer.draw_image(gc, round(l), round(b), data)
|
|
151
|
+
gc.restore()
|
|
152
|
+
del image_group[:]
|
|
153
|
+
|
|
154
|
+
for a in artists:
|
|
155
|
+
if (isinstance(a, _ImageBase) and a.can_composite() and
|
|
156
|
+
a.get_clip_on() and not a.get_clip_path()):
|
|
157
|
+
image_group.append(a)
|
|
158
|
+
else:
|
|
159
|
+
flush_images()
|
|
160
|
+
a.draw(renderer)
|
|
161
|
+
flush_images()
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _resample(
|
|
165
|
+
image_obj, data, out_shape, transform, *, resample=None, alpha=1,
|
|
166
|
+
lut=None):
|
|
167
|
+
"""
|
|
168
|
+
Convenience wrapper around `._image.resample` to resample *data* to
|
|
169
|
+
*out_shape* (with a third dimension if *data* is RGBA) that takes care of
|
|
170
|
+
allocating the output array and fetching the relevant properties from the
|
|
171
|
+
Image object *image_obj*.
|
|
172
|
+
|
|
173
|
+
matplotlib_rs: with a (K, 4) float64 *lut*, *data* holds the lut rows of
|
|
174
|
+
the pixels of the RGBA image ``lut[data]`` resampled.
|
|
175
|
+
"""
|
|
176
|
+
# AGG can only handle coordinates smaller than 24-bit signed integers,
|
|
177
|
+
# so raise errors if the input data is larger than _image.resample can
|
|
178
|
+
# handle.
|
|
179
|
+
msg = ('Data with more than {n} cannot be accurately displayed. '
|
|
180
|
+
'Downsampling to less than {n} before displaying. '
|
|
181
|
+
'To remove this warning, manually downsample your data.')
|
|
182
|
+
if data.shape[1] > 2**23:
|
|
183
|
+
warnings.warn(msg.format(n='2**23 columns'))
|
|
184
|
+
step = int(np.ceil(data.shape[1] / 2**23))
|
|
185
|
+
data = data[:, ::step]
|
|
186
|
+
transform = Affine2D().scale(step, 1) + transform
|
|
187
|
+
if data.shape[0] > 2**24:
|
|
188
|
+
warnings.warn(msg.format(n='2**24 rows'))
|
|
189
|
+
step = int(np.ceil(data.shape[0] / 2**24))
|
|
190
|
+
data = data[::step, :]
|
|
191
|
+
transform = Affine2D().scale(1, step) + transform
|
|
192
|
+
# decide if we need to apply anti-aliasing if the data is upsampled:
|
|
193
|
+
# compare the number of displayed pixels to the number of
|
|
194
|
+
# the data pixels.
|
|
195
|
+
interpolation = image_obj.get_interpolation()
|
|
196
|
+
if interpolation in ['antialiased', 'auto']:
|
|
197
|
+
# don't antialias if upsampling by an integer number or
|
|
198
|
+
# if zooming in more than a factor of 3
|
|
199
|
+
pos = np.array([[0, 0], [data.shape[1], data.shape[0]]])
|
|
200
|
+
disp = transform.transform(pos)
|
|
201
|
+
dispx = np.abs(np.diff(disp[:, 0]))
|
|
202
|
+
dispy = np.abs(np.diff(disp[:, 1]))
|
|
203
|
+
if ((dispx > 3 * data.shape[1] or
|
|
204
|
+
dispx == data.shape[1] or
|
|
205
|
+
dispx == 2 * data.shape[1]) and
|
|
206
|
+
(dispy > 3 * data.shape[0] or
|
|
207
|
+
dispy == data.shape[0] or
|
|
208
|
+
dispy == 2 * data.shape[0])):
|
|
209
|
+
interpolation = 'nearest'
|
|
210
|
+
else:
|
|
211
|
+
interpolation = 'hanning'
|
|
212
|
+
if lut is not None:
|
|
213
|
+
out = np.zeros(out_shape + (4,), lut.dtype)
|
|
214
|
+
else:
|
|
215
|
+
out = np.zeros(out_shape + data.shape[2:], data.dtype) # 2D->2D, 3D->3D.
|
|
216
|
+
if resample is None:
|
|
217
|
+
resample = image_obj.get_resample()
|
|
218
|
+
|
|
219
|
+
# When an output pixel falls exactly on the edge between two input pixels, the Agg
|
|
220
|
+
# resampler will use the right input pixel as the nearest neighbor. We want the
|
|
221
|
+
# left input pixel to be chosen instead, so we flip the input data and the supplied
|
|
222
|
+
# transform. If origin != 'upper', the transform will already include a flip in the
|
|
223
|
+
# vertical direction.
|
|
224
|
+
if interpolation == 'nearest':
|
|
225
|
+
transform = Affine2D().translate(-data.shape[1], 0).scale(-1, 1) + transform
|
|
226
|
+
data = np.flip(data, axis=1)
|
|
227
|
+
if image_obj.origin == 'upper':
|
|
228
|
+
transform = Affine2D().translate(0, -data.shape[0]).scale(1, -1) + transform
|
|
229
|
+
data = np.flip(data, axis=0)
|
|
230
|
+
|
|
231
|
+
if lut is not None:
|
|
232
|
+
_image.resample_indexed(data, lut, out, transform,
|
|
233
|
+
_interpd_[interpolation],
|
|
234
|
+
resample,
|
|
235
|
+
alpha,
|
|
236
|
+
image_obj.get_filternorm(),
|
|
237
|
+
image_obj.get_filterrad())
|
|
238
|
+
return out
|
|
239
|
+
_image.resample(data, out, transform,
|
|
240
|
+
_interpd_[interpolation],
|
|
241
|
+
resample,
|
|
242
|
+
alpha,
|
|
243
|
+
image_obj.get_filternorm(),
|
|
244
|
+
image_obj.get_filterrad())
|
|
245
|
+
|
|
246
|
+
return out
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _rgb_to_rgba(A):
|
|
250
|
+
"""
|
|
251
|
+
Convert an RGB image to RGBA, as required by the image resample C++
|
|
252
|
+
extension.
|
|
253
|
+
"""
|
|
254
|
+
rgba = np.zeros((A.shape[0], A.shape[1], 4), dtype=A.dtype)
|
|
255
|
+
rgba[:, :, :3] = A
|
|
256
|
+
if rgba.dtype == np.uint8:
|
|
257
|
+
rgba[:, :, 3] = 255
|
|
258
|
+
else:
|
|
259
|
+
rgba[:, :, 3] = 1.0
|
|
260
|
+
return rgba
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
class _ImageBase(mcolorizer.ColorizingArtist):
|
|
264
|
+
"""
|
|
265
|
+
Base class for images.
|
|
266
|
+
|
|
267
|
+
*interpolation* and *cmap* default to their rc settings.
|
|
268
|
+
|
|
269
|
+
*cmap* is a `.colors.Colormap` instance.
|
|
270
|
+
*norm* is a `.colors.Normalize` instance to map luminance to 0-1.
|
|
271
|
+
|
|
272
|
+
*extent* is a ``(left, right, bottom, top)`` tuple in data coordinates, for
|
|
273
|
+
making image plots registered with data plots; the default is to label the
|
|
274
|
+
pixel centers with the zero-based row and column indices.
|
|
275
|
+
|
|
276
|
+
Additional kwargs are `.Artist` properties.
|
|
277
|
+
"""
|
|
278
|
+
|
|
279
|
+
zorder = 0
|
|
280
|
+
|
|
281
|
+
def __init__(self, ax,
|
|
282
|
+
cmap=None,
|
|
283
|
+
norm=None,
|
|
284
|
+
colorizer=None,
|
|
285
|
+
interpolation=None,
|
|
286
|
+
origin=None,
|
|
287
|
+
filternorm=True,
|
|
288
|
+
filterrad=4.0,
|
|
289
|
+
resample=False,
|
|
290
|
+
*,
|
|
291
|
+
interpolation_stage=None,
|
|
292
|
+
**kwargs
|
|
293
|
+
):
|
|
294
|
+
super().__init__(self._get_colorizer(cmap, norm, colorizer))
|
|
295
|
+
origin = mpl._val_or_rc(origin, 'image.origin')
|
|
296
|
+
_api.check_in_list(["upper", "lower"], origin=origin)
|
|
297
|
+
self.origin = origin
|
|
298
|
+
self.set_filternorm(filternorm)
|
|
299
|
+
self.set_filterrad(filterrad)
|
|
300
|
+
self.set_interpolation(interpolation)
|
|
301
|
+
self.set_interpolation_stage(interpolation_stage)
|
|
302
|
+
self.set_resample(resample)
|
|
303
|
+
self.axes = ax
|
|
304
|
+
|
|
305
|
+
self._imcache = None
|
|
306
|
+
|
|
307
|
+
self._internal_update(kwargs)
|
|
308
|
+
|
|
309
|
+
def __str__(self):
|
|
310
|
+
try:
|
|
311
|
+
shape = self.get_shape()
|
|
312
|
+
return f"{type(self).__name__}(shape={shape!r})"
|
|
313
|
+
except RuntimeError:
|
|
314
|
+
return type(self).__name__
|
|
315
|
+
|
|
316
|
+
def __getstate__(self):
|
|
317
|
+
# Save some space on the pickle by not saving the cache.
|
|
318
|
+
return {**super().__getstate__(), "_imcache": None}
|
|
319
|
+
|
|
320
|
+
def get_size(self):
|
|
321
|
+
"""Return the size of the image as tuple (numrows, numcols)."""
|
|
322
|
+
return self.get_shape()[:2]
|
|
323
|
+
|
|
324
|
+
def get_shape(self):
|
|
325
|
+
"""
|
|
326
|
+
Return the shape of the image as tuple (numrows, numcols, channels).
|
|
327
|
+
"""
|
|
328
|
+
if self._A is None:
|
|
329
|
+
raise RuntimeError('You must first set the image array')
|
|
330
|
+
|
|
331
|
+
return self._A.shape
|
|
332
|
+
|
|
333
|
+
def set_alpha(self, alpha):
|
|
334
|
+
"""
|
|
335
|
+
Set the alpha value used for blending - not supported on all backends.
|
|
336
|
+
|
|
337
|
+
Parameters
|
|
338
|
+
----------
|
|
339
|
+
alpha : float or 2D array-like or None
|
|
340
|
+
"""
|
|
341
|
+
martist.Artist._set_alpha_for_array(self, alpha)
|
|
342
|
+
if np.ndim(alpha) not in (0, 2):
|
|
343
|
+
raise TypeError('alpha must be a float, two-dimensional '
|
|
344
|
+
'array, or None')
|
|
345
|
+
self._imcache = None
|
|
346
|
+
|
|
347
|
+
def _get_scalar_alpha(self):
|
|
348
|
+
"""
|
|
349
|
+
Get a scalar alpha value to be applied to the artist as a whole.
|
|
350
|
+
|
|
351
|
+
If the alpha value is a matrix, the method returns 1.0 because pixels
|
|
352
|
+
have individual alpha values (see `~._ImageBase._make_image` for
|
|
353
|
+
details). If the alpha value is a scalar, the method returns said value
|
|
354
|
+
to be applied to the artist as a whole because pixels do not have
|
|
355
|
+
individual alpha values.
|
|
356
|
+
"""
|
|
357
|
+
return 1.0 if self._alpha is None or np.ndim(self._alpha) > 0 \
|
|
358
|
+
else self._alpha
|
|
359
|
+
|
|
360
|
+
def changed(self):
|
|
361
|
+
"""
|
|
362
|
+
Call this whenever the mappable is changed so observers can update.
|
|
363
|
+
"""
|
|
364
|
+
self._imcache = None
|
|
365
|
+
super().changed()
|
|
366
|
+
|
|
367
|
+
def _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification=1.0,
|
|
368
|
+
unsampled=False, round_to_pixel_border=True):
|
|
369
|
+
"""
|
|
370
|
+
Normalize, rescale, and colormap the image *A* from the given *in_bbox*
|
|
371
|
+
(in data space), to the given *out_bbox* (in pixel space) clipped to
|
|
372
|
+
the given *clip_bbox* (also in pixel space), and magnified by the
|
|
373
|
+
*magnification* factor.
|
|
374
|
+
|
|
375
|
+
Parameters
|
|
376
|
+
----------
|
|
377
|
+
A : ndarray
|
|
378
|
+
|
|
379
|
+
- a (M, N) array interpreted as scalar (greyscale) image,
|
|
380
|
+
with one of the dtypes `~numpy.float32`, `~numpy.float64`,
|
|
381
|
+
`~numpy.float128`, `~numpy.uint16` or `~numpy.uint8`.
|
|
382
|
+
- (M, N, 4) RGBA image with a dtype of `~numpy.float32`,
|
|
383
|
+
`~numpy.float64`, `~numpy.float128`, or `~numpy.uint8`.
|
|
384
|
+
|
|
385
|
+
in_bbox : `~matplotlib.transforms.Bbox`
|
|
386
|
+
|
|
387
|
+
out_bbox : `~matplotlib.transforms.Bbox`
|
|
388
|
+
|
|
389
|
+
clip_bbox : `~matplotlib.transforms.Bbox`
|
|
390
|
+
|
|
391
|
+
magnification : float, default: 1
|
|
392
|
+
|
|
393
|
+
unsampled : bool, default: False
|
|
394
|
+
If True, the image will not be scaled, but an appropriate
|
|
395
|
+
affine transformation will be returned instead.
|
|
396
|
+
|
|
397
|
+
round_to_pixel_border : bool, default: True
|
|
398
|
+
If True, the output image size will be rounded to the nearest pixel
|
|
399
|
+
boundary. This makes the images align correctly with the Axes.
|
|
400
|
+
It should not be used if exact scaling is needed, such as for
|
|
401
|
+
`.FigureImage`.
|
|
402
|
+
|
|
403
|
+
Returns
|
|
404
|
+
-------
|
|
405
|
+
image : (M, N, 4) `numpy.uint8` array
|
|
406
|
+
The RGBA image, resampled unless *unsampled* is True.
|
|
407
|
+
x, y : float
|
|
408
|
+
The upper left corner where the image should be drawn, in pixel
|
|
409
|
+
space.
|
|
410
|
+
trans : `~matplotlib.transforms.Affine2D`
|
|
411
|
+
The affine transformation from image to pixel space.
|
|
412
|
+
"""
|
|
413
|
+
if A is None:
|
|
414
|
+
raise RuntimeError('You must first set the image '
|
|
415
|
+
'array or the image attribute')
|
|
416
|
+
if A.size == 0:
|
|
417
|
+
raise RuntimeError("_make_image must get a non-empty image. "
|
|
418
|
+
"Your Artist's draw method must filter before "
|
|
419
|
+
"this method is called.")
|
|
420
|
+
|
|
421
|
+
clipped_bbox = Bbox.intersection(out_bbox, clip_bbox)
|
|
422
|
+
|
|
423
|
+
if clipped_bbox is None:
|
|
424
|
+
return None, 0, 0, None
|
|
425
|
+
|
|
426
|
+
# Define the magnified bbox after clipping
|
|
427
|
+
magnified_extents = clipped_bbox.extents * magnification
|
|
428
|
+
if ((not unsampled) and round_to_pixel_border):
|
|
429
|
+
# Round to the nearest output pixel
|
|
430
|
+
# Add a tiny fudge amount to account for numerical precision loss
|
|
431
|
+
# on the two sides away from the Agg anchor point (x0, y1)
|
|
432
|
+
x0 = np.floor(magnified_extents[0] + 0.5) # round half up
|
|
433
|
+
y0 = np.ceil(magnified_extents[1] - 0.5 - 1e-8) # round half down
|
|
434
|
+
x1 = np.floor(magnified_extents[2] + 0.5 + 1e-8) # round half up
|
|
435
|
+
y1 = np.ceil(magnified_extents[3] - 0.5) # round half down
|
|
436
|
+
magnified_bbox = Bbox.from_extents([x0, y0, x1, y1])
|
|
437
|
+
else:
|
|
438
|
+
magnified_bbox = Bbox.from_extents(magnified_extents)
|
|
439
|
+
|
|
440
|
+
if magnified_bbox.width == 0 or magnified_bbox.height == 0:
|
|
441
|
+
return None, 0, 0, None
|
|
442
|
+
|
|
443
|
+
if self.origin == 'upper':
|
|
444
|
+
# Flip the input image using a transform. This avoids the
|
|
445
|
+
# problem with flipping the array, which results in a copy
|
|
446
|
+
# when it is converted to contiguous in the C wrapper
|
|
447
|
+
t0 = Affine2D().translate(0, -A.shape[0]).scale(1, -1)
|
|
448
|
+
else:
|
|
449
|
+
t0 = IdentityTransform()
|
|
450
|
+
|
|
451
|
+
t0 += (
|
|
452
|
+
Affine2D()
|
|
453
|
+
.scale(
|
|
454
|
+
in_bbox.width / A.shape[1],
|
|
455
|
+
in_bbox.height / A.shape[0])
|
|
456
|
+
.translate(in_bbox.x0, in_bbox.y0)
|
|
457
|
+
+ self.get_transform())
|
|
458
|
+
|
|
459
|
+
t = (t0
|
|
460
|
+
+ (Affine2D()
|
|
461
|
+
.scale(magnification)
|
|
462
|
+
.translate(-magnified_bbox.x0, -magnified_bbox.y0)))
|
|
463
|
+
|
|
464
|
+
out_shape = (int(magnified_bbox.height), int(magnified_bbox.width))
|
|
465
|
+
|
|
466
|
+
if not unsampled:
|
|
467
|
+
if not (A.ndim == 2 or A.ndim == 3 and A.shape[-1] in (3, 4)):
|
|
468
|
+
raise ValueError(f"Invalid shape {A.shape} for image data")
|
|
469
|
+
|
|
470
|
+
# if antialiased, this needs to change as window sizes
|
|
471
|
+
# change:
|
|
472
|
+
interpolation_stage = self._interpolation_stage
|
|
473
|
+
if interpolation_stage in ['antialiased', 'auto']:
|
|
474
|
+
pos = np.array([[0, 0], [A.shape[1], A.shape[0]]])
|
|
475
|
+
disp = t.transform(pos)
|
|
476
|
+
dispx = np.abs(np.diff(disp[:, 0])) / A.shape[1]
|
|
477
|
+
dispy = np.abs(np.diff(disp[:, 1])) / A.shape[0]
|
|
478
|
+
if (dispx < 3) or (dispy < 3):
|
|
479
|
+
interpolation_stage = 'rgba'
|
|
480
|
+
else:
|
|
481
|
+
interpolation_stage = 'data'
|
|
482
|
+
|
|
483
|
+
if A.ndim == 2 and interpolation_stage == 'data':
|
|
484
|
+
# if we are a 2D array, then we are running through the
|
|
485
|
+
# norm + colormap transformation. However, in general the
|
|
486
|
+
# input data is not going to match the size on the screen so we
|
|
487
|
+
# have to resample to the correct number of pixels
|
|
488
|
+
|
|
489
|
+
if A.dtype.kind == 'f': # Float dtype: scale to same dtype.
|
|
490
|
+
scaled_dtype = np.dtype("f8" if A.dtype.itemsize > 4 else "f4")
|
|
491
|
+
if scaled_dtype.itemsize < A.dtype.itemsize:
|
|
492
|
+
_api.warn_external(f"Casting input data from {A.dtype}"
|
|
493
|
+
f" to {scaled_dtype} for imshow.")
|
|
494
|
+
else: # Int dtype, likely.
|
|
495
|
+
# TODO slice input array first
|
|
496
|
+
# Scale to appropriately sized float: use float32 if the
|
|
497
|
+
# dynamic range is small, to limit the memory footprint.
|
|
498
|
+
da = A.max().astype("f8") - A.min().astype("f8")
|
|
499
|
+
scaled_dtype = "f8" if da > 1e8 else "f4"
|
|
500
|
+
|
|
501
|
+
# resample the input data to the correct resolution and shape
|
|
502
|
+
A_resampled = _resample(self, A.astype(scaled_dtype), out_shape, t)
|
|
503
|
+
|
|
504
|
+
# if using NoNorm, cast back to the original datatype
|
|
505
|
+
if isinstance(self.norm, mcolors.NoNorm):
|
|
506
|
+
A_resampled = A_resampled.astype(A.dtype)
|
|
507
|
+
|
|
508
|
+
# Compute out_mask (what screen pixels include "bad" data
|
|
509
|
+
# pixels) and out_alpha (to what extent screen pixels are
|
|
510
|
+
# covered by data pixels: 0 outside the data extent, 1 inside
|
|
511
|
+
# (even for bad data), and intermediate values at the edges).
|
|
512
|
+
mask = (np.where(A.mask, np.float32(np.nan), np.float32(1))
|
|
513
|
+
if A.mask.shape == A.shape # nontrivial mask
|
|
514
|
+
else np.ones_like(A, np.float32))
|
|
515
|
+
# we always have to interpolate the mask to account for
|
|
516
|
+
# non-affine transformations
|
|
517
|
+
out_alpha = _resample(self, mask, out_shape, t, resample=True)
|
|
518
|
+
del mask # Make sure we don't use mask anymore!
|
|
519
|
+
out_mask = np.isnan(out_alpha)
|
|
520
|
+
out_alpha[out_mask] = 1
|
|
521
|
+
# Apply the pixel-by-pixel alpha values if present
|
|
522
|
+
alpha = self.get_alpha()
|
|
523
|
+
if alpha is not None and np.ndim(alpha) > 0:
|
|
524
|
+
out_alpha *= _resample(self, alpha, out_shape, t, resample=True)
|
|
525
|
+
# mask and run through the norm
|
|
526
|
+
resampled_masked = np.ma.masked_array(A_resampled, out_mask)
|
|
527
|
+
res = self.norm(resampled_masked)
|
|
528
|
+
else:
|
|
529
|
+
if A.ndim == 2: # interpolation_stage = 'rgba'
|
|
530
|
+
self.norm.autoscale_None(A)
|
|
531
|
+
# matplotlib_rs: large float data as colormap lut rows
|
|
532
|
+
A = _colormap.image_rgba(self, A)
|
|
533
|
+
if isinstance(A, _colormap.Indexed):
|
|
534
|
+
# The premultiplied RGBA array below is lut[A.idx] for
|
|
535
|
+
# the premultiplied lut (rows of alpha 1 are unchanged,
|
|
536
|
+
# as when no premultiplication is needed).
|
|
537
|
+
alpha = self.get_alpha()
|
|
538
|
+
post_apply_alpha = alpha is not None
|
|
539
|
+
lut = A.lut * A.lut[:, 3:4]
|
|
540
|
+
lut[:, 3] = A.lut[:, 3]
|
|
541
|
+
res = _resample(self, A.idx, out_shape, t, lut=lut)
|
|
542
|
+
else:
|
|
543
|
+
if A.dtype == np.uint8:
|
|
544
|
+
# uint8 is too imprecise for premultiplied alpha roundtrips.
|
|
545
|
+
A = np.divide(A, 0xff, dtype=np.float32)
|
|
546
|
+
alpha = self.get_alpha()
|
|
547
|
+
post_apply_alpha = False
|
|
548
|
+
if alpha is None: # alpha parameter not specified
|
|
549
|
+
if A.shape[2] == 3: # image has no alpha channel
|
|
550
|
+
A = np.dstack([A, np.ones(A.shape[:2])])
|
|
551
|
+
elif np.ndim(alpha) > 0: # Array alpha
|
|
552
|
+
if A.shape[2] == 3: # RGB: use array alpha directly
|
|
553
|
+
A = np.dstack([A, alpha])
|
|
554
|
+
else: # RGBA: multiply existing alpha by array alpha
|
|
555
|
+
A = np.dstack([A[..., :3], A[..., 3] * alpha])
|
|
556
|
+
else: # Scalar alpha
|
|
557
|
+
if A.shape[2] == 3: # broadcast scalar alpha
|
|
558
|
+
A = np.dstack([A, np.full(A.shape[:2], alpha, np.float32)])
|
|
559
|
+
else: # or apply scalar alpha to existing alpha channel
|
|
560
|
+
post_apply_alpha = True
|
|
561
|
+
# Resample in premultiplied alpha space. (TODO: Consider
|
|
562
|
+
# implementing premultiplied-space resampling in
|
|
563
|
+
# span_image_resample_rgba_affine::generate?)
|
|
564
|
+
# Multiplying the whole array and then restoring the alpha channel
|
|
565
|
+
# is faster than an in-place multiply of the strided A[..., :3]
|
|
566
|
+
# view. If alpha is uniformly 1, premultiplication can be skipped.
|
|
567
|
+
alpha_in = A[..., 3]
|
|
568
|
+
if (alpha_in != 1).any():
|
|
569
|
+
A = A * alpha_in[..., None]
|
|
570
|
+
A[..., 3] = alpha_in
|
|
571
|
+
res = _resample(self, A, out_shape, t)
|
|
572
|
+
# Demultiply. Zeroes in the divisor are replaced by ones,
|
|
573
|
+
# which leaves the corresponding (premultiplied) RGB values
|
|
574
|
+
# untouched. Dividing the whole contiguous array is several
|
|
575
|
+
# times faster than np.divide(..., where=...) into the strided
|
|
576
|
+
# res[..., :3] view.
|
|
577
|
+
alpha_out = res[..., 3].copy()
|
|
578
|
+
res /= np.where(alpha_out != 0, alpha_out, 1)[..., None]
|
|
579
|
+
res[..., 3] = alpha_out
|
|
580
|
+
if post_apply_alpha:
|
|
581
|
+
res[..., 3] *= alpha
|
|
582
|
+
|
|
583
|
+
# res is now either a 2D array of normed (int or float) data
|
|
584
|
+
# or an RGBA array of re-sampled input
|
|
585
|
+
output = self.to_rgba(res, bytes=True, norm=False)
|
|
586
|
+
# output is now a correctly sized RGBA array of uint8
|
|
587
|
+
|
|
588
|
+
# Apply alpha *after* if the input was greyscale without a mask
|
|
589
|
+
# (matplotlib_rs: A.ndim == 2 here only in the 'data' stage; A
|
|
590
|
+
# may be an _colormap.Indexed image in the 'rgba' stage)
|
|
591
|
+
if interpolation_stage == 'data' and A.ndim == 2:
|
|
592
|
+
alpha = self._get_scalar_alpha()
|
|
593
|
+
alpha_channel = output[:, :, 3]
|
|
594
|
+
alpha_channel[:] = ( # Assignment will cast to uint8.
|
|
595
|
+
alpha_channel.astype(np.float32) * out_alpha * alpha)
|
|
596
|
+
|
|
597
|
+
else:
|
|
598
|
+
if self._imcache is None:
|
|
599
|
+
self._imcache = self.to_rgba(A, bytes=True, norm=(A.ndim == 2))
|
|
600
|
+
output = self._imcache
|
|
601
|
+
|
|
602
|
+
# Subset the input image to only the part that will be displayed.
|
|
603
|
+
subset = TransformedBbox(clip_bbox, t0.inverted()).frozen()
|
|
604
|
+
output = output[
|
|
605
|
+
int(max(subset.ymin, 0)):
|
|
606
|
+
int(min(subset.ymax + 1, output.shape[0])),
|
|
607
|
+
int(max(subset.xmin, 0)):
|
|
608
|
+
int(min(subset.xmax + 1, output.shape[1]))]
|
|
609
|
+
|
|
610
|
+
t = Affine2D().translate(
|
|
611
|
+
int(max(subset.xmin, 0)), int(max(subset.ymin, 0))) + t
|
|
612
|
+
|
|
613
|
+
return (output,
|
|
614
|
+
magnified_bbox.x0 / magnification,
|
|
615
|
+
magnified_bbox.y0 / magnification,
|
|
616
|
+
t)
|
|
617
|
+
|
|
618
|
+
def make_image(self, renderer, magnification=1.0, unsampled=False):
|
|
619
|
+
"""
|
|
620
|
+
Normalize, rescale, and colormap this image's data for rendering using
|
|
621
|
+
*renderer*, with the given *magnification*.
|
|
622
|
+
|
|
623
|
+
If *unsampled* is True, the image will not be scaled, but an
|
|
624
|
+
appropriate affine transformation will be returned instead.
|
|
625
|
+
|
|
626
|
+
Returns
|
|
627
|
+
-------
|
|
628
|
+
image : (M, N, 4) `numpy.uint8` array
|
|
629
|
+
The RGBA image, resampled unless *unsampled* is True.
|
|
630
|
+
x, y : float
|
|
631
|
+
The upper left corner where the image should be drawn, in pixel
|
|
632
|
+
space.
|
|
633
|
+
trans : `~matplotlib.transforms.Affine2D`
|
|
634
|
+
The affine transformation from image to pixel space.
|
|
635
|
+
"""
|
|
636
|
+
raise NotImplementedError('The make_image method must be overridden')
|
|
637
|
+
|
|
638
|
+
def _check_unsampled_image(self):
|
|
639
|
+
"""
|
|
640
|
+
Return whether the image is better to be drawn unsampled.
|
|
641
|
+
|
|
642
|
+
The derived class needs to override it.
|
|
643
|
+
"""
|
|
644
|
+
return False
|
|
645
|
+
|
|
646
|
+
@martist.allow_rasterization
|
|
647
|
+
def draw(self, renderer):
|
|
648
|
+
# if not visible, declare victory and return
|
|
649
|
+
if not self.get_visible():
|
|
650
|
+
self.stale = False
|
|
651
|
+
return
|
|
652
|
+
# for empty images, there is nothing to draw!
|
|
653
|
+
if self.get_array().size == 0:
|
|
654
|
+
self.stale = False
|
|
655
|
+
return
|
|
656
|
+
# actually render the image.
|
|
657
|
+
gc = renderer.new_gc()
|
|
658
|
+
self._set_gc_clip(gc)
|
|
659
|
+
gc.set_alpha(self._get_scalar_alpha())
|
|
660
|
+
gc.set_url(self.get_url())
|
|
661
|
+
gc.set_gid(self.get_gid())
|
|
662
|
+
if (renderer.option_scale_image() # Renderer supports transform kwarg.
|
|
663
|
+
and self._check_unsampled_image()
|
|
664
|
+
and self.get_transform().is_affine):
|
|
665
|
+
im, l, b, trans = self.make_image(renderer, unsampled=True)
|
|
666
|
+
if im is not None:
|
|
667
|
+
trans = Affine2D().scale(im.shape[1], im.shape[0]) + trans
|
|
668
|
+
renderer.draw_image(gc, l, b, im, trans)
|
|
669
|
+
else:
|
|
670
|
+
im, l, b, trans = self.make_image(
|
|
671
|
+
renderer, renderer.get_image_magnification())
|
|
672
|
+
if im is not None:
|
|
673
|
+
renderer.draw_image(gc, l, b, im)
|
|
674
|
+
gc.restore()
|
|
675
|
+
self.stale = False
|
|
676
|
+
|
|
677
|
+
def contains(self, mouseevent):
|
|
678
|
+
"""Test whether the mouse event occurred within the image."""
|
|
679
|
+
if (self._different_canvas(mouseevent)
|
|
680
|
+
# This doesn't work for figimage.
|
|
681
|
+
or not self.axes.contains(mouseevent)[0]):
|
|
682
|
+
return False, {}
|
|
683
|
+
# TODO: make sure this is consistent with patch and patch
|
|
684
|
+
# collection on nonlinear transformed coordinates.
|
|
685
|
+
# TODO: consider returning image coordinates (shouldn't
|
|
686
|
+
# be too difficult given that the image is rectilinear
|
|
687
|
+
trans = self.get_transform().inverted()
|
|
688
|
+
x, y = trans.transform([mouseevent.x, mouseevent.y])
|
|
689
|
+
xmin, xmax, ymin, ymax = self.get_extent()
|
|
690
|
+
# This checks xmin <= x <= xmax *or* xmax <= x <= xmin.
|
|
691
|
+
inside = (x is not None and (x - xmin) * (x - xmax) <= 0
|
|
692
|
+
and y is not None and (y - ymin) * (y - ymax) <= 0)
|
|
693
|
+
return inside, {}
|
|
694
|
+
|
|
695
|
+
def write_png(self, fname):
|
|
696
|
+
"""Write the image to png file *fname*."""
|
|
697
|
+
im = self.to_rgba(self._A[::-1] if self.origin == 'lower' else self._A,
|
|
698
|
+
bytes=True, norm=True)
|
|
699
|
+
_png.write(fname, im)
|
|
700
|
+
|
|
701
|
+
@staticmethod
|
|
702
|
+
def _normalize_image_array(A):
|
|
703
|
+
"""
|
|
704
|
+
Check validity of image-like input *A* and normalize it to a format suitable for
|
|
705
|
+
Image subclasses.
|
|
706
|
+
"""
|
|
707
|
+
A = cbook.safe_masked_invalid(A, copy=True)
|
|
708
|
+
if A.dtype != np.uint8 and not np.can_cast(A.dtype, float, "same_kind"):
|
|
709
|
+
raise TypeError(f"Image data of dtype {A.dtype} cannot be "
|
|
710
|
+
f"converted to float")
|
|
711
|
+
if A.ndim == 3 and A.shape[-1] == 1:
|
|
712
|
+
A = A.squeeze(-1) # If just (M, N, 1), assume scalar and apply colormap.
|
|
713
|
+
if not (A.ndim == 2 or A.ndim == 3 and A.shape[-1] in [3, 4]):
|
|
714
|
+
raise TypeError(f"Invalid shape {A.shape} for image data")
|
|
715
|
+
if A.ndim == 3:
|
|
716
|
+
# If the input data has values outside the valid range (after
|
|
717
|
+
# normalisation), we issue a warning and then clip X to the bounds
|
|
718
|
+
# - otherwise casting wraps extreme values, hiding outliers and
|
|
719
|
+
# making reliable interpretation impossible.
|
|
720
|
+
high = 255 if np.issubdtype(A.dtype, np.integer) else 1
|
|
721
|
+
if A.min() < 0 or high < A.max():
|
|
722
|
+
_log.warning(
|
|
723
|
+
'Clipping input data to the valid range for imshow with '
|
|
724
|
+
'RGB data ([0..1] for floats or [0..255] for integers). '
|
|
725
|
+
'Got range [%s..%s].',
|
|
726
|
+
A.min(), A.max()
|
|
727
|
+
)
|
|
728
|
+
A = np.clip(A, 0, high)
|
|
729
|
+
# Cast unsupported integer types to uint8
|
|
730
|
+
if A.dtype != np.uint8 and np.issubdtype(A.dtype, np.integer):
|
|
731
|
+
A = A.astype(np.uint8)
|
|
732
|
+
return A
|
|
733
|
+
|
|
734
|
+
def set_data(self, A):
|
|
735
|
+
"""
|
|
736
|
+
Set the image array.
|
|
737
|
+
|
|
738
|
+
Note that this function does *not* update the normalization used.
|
|
739
|
+
|
|
740
|
+
Parameters
|
|
741
|
+
----------
|
|
742
|
+
A : array-like or `PIL.Image.Image`
|
|
743
|
+
"""
|
|
744
|
+
pil_image = sys.modules.get('PIL.Image')
|
|
745
|
+
if pil_image is not None and isinstance(A, pil_image.Image):
|
|
746
|
+
A = pil_to_array(A) # Needed e.g. to apply png palette.
|
|
747
|
+
self._A = self._normalize_image_array(A)
|
|
748
|
+
self._imcache = None
|
|
749
|
+
self.stale = True
|
|
750
|
+
|
|
751
|
+
def set_array(self, A):
|
|
752
|
+
"""
|
|
753
|
+
Retained for backwards compatibility - use set_data instead.
|
|
754
|
+
|
|
755
|
+
Parameters
|
|
756
|
+
----------
|
|
757
|
+
A : array-like
|
|
758
|
+
"""
|
|
759
|
+
# This also needs to be here to override the inherited
|
|
760
|
+
# cm.ScalarMappable.set_array method so it is not invoked by mistake.
|
|
761
|
+
self.set_data(A)
|
|
762
|
+
|
|
763
|
+
def get_interpolation(self):
|
|
764
|
+
"""
|
|
765
|
+
Return the interpolation method the image uses when resizing.
|
|
766
|
+
|
|
767
|
+
One of 'auto', 'antialiased', 'nearest', 'bilinear', 'bicubic',
|
|
768
|
+
'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser',
|
|
769
|
+
'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos',
|
|
770
|
+
or 'none'.
|
|
771
|
+
"""
|
|
772
|
+
return self._interpolation
|
|
773
|
+
|
|
774
|
+
def set_interpolation(self, s):
|
|
775
|
+
"""
|
|
776
|
+
Set the interpolation method the image uses when resizing.
|
|
777
|
+
|
|
778
|
+
If None, use :rc:`image.interpolation`. If 'none', the image is
|
|
779
|
+
shown as is without interpolating. 'none' is only supported in
|
|
780
|
+
agg, ps and pdf backends and will fall back to 'nearest' mode
|
|
781
|
+
for other backends.
|
|
782
|
+
|
|
783
|
+
Parameters
|
|
784
|
+
----------
|
|
785
|
+
s : {'auto', 'nearest', 'bilinear', 'bicubic', 'spline16', \
|
|
786
|
+
'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', \
|
|
787
|
+
'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', 'none'} or None
|
|
788
|
+
"""
|
|
789
|
+
s = mpl._val_or_rc(s, 'image.interpolation').lower()
|
|
790
|
+
_api.check_in_list(interpolations_names, interpolation=s)
|
|
791
|
+
self._interpolation = s
|
|
792
|
+
self.stale = True
|
|
793
|
+
|
|
794
|
+
def get_interpolation_stage(self):
|
|
795
|
+
"""
|
|
796
|
+
Return when interpolation happens during the transform to RGBA.
|
|
797
|
+
|
|
798
|
+
One of 'data', 'rgba', 'auto'.
|
|
799
|
+
"""
|
|
800
|
+
return self._interpolation_stage
|
|
801
|
+
|
|
802
|
+
def set_interpolation_stage(self, s):
|
|
803
|
+
"""
|
|
804
|
+
Set when interpolation happens during the transform to RGBA.
|
|
805
|
+
|
|
806
|
+
Parameters
|
|
807
|
+
----------
|
|
808
|
+
s : {'data', 'rgba', 'auto'}, default: :rc:`image.interpolation_stage`
|
|
809
|
+
Whether to apply resampling interpolation in data or RGBA space.
|
|
810
|
+
If 'auto', 'rgba' is used if the upsampling rate is less than 3,
|
|
811
|
+
otherwise 'data' is used.
|
|
812
|
+
"""
|
|
813
|
+
s = mpl._val_or_rc(s, 'image.interpolation_stage')
|
|
814
|
+
_api.check_in_list(['data', 'rgba', 'auto'], s=s)
|
|
815
|
+
self._interpolation_stage = s
|
|
816
|
+
self.stale = True
|
|
817
|
+
|
|
818
|
+
def can_composite(self):
|
|
819
|
+
"""Return whether the image can be composited with its neighbors."""
|
|
820
|
+
trans = self.get_transform()
|
|
821
|
+
return (
|
|
822
|
+
self._interpolation != 'none' and
|
|
823
|
+
trans.is_affine and
|
|
824
|
+
trans.is_separable)
|
|
825
|
+
|
|
826
|
+
def set_resample(self, v):
|
|
827
|
+
"""
|
|
828
|
+
Set whether image resampling is used.
|
|
829
|
+
|
|
830
|
+
Parameters
|
|
831
|
+
----------
|
|
832
|
+
v : bool, default: :rc:`image.resample`
|
|
833
|
+
"""
|
|
834
|
+
v = mpl._val_or_rc(v, 'image.resample')
|
|
835
|
+
self._resample = v
|
|
836
|
+
self.stale = True
|
|
837
|
+
|
|
838
|
+
def get_resample(self):
|
|
839
|
+
"""Return whether image resampling is used."""
|
|
840
|
+
return self._resample
|
|
841
|
+
|
|
842
|
+
def set_filternorm(self, filternorm):
|
|
843
|
+
"""
|
|
844
|
+
Set whether the resize filter normalizes the weights.
|
|
845
|
+
|
|
846
|
+
See help for `~.Axes.imshow`.
|
|
847
|
+
|
|
848
|
+
Parameters
|
|
849
|
+
----------
|
|
850
|
+
filternorm : bool
|
|
851
|
+
"""
|
|
852
|
+
self._filternorm = bool(filternorm)
|
|
853
|
+
self.stale = True
|
|
854
|
+
|
|
855
|
+
def get_filternorm(self):
|
|
856
|
+
"""Return whether the resize filter normalizes the weights."""
|
|
857
|
+
return self._filternorm
|
|
858
|
+
|
|
859
|
+
def set_filterrad(self, filterrad):
|
|
860
|
+
"""
|
|
861
|
+
Set the resize filter radius (only applicable to some
|
|
862
|
+
interpolation schemes).
|
|
863
|
+
|
|
864
|
+
See help for `~.Axes.imshow`.
|
|
865
|
+
|
|
866
|
+
Parameters
|
|
867
|
+
----------
|
|
868
|
+
filterrad : positive float
|
|
869
|
+
"""
|
|
870
|
+
r = float(filterrad)
|
|
871
|
+
if r <= 0:
|
|
872
|
+
raise ValueError("The filter radius must be a positive number")
|
|
873
|
+
self._filterrad = r
|
|
874
|
+
self.stale = True
|
|
875
|
+
|
|
876
|
+
def get_filterrad(self):
|
|
877
|
+
"""Return the filterrad setting."""
|
|
878
|
+
return self._filterrad
|
|
879
|
+
|
|
880
|
+
|
|
881
|
+
class AxesImage(_ImageBase):
|
|
882
|
+
"""
|
|
883
|
+
An image with pixels on a regular grid, attached to an Axes.
|
|
884
|
+
|
|
885
|
+
Parameters
|
|
886
|
+
----------
|
|
887
|
+
ax : `~matplotlib.axes.Axes`
|
|
888
|
+
The Axes the image will belong to.
|
|
889
|
+
cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
|
|
890
|
+
The Colormap instance or registered colormap name used to map scalar
|
|
891
|
+
data to colors.
|
|
892
|
+
norm : str or `~matplotlib.colors.Normalize`
|
|
893
|
+
Maps luminance to 0-1.
|
|
894
|
+
interpolation : str, default: :rc:`image.interpolation`
|
|
895
|
+
Supported values are 'none', 'auto', 'nearest', 'bilinear',
|
|
896
|
+
'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite',
|
|
897
|
+
'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell',
|
|
898
|
+
'sinc', 'lanczos', 'blackman'.
|
|
899
|
+
interpolation_stage : {'data', 'rgba'}, default: 'data'
|
|
900
|
+
If 'data', interpolation
|
|
901
|
+
is carried out on the data provided by the user. If 'rgba', the
|
|
902
|
+
interpolation is carried out after the colormapping has been
|
|
903
|
+
applied (visual interpolation).
|
|
904
|
+
origin : {'upper', 'lower'}, default: :rc:`image.origin`
|
|
905
|
+
Place the [0, 0] index of the array in the upper left or lower left
|
|
906
|
+
corner of the Axes. The convention 'upper' is typically used for
|
|
907
|
+
matrices and images.
|
|
908
|
+
extent : tuple, optional
|
|
909
|
+
The data axes (left, right, bottom, top) for making image plots
|
|
910
|
+
registered with data plots. Default is to label the pixel
|
|
911
|
+
centers with the zero-based row and column indices.
|
|
912
|
+
filternorm : bool, default: True
|
|
913
|
+
A parameter for the antigrain image resize filter
|
|
914
|
+
(see the antigrain documentation).
|
|
915
|
+
If filternorm is set, the filter normalizes integer values and corrects
|
|
916
|
+
the rounding errors. It doesn't do anything with the source floating
|
|
917
|
+
point values, it corrects only integers according to the rule of 1.0
|
|
918
|
+
which means that any sum of pixel weights must be equal to 1.0. So,
|
|
919
|
+
the filter function must produce a graph of the proper shape.
|
|
920
|
+
filterrad : float > 0, default: 4
|
|
921
|
+
The filter radius for filters that have a radius parameter, i.e. when
|
|
922
|
+
interpolation is one of: 'sinc', 'lanczos' or 'blackman'.
|
|
923
|
+
resample : bool, default: False
|
|
924
|
+
When True, use a full resampling method. When False, only resample when
|
|
925
|
+
the output image is larger than the input image.
|
|
926
|
+
**kwargs : `~matplotlib.artist.Artist` properties
|
|
927
|
+
"""
|
|
928
|
+
|
|
929
|
+
def __init__(self, ax,
|
|
930
|
+
*,
|
|
931
|
+
cmap=None,
|
|
932
|
+
norm=None,
|
|
933
|
+
colorizer=None,
|
|
934
|
+
interpolation=None,
|
|
935
|
+
origin=None,
|
|
936
|
+
extent=None,
|
|
937
|
+
filternorm=True,
|
|
938
|
+
filterrad=4.0,
|
|
939
|
+
resample=False,
|
|
940
|
+
interpolation_stage=None,
|
|
941
|
+
**kwargs
|
|
942
|
+
):
|
|
943
|
+
|
|
944
|
+
self._extent = extent
|
|
945
|
+
|
|
946
|
+
super().__init__(
|
|
947
|
+
ax,
|
|
948
|
+
cmap=cmap,
|
|
949
|
+
norm=norm,
|
|
950
|
+
colorizer=colorizer,
|
|
951
|
+
interpolation=interpolation,
|
|
952
|
+
origin=origin,
|
|
953
|
+
filternorm=filternorm,
|
|
954
|
+
filterrad=filterrad,
|
|
955
|
+
resample=resample,
|
|
956
|
+
interpolation_stage=interpolation_stage,
|
|
957
|
+
**kwargs
|
|
958
|
+
)
|
|
959
|
+
|
|
960
|
+
def get_window_extent(self, renderer=None):
|
|
961
|
+
x0, x1, y0, y1 = self._extent
|
|
962
|
+
bbox = Bbox.from_extents([x0, y0, x1, y1])
|
|
963
|
+
return bbox.transformed(self.get_transform())
|
|
964
|
+
|
|
965
|
+
def make_image(self, renderer, magnification=1.0, unsampled=False):
|
|
966
|
+
# docstring inherited
|
|
967
|
+
trans = self.get_transform()
|
|
968
|
+
# image is created in the canvas coordinate.
|
|
969
|
+
x1, x2, y1, y2 = self.get_extent()
|
|
970
|
+
bbox = Bbox(np.array([[x1, y1], [x2, y2]]))
|
|
971
|
+
transformed_bbox = TransformedBbox(bbox, trans)
|
|
972
|
+
clip = ((self.get_clip_box() or self.axes.bbox) if self.get_clip_on()
|
|
973
|
+
else self.get_figure(root=True).bbox)
|
|
974
|
+
return self._make_image(self._A, bbox, transformed_bbox, clip,
|
|
975
|
+
magnification, unsampled=unsampled)
|
|
976
|
+
|
|
977
|
+
def _check_unsampled_image(self):
|
|
978
|
+
"""Return whether the image would be better drawn unsampled."""
|
|
979
|
+
return self.get_interpolation() == "none"
|
|
980
|
+
|
|
981
|
+
def set_extent(self, extent, **kwargs):
|
|
982
|
+
"""
|
|
983
|
+
Set the image extent.
|
|
984
|
+
|
|
985
|
+
Parameters
|
|
986
|
+
----------
|
|
987
|
+
extent : 4-tuple of float
|
|
988
|
+
The position and size of the image as tuple
|
|
989
|
+
``(left, right, bottom, top)`` in data coordinates.
|
|
990
|
+
**kwargs
|
|
991
|
+
Other parameters from which unit info (i.e., the *xunits*,
|
|
992
|
+
*yunits*, *zunits* (for 3D Axes), *runits* and *thetaunits* (for
|
|
993
|
+
polar Axes) entries are applied, if present.
|
|
994
|
+
|
|
995
|
+
Notes
|
|
996
|
+
-----
|
|
997
|
+
This updates `.Axes.dataLim`, and, if autoscaling, sets `.Axes.viewLim`
|
|
998
|
+
to tightly fit the image, regardless of `~.Axes.dataLim`. Autoscaling
|
|
999
|
+
state is not changed, so a subsequent call to `.Axes.autoscale_view`
|
|
1000
|
+
will redo the autoscaling in accord with `~.Axes.dataLim`.
|
|
1001
|
+
"""
|
|
1002
|
+
(xmin, xmax), (ymin, ymax) = self.axes._process_unit_info(
|
|
1003
|
+
[("x", [extent[0], extent[1]]),
|
|
1004
|
+
("y", [extent[2], extent[3]])],
|
|
1005
|
+
kwargs)
|
|
1006
|
+
if kwargs:
|
|
1007
|
+
raise _api.kwarg_error("set_extent", kwargs)
|
|
1008
|
+
xmin = self.axes._validate_converted_limits(
|
|
1009
|
+
xmin, self.convert_xunits)
|
|
1010
|
+
xmax = self.axes._validate_converted_limits(
|
|
1011
|
+
xmax, self.convert_xunits)
|
|
1012
|
+
ymin = self.axes._validate_converted_limits(
|
|
1013
|
+
ymin, self.convert_yunits)
|
|
1014
|
+
ymax = self.axes._validate_converted_limits(
|
|
1015
|
+
ymax, self.convert_yunits)
|
|
1016
|
+
extent = [xmin, xmax, ymin, ymax]
|
|
1017
|
+
|
|
1018
|
+
self._extent = extent
|
|
1019
|
+
corners = (xmin, ymin), (xmax, ymax)
|
|
1020
|
+
self.axes.update_datalim(corners)
|
|
1021
|
+
self.sticky_edges.x[:] = [xmin, xmax]
|
|
1022
|
+
self.sticky_edges.y[:] = [ymin, ymax]
|
|
1023
|
+
if self.axes.get_autoscalex_on():
|
|
1024
|
+
self.axes.set_xlim(xmin, xmax, auto=None)
|
|
1025
|
+
if self.axes.get_autoscaley_on():
|
|
1026
|
+
self.axes.set_ylim(ymin, ymax, auto=None)
|
|
1027
|
+
self.stale = True
|
|
1028
|
+
|
|
1029
|
+
def get_extent(self):
|
|
1030
|
+
"""Return the image extent as tuple (left, right, bottom, top)."""
|
|
1031
|
+
if self._extent is not None:
|
|
1032
|
+
return self._extent
|
|
1033
|
+
else:
|
|
1034
|
+
sz = self.get_size()
|
|
1035
|
+
numrows, numcols = sz
|
|
1036
|
+
if self.origin == 'upper':
|
|
1037
|
+
return (-0.5, numcols-0.5, numrows-0.5, -0.5)
|
|
1038
|
+
else:
|
|
1039
|
+
return (-0.5, numcols-0.5, -0.5, numrows-0.5)
|
|
1040
|
+
|
|
1041
|
+
def get_cursor_data(self, event):
|
|
1042
|
+
"""
|
|
1043
|
+
Return the image value at the event position or *None* if the event is
|
|
1044
|
+
outside the image.
|
|
1045
|
+
|
|
1046
|
+
See Also
|
|
1047
|
+
--------
|
|
1048
|
+
matplotlib.artist.Artist.get_cursor_data
|
|
1049
|
+
"""
|
|
1050
|
+
xmin, xmax, ymin, ymax = self.get_extent()
|
|
1051
|
+
if self.origin == 'upper':
|
|
1052
|
+
ymin, ymax = ymax, ymin
|
|
1053
|
+
arr = self.get_array()
|
|
1054
|
+
data_extent = Bbox([[xmin, ymin], [xmax, ymax]])
|
|
1055
|
+
array_extent = Bbox([[0, 0], [arr.shape[1], arr.shape[0]]])
|
|
1056
|
+
trans = self.get_transform().inverted()
|
|
1057
|
+
trans += BboxTransform(boxin=data_extent, boxout=array_extent)
|
|
1058
|
+
point = trans.transform([event.x, event.y])
|
|
1059
|
+
if any(np.isnan(point)):
|
|
1060
|
+
return None
|
|
1061
|
+
j, i = point.astype(int)
|
|
1062
|
+
# Clip the coordinates at array bounds
|
|
1063
|
+
if not (0 <= i < arr.shape[0]) or not (0 <= j < arr.shape[1]):
|
|
1064
|
+
return None
|
|
1065
|
+
else:
|
|
1066
|
+
return arr[i, j]
|
|
1067
|
+
|
|
1068
|
+
|
|
1069
|
+
class NonUniformImage(AxesImage):
|
|
1070
|
+
"""
|
|
1071
|
+
An image with pixels on a rectilinear grid.
|
|
1072
|
+
|
|
1073
|
+
In contrast to `.AxesImage`, where pixels are on a regular grid,
|
|
1074
|
+
NonUniformImage allows rows and columns with individual heights / widths.
|
|
1075
|
+
|
|
1076
|
+
See also :doc:`/gallery/images_contours_and_fields/image_nonuniform`.
|
|
1077
|
+
"""
|
|
1078
|
+
|
|
1079
|
+
def __init__(self, ax, *, interpolation='nearest', **kwargs):
|
|
1080
|
+
"""
|
|
1081
|
+
Parameters
|
|
1082
|
+
----------
|
|
1083
|
+
ax : `~matplotlib.axes.Axes`
|
|
1084
|
+
The Axes the image will belong to.
|
|
1085
|
+
interpolation : {'nearest', 'bilinear'}, default: 'nearest'
|
|
1086
|
+
The interpolation scheme used in the resampling.
|
|
1087
|
+
**kwargs
|
|
1088
|
+
All other keyword arguments are identical to those of `.AxesImage`.
|
|
1089
|
+
"""
|
|
1090
|
+
super().__init__(ax, **kwargs)
|
|
1091
|
+
self.set_interpolation(interpolation)
|
|
1092
|
+
|
|
1093
|
+
def _check_unsampled_image(self):
|
|
1094
|
+
"""Return False. Do not use unsampled image."""
|
|
1095
|
+
return False
|
|
1096
|
+
|
|
1097
|
+
def make_image(self, renderer, magnification=1.0, unsampled=False):
|
|
1098
|
+
# docstring inherited
|
|
1099
|
+
if self._A is None:
|
|
1100
|
+
raise RuntimeError('You must first set the image array')
|
|
1101
|
+
if unsampled:
|
|
1102
|
+
raise ValueError('unsampled not supported on NonUniformImage')
|
|
1103
|
+
A = self._A
|
|
1104
|
+
if A.ndim == 2:
|
|
1105
|
+
if A.dtype != np.uint8:
|
|
1106
|
+
A = self.to_rgba(A, bytes=True)
|
|
1107
|
+
else:
|
|
1108
|
+
A = np.repeat(A[:, :, np.newaxis], 4, 2)
|
|
1109
|
+
A[:, :, 3] = 255
|
|
1110
|
+
else:
|
|
1111
|
+
if A.dtype != np.uint8:
|
|
1112
|
+
A = (255*A).astype(np.uint8)
|
|
1113
|
+
if A.shape[2] == 3:
|
|
1114
|
+
B = np.zeros(tuple([*A.shape[0:2], 4]), np.uint8)
|
|
1115
|
+
B[:, :, 0:3] = A
|
|
1116
|
+
B[:, :, 3] = 255
|
|
1117
|
+
A = B
|
|
1118
|
+
magnified_extents = (self.axes.bbox.extents * magnification + 0.5).astype(int)
|
|
1119
|
+
l, b, r, t = magnified_extents / magnification
|
|
1120
|
+
width = int((r - l) * magnification)
|
|
1121
|
+
height = int((t - b) * magnification)
|
|
1122
|
+
|
|
1123
|
+
invertedTransform = self.axes.transData.inverted()
|
|
1124
|
+
x_pix_edges = invertedTransform.transform(
|
|
1125
|
+
[(x, b) for x in np.linspace(l, r, width + 1)])[:, 0]
|
|
1126
|
+
y_pix_edges = invertedTransform.transform(
|
|
1127
|
+
[(l, y) for y in np.linspace(b, t, height + 1)])[:, 1]
|
|
1128
|
+
x_pix_centers = (x_pix_edges[:-1] + x_pix_edges[1:]) / 2
|
|
1129
|
+
y_pix_centers = (y_pix_edges[:-1] + y_pix_edges[1:]) / 2
|
|
1130
|
+
|
|
1131
|
+
if self._interpolation == "nearest":
|
|
1132
|
+
x_mid = (self._Ax[:-1] + self._Ax[1:]) / 2
|
|
1133
|
+
y_mid = (self._Ay[:-1] + self._Ay[1:]) / 2
|
|
1134
|
+
x_int = x_mid.searchsorted(x_pix_centers)
|
|
1135
|
+
y_int = y_mid.searchsorted(y_pix_centers)
|
|
1136
|
+
# The following is equal to `A[y_int[:, None], x_int[None, :]]`,
|
|
1137
|
+
# but many times faster. Both casting to uint32 (to have an
|
|
1138
|
+
# effectively 1D array) and manual index flattening matter.
|
|
1139
|
+
im = (
|
|
1140
|
+
np.ascontiguousarray(A).view(np.uint32).ravel()[
|
|
1141
|
+
np.add.outer(y_int * A.shape[1], x_int)]
|
|
1142
|
+
.view(np.uint8).reshape((height, width, 4)))
|
|
1143
|
+
else: # self._interpolation == "bilinear"
|
|
1144
|
+
# Use np.interp to compute x_int/x_float has similar speed.
|
|
1145
|
+
x_int = np.clip(
|
|
1146
|
+
self._Ax.searchsorted(x_pix_centers) - 1, 0, len(self._Ax) - 2)
|
|
1147
|
+
y_int = np.clip(
|
|
1148
|
+
self._Ay.searchsorted(y_pix_centers) - 1, 0, len(self._Ay) - 2)
|
|
1149
|
+
idx_int = np.add.outer(y_int * A.shape[1], x_int)
|
|
1150
|
+
x_frac = np.clip(
|
|
1151
|
+
np.divide(x_pix_centers - self._Ax[x_int], np.diff(self._Ax)[x_int],
|
|
1152
|
+
dtype=np.float32), # Downcasting helps with speed.
|
|
1153
|
+
0, 1)
|
|
1154
|
+
y_frac = np.clip(
|
|
1155
|
+
np.divide(y_pix_centers - self._Ay[y_int], np.diff(self._Ay)[y_int],
|
|
1156
|
+
dtype=np.float32),
|
|
1157
|
+
0, 1)
|
|
1158
|
+
f00 = np.outer(1 - y_frac, 1 - x_frac)
|
|
1159
|
+
f10 = np.outer(y_frac, 1 - x_frac)
|
|
1160
|
+
f01 = np.outer(1 - y_frac, x_frac)
|
|
1161
|
+
f11 = np.outer(y_frac, x_frac)
|
|
1162
|
+
im = np.empty((height, width, 4), np.uint8)
|
|
1163
|
+
for chan in range(4):
|
|
1164
|
+
ac = A[:, :, chan].reshape(-1) # reshape(-1) avoids a copy.
|
|
1165
|
+
# Shifting the buffer start (`ac[offset:]`) avoids an array
|
|
1166
|
+
# addition (`ac[idx_int + offset]`).
|
|
1167
|
+
buf = f00 * ac[idx_int]
|
|
1168
|
+
buf += f10 * ac[A.shape[1]:][idx_int]
|
|
1169
|
+
buf += f01 * ac[1:][idx_int]
|
|
1170
|
+
buf += f11 * ac[A.shape[1] + 1:][idx_int]
|
|
1171
|
+
im[:, :, chan] = buf # Implicitly casts to uint8.
|
|
1172
|
+
return im, l, b, IdentityTransform()
|
|
1173
|
+
|
|
1174
|
+
def set_data(self, x, y, A):
|
|
1175
|
+
"""
|
|
1176
|
+
Set the grid for the pixel centers, and the pixel values.
|
|
1177
|
+
|
|
1178
|
+
Parameters
|
|
1179
|
+
----------
|
|
1180
|
+
x, y : 1D array-like
|
|
1181
|
+
Monotonic arrays of shapes (N,) and (M,), respectively, specifying
|
|
1182
|
+
pixel centers.
|
|
1183
|
+
A : array-like
|
|
1184
|
+
(M, N) `~numpy.ndarray` or masked array of values to be
|
|
1185
|
+
colormapped, or (M, N, 3) RGB array, or (M, N, 4) RGBA array.
|
|
1186
|
+
"""
|
|
1187
|
+
A = self._normalize_image_array(A)
|
|
1188
|
+
x = np.array(x, np.float32)
|
|
1189
|
+
y = np.array(y, np.float32)
|
|
1190
|
+
if not (x.ndim == y.ndim == 1 and A.shape[:2] == y.shape + x.shape):
|
|
1191
|
+
raise TypeError("Axes don't match array shape")
|
|
1192
|
+
self._A = A
|
|
1193
|
+
self._Ax = x
|
|
1194
|
+
self._Ay = y
|
|
1195
|
+
self._imcache = None
|
|
1196
|
+
self.stale = True
|
|
1197
|
+
|
|
1198
|
+
def set_array(self, *args):
|
|
1199
|
+
raise NotImplementedError('Method not supported')
|
|
1200
|
+
|
|
1201
|
+
def set_interpolation(self, s):
|
|
1202
|
+
"""
|
|
1203
|
+
Parameters
|
|
1204
|
+
----------
|
|
1205
|
+
s : {'nearest', 'bilinear'} or None
|
|
1206
|
+
If None, use :rc:`image.interpolation`.
|
|
1207
|
+
"""
|
|
1208
|
+
if s is not None and s not in ('nearest', 'bilinear'):
|
|
1209
|
+
raise NotImplementedError('Only nearest neighbor and '
|
|
1210
|
+
'bilinear interpolations are supported')
|
|
1211
|
+
super().set_interpolation(s)
|
|
1212
|
+
|
|
1213
|
+
def get_extent(self):
|
|
1214
|
+
if self._A is None:
|
|
1215
|
+
raise RuntimeError('Must set data first')
|
|
1216
|
+
return self._Ax[0], self._Ax[-1], self._Ay[0], self._Ay[-1]
|
|
1217
|
+
|
|
1218
|
+
def set_filternorm(self, filternorm):
|
|
1219
|
+
pass
|
|
1220
|
+
|
|
1221
|
+
def set_filterrad(self, filterrad):
|
|
1222
|
+
pass
|
|
1223
|
+
|
|
1224
|
+
def set_norm(self, norm):
|
|
1225
|
+
if self._A is not None:
|
|
1226
|
+
raise RuntimeError('Cannot change colors after loading data')
|
|
1227
|
+
super().set_norm(norm)
|
|
1228
|
+
|
|
1229
|
+
def set_cmap(self, cmap):
|
|
1230
|
+
if self._A is not None:
|
|
1231
|
+
raise RuntimeError('Cannot change colors after loading data')
|
|
1232
|
+
super().set_cmap(cmap)
|
|
1233
|
+
|
|
1234
|
+
def get_cursor_data(self, event):
|
|
1235
|
+
# docstring inherited
|
|
1236
|
+
x, y = event.xdata, event.ydata
|
|
1237
|
+
if (x < self._Ax[0] or x > self._Ax[-1] or
|
|
1238
|
+
y < self._Ay[0] or y > self._Ay[-1]):
|
|
1239
|
+
return None
|
|
1240
|
+
j = np.searchsorted(self._Ax, x) - 1
|
|
1241
|
+
i = np.searchsorted(self._Ay, y) - 1
|
|
1242
|
+
return self._A[i, j]
|
|
1243
|
+
|
|
1244
|
+
|
|
1245
|
+
class PcolorImage(AxesImage):
|
|
1246
|
+
"""
|
|
1247
|
+
Make a pcolor-style plot with an irregular rectangular grid.
|
|
1248
|
+
|
|
1249
|
+
This uses a variation of the original irregular image code,
|
|
1250
|
+
and it is used by pcolorfast for the corresponding grid type.
|
|
1251
|
+
"""
|
|
1252
|
+
|
|
1253
|
+
def __init__(self, ax,
|
|
1254
|
+
x=None,
|
|
1255
|
+
y=None,
|
|
1256
|
+
A=None,
|
|
1257
|
+
*,
|
|
1258
|
+
cmap=None,
|
|
1259
|
+
norm=None,
|
|
1260
|
+
colorizer=None,
|
|
1261
|
+
**kwargs
|
|
1262
|
+
):
|
|
1263
|
+
"""
|
|
1264
|
+
Parameters
|
|
1265
|
+
----------
|
|
1266
|
+
ax : `~matplotlib.axes.Axes`
|
|
1267
|
+
The Axes the image will belong to.
|
|
1268
|
+
x, y : 1D array-like, optional
|
|
1269
|
+
Monotonic arrays of length N+1 and M+1, respectively, specifying
|
|
1270
|
+
rectangle boundaries. If not given, will default to
|
|
1271
|
+
``range(N + 1)`` and ``range(M + 1)``, respectively.
|
|
1272
|
+
A : array-like
|
|
1273
|
+
The data to be color-coded. The interpretation depends on the
|
|
1274
|
+
shape:
|
|
1275
|
+
|
|
1276
|
+
- (M, N) `~numpy.ndarray` or masked array: values to be colormapped
|
|
1277
|
+
- (M, N, 3): RGB array
|
|
1278
|
+
- (M, N, 4): RGBA array
|
|
1279
|
+
|
|
1280
|
+
cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
|
|
1281
|
+
The Colormap instance or registered colormap name used to map
|
|
1282
|
+
scalar data to colors.
|
|
1283
|
+
norm : str or `~matplotlib.colors.Normalize`
|
|
1284
|
+
Maps luminance to 0-1.
|
|
1285
|
+
**kwargs : `~matplotlib.artist.Artist` properties
|
|
1286
|
+
"""
|
|
1287
|
+
super().__init__(ax, norm=norm, cmap=cmap, colorizer=colorizer)
|
|
1288
|
+
self._internal_update(kwargs)
|
|
1289
|
+
if A is not None:
|
|
1290
|
+
self.set_data(x, y, A)
|
|
1291
|
+
|
|
1292
|
+
def make_image(self, renderer, magnification=1.0, unsampled=False):
|
|
1293
|
+
# docstring inherited
|
|
1294
|
+
if self._A is None:
|
|
1295
|
+
raise RuntimeError('You must first set the image array')
|
|
1296
|
+
if unsampled:
|
|
1297
|
+
raise ValueError('unsampled not supported on PColorImage')
|
|
1298
|
+
|
|
1299
|
+
if self._imcache is None:
|
|
1300
|
+
A = self.to_rgba(self._A, bytes=True)
|
|
1301
|
+
self._imcache = np.pad(A, [(1, 1), (1, 1), (0, 0)], "constant")
|
|
1302
|
+
padded_A = self._imcache
|
|
1303
|
+
bg = mcolors.to_rgba(self.axes.patch.get_facecolor(), 0)
|
|
1304
|
+
bg = (np.array(bg) * 255).astype(np.uint8)
|
|
1305
|
+
if (padded_A[0, 0] != bg).all():
|
|
1306
|
+
padded_A[[0, -1], :] = padded_A[:, [0, -1]] = bg
|
|
1307
|
+
|
|
1308
|
+
# Round to the nearest output pixels after magnification
|
|
1309
|
+
l, b, r, t = (self.axes.bbox.extents * magnification + 0.5).astype(int)
|
|
1310
|
+
width = r - l
|
|
1311
|
+
height = t - b
|
|
1312
|
+
|
|
1313
|
+
vl = self.axes.viewLim
|
|
1314
|
+
|
|
1315
|
+
x_pix_edges = np.linspace(vl.x0, vl.x1, width + 1)
|
|
1316
|
+
y_pix_edges = np.linspace(vl.y0, vl.y1, height + 1)
|
|
1317
|
+
x_pix_centers = (x_pix_edges[:-1] + x_pix_edges[1:]) / 2
|
|
1318
|
+
y_pix_centers = (y_pix_edges[:-1] + y_pix_edges[1:]) / 2
|
|
1319
|
+
x_int = self._Ax.searchsorted(x_pix_centers)
|
|
1320
|
+
y_int = self._Ay.searchsorted(y_pix_centers)
|
|
1321
|
+
im = ( # See comment in NonUniformImage.make_image re: performance.
|
|
1322
|
+
padded_A.view(np.uint32).ravel()[
|
|
1323
|
+
np.add.outer(y_int * padded_A.shape[1], x_int)]
|
|
1324
|
+
.view(np.uint8).reshape((height, width, 4)))
|
|
1325
|
+
return im, l / magnification, b / magnification, IdentityTransform()
|
|
1326
|
+
|
|
1327
|
+
def _check_unsampled_image(self):
|
|
1328
|
+
return False
|
|
1329
|
+
|
|
1330
|
+
def set_data(self, x, y, A):
|
|
1331
|
+
"""
|
|
1332
|
+
Set the grid for the rectangle boundaries, and the data values.
|
|
1333
|
+
|
|
1334
|
+
Parameters
|
|
1335
|
+
----------
|
|
1336
|
+
x, y : 1D array-like, optional
|
|
1337
|
+
Monotonic arrays of length N+1 and M+1, respectively, specifying
|
|
1338
|
+
rectangle boundaries. If not given, will default to
|
|
1339
|
+
``range(N + 1)`` and ``range(M + 1)``, respectively.
|
|
1340
|
+
A : array-like
|
|
1341
|
+
The data to be color-coded. The interpretation depends on the
|
|
1342
|
+
shape:
|
|
1343
|
+
|
|
1344
|
+
- (M, N) `~numpy.ndarray` or masked array: values to be colormapped
|
|
1345
|
+
- (M, N, 3): RGB array
|
|
1346
|
+
- (M, N, 4): RGBA array
|
|
1347
|
+
"""
|
|
1348
|
+
A = self._normalize_image_array(A)
|
|
1349
|
+
x = np.arange(0., A.shape[1] + 1) if x is None else np.array(x, float).ravel()
|
|
1350
|
+
y = np.arange(0., A.shape[0] + 1) if y is None else np.array(y, float).ravel()
|
|
1351
|
+
if A.shape[:2] != (y.size - 1, x.size - 1):
|
|
1352
|
+
raise ValueError(
|
|
1353
|
+
"Axes don't match array shape. Got %s, expected %s." %
|
|
1354
|
+
(A.shape[:2], (y.size - 1, x.size - 1)))
|
|
1355
|
+
# For efficient cursor readout, ensure x and y are increasing.
|
|
1356
|
+
if x[-1] < x[0]:
|
|
1357
|
+
x = x[::-1]
|
|
1358
|
+
A = A[:, ::-1]
|
|
1359
|
+
if y[-1] < y[0]:
|
|
1360
|
+
y = y[::-1]
|
|
1361
|
+
A = A[::-1]
|
|
1362
|
+
self._A = A
|
|
1363
|
+
self._Ax = x
|
|
1364
|
+
self._Ay = y
|
|
1365
|
+
self._imcache = None
|
|
1366
|
+
self.stale = True
|
|
1367
|
+
|
|
1368
|
+
def set_array(self, *args):
|
|
1369
|
+
raise NotImplementedError('Method not supported')
|
|
1370
|
+
|
|
1371
|
+
def get_cursor_data(self, event):
|
|
1372
|
+
# docstring inherited
|
|
1373
|
+
x, y = event.xdata, event.ydata
|
|
1374
|
+
if (x < self._Ax[0] or x > self._Ax[-1] or
|
|
1375
|
+
y < self._Ay[0] or y > self._Ay[-1]):
|
|
1376
|
+
return None
|
|
1377
|
+
j = np.searchsorted(self._Ax, x) - 1
|
|
1378
|
+
i = np.searchsorted(self._Ay, y) - 1
|
|
1379
|
+
return self._A[i, j]
|
|
1380
|
+
|
|
1381
|
+
|
|
1382
|
+
class FigureImage(_ImageBase):
|
|
1383
|
+
"""An image attached to a figure."""
|
|
1384
|
+
|
|
1385
|
+
zorder = 0
|
|
1386
|
+
|
|
1387
|
+
_interpolation = 'nearest'
|
|
1388
|
+
|
|
1389
|
+
def __init__(self, fig,
|
|
1390
|
+
*,
|
|
1391
|
+
cmap=None,
|
|
1392
|
+
norm=None,
|
|
1393
|
+
colorizer=None,
|
|
1394
|
+
offsetx=0,
|
|
1395
|
+
offsety=0,
|
|
1396
|
+
origin=None,
|
|
1397
|
+
**kwargs
|
|
1398
|
+
):
|
|
1399
|
+
"""
|
|
1400
|
+
cmap is a colors.Colormap instance
|
|
1401
|
+
norm is a colors.Normalize instance to map luminance to 0-1
|
|
1402
|
+
|
|
1403
|
+
kwargs are an optional list of Artist keyword args
|
|
1404
|
+
"""
|
|
1405
|
+
super().__init__(
|
|
1406
|
+
None,
|
|
1407
|
+
norm=norm,
|
|
1408
|
+
cmap=cmap,
|
|
1409
|
+
colorizer=colorizer,
|
|
1410
|
+
origin=origin
|
|
1411
|
+
)
|
|
1412
|
+
self.set_figure(fig)
|
|
1413
|
+
self.ox = offsetx
|
|
1414
|
+
self.oy = offsety
|
|
1415
|
+
self._internal_update(kwargs)
|
|
1416
|
+
self.magnification = 1.0
|
|
1417
|
+
|
|
1418
|
+
def get_extent(self):
|
|
1419
|
+
"""Return the image extent as tuple (left, right, bottom, top)."""
|
|
1420
|
+
numrows, numcols = self.get_size()
|
|
1421
|
+
return (-0.5 + self.ox, numcols-0.5 + self.ox,
|
|
1422
|
+
-0.5 + self.oy, numrows-0.5 + self.oy)
|
|
1423
|
+
|
|
1424
|
+
def make_image(self, renderer, magnification=1.0, unsampled=False):
|
|
1425
|
+
# docstring inherited
|
|
1426
|
+
fig = self.get_figure(root=True)
|
|
1427
|
+
fac = renderer.dpi/fig.dpi
|
|
1428
|
+
# fac here is to account for pdf, eps, svg backends where
|
|
1429
|
+
# figure.dpi is set to 72. This means we need to scale the
|
|
1430
|
+
# image (using magnification) and offset it appropriately.
|
|
1431
|
+
bbox = Bbox([[self.ox/fac, self.oy/fac],
|
|
1432
|
+
[(self.ox/fac + self._A.shape[1]),
|
|
1433
|
+
(self.oy/fac + self._A.shape[0])]])
|
|
1434
|
+
width, height = fig.get_size_inches()
|
|
1435
|
+
width *= renderer.dpi
|
|
1436
|
+
height *= renderer.dpi
|
|
1437
|
+
clip = Bbox([[0, 0], [width, height]])
|
|
1438
|
+
return self._make_image(
|
|
1439
|
+
self._A, bbox, bbox, clip, magnification=magnification / fac,
|
|
1440
|
+
unsampled=unsampled, round_to_pixel_border=False)
|
|
1441
|
+
|
|
1442
|
+
def set_data(self, A):
|
|
1443
|
+
"""Set the image array."""
|
|
1444
|
+
super().set_data(A)
|
|
1445
|
+
self.stale = True
|
|
1446
|
+
|
|
1447
|
+
|
|
1448
|
+
class BboxImage(_ImageBase):
|
|
1449
|
+
"""
|
|
1450
|
+
The Image class whose size is determined by the given bbox.
|
|
1451
|
+
|
|
1452
|
+
Parameters
|
|
1453
|
+
----------
|
|
1454
|
+
bbox : BboxBase or Callable[RendererBase, BboxBase]
|
|
1455
|
+
The bbox or a function to generate the bbox
|
|
1456
|
+
|
|
1457
|
+
.. warning ::
|
|
1458
|
+
|
|
1459
|
+
If using `matplotlib.artist.Artist.get_window_extent` as the
|
|
1460
|
+
callable ensure that the other artist is drawn first (lower zorder)
|
|
1461
|
+
or you may need to renderer the figure twice to ensure that the
|
|
1462
|
+
computed bbox is accurate.
|
|
1463
|
+
|
|
1464
|
+
cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
|
|
1465
|
+
The Colormap instance or registered colormap name used to map scalar
|
|
1466
|
+
data to colors. This parameter is ignored if X is RGB(A).
|
|
1467
|
+
norm : str or `~matplotlib.colors.Normalize`
|
|
1468
|
+
Maps luminance to 0-1. This parameter is ignored if X is RGB(A).
|
|
1469
|
+
interpolation : str, default: :rc:`image.interpolation`
|
|
1470
|
+
Supported values are 'none', 'auto', 'nearest', 'bilinear',
|
|
1471
|
+
'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite',
|
|
1472
|
+
'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell',
|
|
1473
|
+
'sinc', 'lanczos', 'blackman'.
|
|
1474
|
+
origin : {'upper', 'lower'}, default: :rc:`image.origin`
|
|
1475
|
+
Place the [0, 0] index of the array in the upper left or lower left
|
|
1476
|
+
corner of the Axes. The convention 'upper' is typically used for
|
|
1477
|
+
matrices and images.
|
|
1478
|
+
filternorm : bool, default: True
|
|
1479
|
+
A parameter for the antigrain image resize filter
|
|
1480
|
+
(see the antigrain documentation).
|
|
1481
|
+
If filternorm is set, the filter normalizes integer values and corrects
|
|
1482
|
+
the rounding errors. It doesn't do anything with the source floating
|
|
1483
|
+
point values, it corrects only integers according to the rule of 1.0
|
|
1484
|
+
which means that any sum of pixel weights must be equal to 1.0. So,
|
|
1485
|
+
the filter function must produce a graph of the proper shape.
|
|
1486
|
+
filterrad : float > 0, default: 4
|
|
1487
|
+
The filter radius for filters that have a radius parameter, i.e. when
|
|
1488
|
+
interpolation is one of: 'sinc', 'lanczos' or 'blackman'.
|
|
1489
|
+
resample : bool, default: False
|
|
1490
|
+
When True, use a full resampling method. When False, only resample when
|
|
1491
|
+
the output image is larger than the input image.
|
|
1492
|
+
**kwargs : `~matplotlib.artist.Artist` properties
|
|
1493
|
+
|
|
1494
|
+
"""
|
|
1495
|
+
def __init__(self, bbox,
|
|
1496
|
+
*,
|
|
1497
|
+
cmap=None,
|
|
1498
|
+
norm=None,
|
|
1499
|
+
colorizer=None,
|
|
1500
|
+
interpolation=None,
|
|
1501
|
+
origin=None,
|
|
1502
|
+
filternorm=True,
|
|
1503
|
+
filterrad=4.0,
|
|
1504
|
+
resample=False,
|
|
1505
|
+
**kwargs
|
|
1506
|
+
):
|
|
1507
|
+
|
|
1508
|
+
super().__init__(
|
|
1509
|
+
None,
|
|
1510
|
+
cmap=cmap,
|
|
1511
|
+
norm=norm,
|
|
1512
|
+
colorizer=colorizer,
|
|
1513
|
+
interpolation=interpolation,
|
|
1514
|
+
origin=origin,
|
|
1515
|
+
filternorm=filternorm,
|
|
1516
|
+
filterrad=filterrad,
|
|
1517
|
+
resample=resample,
|
|
1518
|
+
**kwargs
|
|
1519
|
+
)
|
|
1520
|
+
self.bbox = bbox
|
|
1521
|
+
|
|
1522
|
+
def get_window_extent(self, renderer=None):
|
|
1523
|
+
if isinstance(self.bbox, BboxBase):
|
|
1524
|
+
return self.bbox
|
|
1525
|
+
elif callable(self.bbox):
|
|
1526
|
+
if renderer is None:
|
|
1527
|
+
renderer = self.get_figure()._get_renderer()
|
|
1528
|
+
return self.bbox(renderer)
|
|
1529
|
+
else:
|
|
1530
|
+
raise ValueError("Unknown type of bbox")
|
|
1531
|
+
|
|
1532
|
+
def contains(self, mouseevent):
|
|
1533
|
+
"""Test whether the mouse event occurred within the image."""
|
|
1534
|
+
if self._different_canvas(mouseevent) or not self.get_visible():
|
|
1535
|
+
return False, {}
|
|
1536
|
+
x, y = mouseevent.x, mouseevent.y
|
|
1537
|
+
inside = self.get_window_extent().contains(x, y)
|
|
1538
|
+
return inside, {}
|
|
1539
|
+
|
|
1540
|
+
def make_image(self, renderer, magnification=1.0, unsampled=False):
|
|
1541
|
+
# docstring inherited
|
|
1542
|
+
width, height = renderer.get_canvas_width_height()
|
|
1543
|
+
bbox_in = self.get_window_extent(renderer).frozen()
|
|
1544
|
+
bbox_in._points /= [width, height]
|
|
1545
|
+
bbox_out = self.get_window_extent(renderer)
|
|
1546
|
+
clip = Bbox([[0, 0], [width, height]])
|
|
1547
|
+
self._transform = BboxTransformTo(clip)
|
|
1548
|
+
return self._make_image(
|
|
1549
|
+
self._A,
|
|
1550
|
+
bbox_in, bbox_out, clip, magnification, unsampled=unsampled)
|
|
1551
|
+
|
|
1552
|
+
|
|
1553
|
+
def imread(fname, format=None):
|
|
1554
|
+
"""
|
|
1555
|
+
Read an image from a file into an array.
|
|
1556
|
+
|
|
1557
|
+
.. note::
|
|
1558
|
+
|
|
1559
|
+
This function exists for historical reasons. It is recommended to
|
|
1560
|
+
use `PIL.Image.open` instead for loading images.
|
|
1561
|
+
|
|
1562
|
+
Parameters
|
|
1563
|
+
----------
|
|
1564
|
+
fname : str or file-like
|
|
1565
|
+
The image file to read: a filename, a URL or a file-like object opened
|
|
1566
|
+
in read-binary mode.
|
|
1567
|
+
|
|
1568
|
+
Passing a URL is deprecated. Please open the URL
|
|
1569
|
+
for reading and pass the result to Pillow, e.g. with
|
|
1570
|
+
``np.array(PIL.Image.open(urllib.request.urlopen(url)))``.
|
|
1571
|
+
format : str, optional
|
|
1572
|
+
The image file format assumed for reading the data. The image is
|
|
1573
|
+
loaded as a PNG file if *format* is set to "png", if *fname* is a path
|
|
1574
|
+
or opened file with a ".png" extension, or if it is a URL. In all
|
|
1575
|
+
other cases, *format* is ignored and the format is auto-detected by
|
|
1576
|
+
`PIL.Image.open`.
|
|
1577
|
+
|
|
1578
|
+
Returns
|
|
1579
|
+
-------
|
|
1580
|
+
`numpy.array`
|
|
1581
|
+
The image data. The returned array has shape
|
|
1582
|
+
|
|
1583
|
+
- (M, N) for grayscale images.
|
|
1584
|
+
- (M, N, 3) for RGB images.
|
|
1585
|
+
- (M, N, 4) for RGBA images.
|
|
1586
|
+
|
|
1587
|
+
PNG images are returned as float arrays (0-1). All other formats are
|
|
1588
|
+
returned as int arrays, with a bit depth determined by the file's
|
|
1589
|
+
contents.
|
|
1590
|
+
"""
|
|
1591
|
+
# hide imports to speed initial import on systems with slow linkers
|
|
1592
|
+
from urllib import parse
|
|
1593
|
+
|
|
1594
|
+
if format is None:
|
|
1595
|
+
if isinstance(fname, str):
|
|
1596
|
+
parsed = parse.urlparse(fname)
|
|
1597
|
+
# If the string is a URL (Windows paths appear as if they have a
|
|
1598
|
+
# length-1 scheme), assume png.
|
|
1599
|
+
if len(parsed.scheme) > 1:
|
|
1600
|
+
ext = 'png'
|
|
1601
|
+
else:
|
|
1602
|
+
ext = Path(fname).suffix.lower()[1:]
|
|
1603
|
+
elif hasattr(fname, 'geturl'): # Returned by urlopen().
|
|
1604
|
+
# We could try to parse the url's path and use the extension, but
|
|
1605
|
+
# returning png is consistent with the block above. Note that this
|
|
1606
|
+
# if clause has to come before checking for fname.name as
|
|
1607
|
+
# urlopen("file:///...") also has a name attribute (with the fixed
|
|
1608
|
+
# value "<urllib response>").
|
|
1609
|
+
ext = 'png'
|
|
1610
|
+
elif hasattr(fname, 'name'):
|
|
1611
|
+
ext = Path(fname.name).suffix.lower()[1:]
|
|
1612
|
+
else:
|
|
1613
|
+
ext = 'png'
|
|
1614
|
+
else:
|
|
1615
|
+
ext = format
|
|
1616
|
+
if isinstance(fname, str) and len(parse.urlparse(fname).scheme) > 1:
|
|
1617
|
+
raise ValueError(
|
|
1618
|
+
"Please open the URL for reading and pass the result to imread, e.g. "
|
|
1619
|
+
"with ``imread(urllib.request.urlopen(url))``.")
|
|
1620
|
+
# PNG files as 0-1 floats, JPEG, TIFF, GIF and WebP files as Pillow's
|
|
1621
|
+
# pil_to_array returns them; all decoded by the Rust core.
|
|
1622
|
+
return _imageio.read(fname, ext)
|
|
1623
|
+
|
|
1624
|
+
|
|
1625
|
+
def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
|
|
1626
|
+
origin=None, dpi=100, *, metadata=None, pil_kwargs=None):
|
|
1627
|
+
"""
|
|
1628
|
+
Colormap and save an array as an image file.
|
|
1629
|
+
|
|
1630
|
+
RGB(A) images are passed through. Single channel images will be
|
|
1631
|
+
colormapped according to *cmap* and *norm*.
|
|
1632
|
+
|
|
1633
|
+
.. note::
|
|
1634
|
+
|
|
1635
|
+
If you want to save a single channel image as gray scale please use an
|
|
1636
|
+
image I/O library (such as pillow, tifffile, or imageio) directly.
|
|
1637
|
+
|
|
1638
|
+
Parameters
|
|
1639
|
+
----------
|
|
1640
|
+
fname : str or path-like or file-like
|
|
1641
|
+
A path or a file-like object to store the image in.
|
|
1642
|
+
If *format* is not set, then the output format is inferred from the
|
|
1643
|
+
extension of *fname*, if any, and from :rc:`savefig.format` otherwise.
|
|
1644
|
+
If *format* is set, it determines the output format.
|
|
1645
|
+
arr : array-like
|
|
1646
|
+
The image data. Accepts NumPy arrays or sequences
|
|
1647
|
+
(e.g., lists or tuples). The shape can be one of
|
|
1648
|
+
MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA).
|
|
1649
|
+
vmin, vmax : float, optional
|
|
1650
|
+
*vmin* and *vmax* set the color scaling for the image by fixing the
|
|
1651
|
+
values that map to the colormap color limits. If either *vmin*
|
|
1652
|
+
or *vmax* is None, that limit is determined from the *arr*
|
|
1653
|
+
min/max value.
|
|
1654
|
+
cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
|
|
1655
|
+
A Colormap instance or registered colormap name. The colormap
|
|
1656
|
+
maps scalar data to colors. It is ignored for RGB(A) data.
|
|
1657
|
+
format : str, optional
|
|
1658
|
+
The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this
|
|
1659
|
+
is unset is documented under *fname*.
|
|
1660
|
+
origin : {'upper', 'lower'}, default: :rc:`image.origin`
|
|
1661
|
+
Indicates whether the ``(0, 0)`` index of the array is in the upper
|
|
1662
|
+
left or lower left corner of the Axes.
|
|
1663
|
+
dpi : float
|
|
1664
|
+
The DPI to store in the metadata of the file. This does not affect the
|
|
1665
|
+
resolution of the output image. Depending on file format, this may be
|
|
1666
|
+
rounded to the nearest integer.
|
|
1667
|
+
metadata : dict, optional
|
|
1668
|
+
Metadata in the image file. The supported keys depend on the output
|
|
1669
|
+
format, see the documentation of the respective backends for more
|
|
1670
|
+
information.
|
|
1671
|
+
Currently only supported for "png", "pdf", "ps", "eps", and "svg".
|
|
1672
|
+
pil_kwargs : dict, optional
|
|
1673
|
+
Keyword arguments passed to `PIL.Image.Image.save`. If the 'pnginfo'
|
|
1674
|
+
key is present, it completely overrides *metadata*, including the
|
|
1675
|
+
default 'Software' key.
|
|
1676
|
+
|
|
1677
|
+
matplotlib_rs writes every format with the Rust core instead (Pillow
|
|
1678
|
+
is not used); the options it supports for each format, with Pillow's
|
|
1679
|
+
meaning, are listed in `matplotlib_rs._imageio`.
|
|
1680
|
+
"""
|
|
1681
|
+
from matplotlib_rs.figure import Figure
|
|
1682
|
+
|
|
1683
|
+
# Normalizing input (e.g., list or tuples) to NumPy array if needed
|
|
1684
|
+
arr = np.asanyarray(arr)
|
|
1685
|
+
|
|
1686
|
+
if isinstance(fname, os.PathLike):
|
|
1687
|
+
fname = os.fspath(fname)
|
|
1688
|
+
if format is None:
|
|
1689
|
+
format = (Path(fname).suffix[1:] if isinstance(fname, str)
|
|
1690
|
+
else mpl.rcParams["savefig.format"]).lower()
|
|
1691
|
+
if format in ["pdf", "ps", "eps", "svg"]:
|
|
1692
|
+
# Vector formats that are not handled by PIL.
|
|
1693
|
+
if pil_kwargs is not None:
|
|
1694
|
+
raise ValueError(
|
|
1695
|
+
f"Cannot use 'pil_kwargs' when saving to {format}")
|
|
1696
|
+
fig = Figure(dpi=dpi, frameon=False)
|
|
1697
|
+
fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin,
|
|
1698
|
+
resize=True)
|
|
1699
|
+
fig.savefig(fname, dpi=dpi, format=format, transparent=True,
|
|
1700
|
+
metadata=metadata)
|
|
1701
|
+
else:
|
|
1702
|
+
# Don't bother creating an image; this avoids rounding errors on the
|
|
1703
|
+
# size when dividing and then multiplying by dpi.
|
|
1704
|
+
origin = mpl._val_or_rc(origin, "image.origin")
|
|
1705
|
+
_api.check_in_list(('upper', 'lower'), origin=origin)
|
|
1706
|
+
if origin == "lower":
|
|
1707
|
+
arr = arr[::-1]
|
|
1708
|
+
if (isinstance(arr, memoryview) and arr.format == "B"
|
|
1709
|
+
and arr.ndim == 3 and arr.shape[-1] == 4):
|
|
1710
|
+
# Such an ``arr`` would also be handled fine by sm.to_rgba below
|
|
1711
|
+
# (after casting with asarray), but it is useful to special-case it
|
|
1712
|
+
# because that's what backend_agg passes, and can be in fact used
|
|
1713
|
+
# as is, saving a few operations.
|
|
1714
|
+
rgba = arr
|
|
1715
|
+
else:
|
|
1716
|
+
sm = mcolorizer.Colorizer(cmap=cmap)
|
|
1717
|
+
sm.set_clim(vmin, vmax)
|
|
1718
|
+
rgba = sm.to_rgba(arr, bytes=True)
|
|
1719
|
+
fmt = _imageio.canonical_format(format)
|
|
1720
|
+
if fmt is None:
|
|
1721
|
+
raise ValueError(
|
|
1722
|
+
f"Format {format!r} is not supported (matplotlib_rs writes png, jpg, "
|
|
1723
|
+
f"tiff, gif, webp and avif images, and pdf, ps, eps and svg files)")
|
|
1724
|
+
background = None
|
|
1725
|
+
if fmt == "jpeg":
|
|
1726
|
+
facecolor = mpl.rcParams["savefig.facecolor"]
|
|
1727
|
+
if cbook._str_equal(facecolor, "auto"):
|
|
1728
|
+
facecolor = mpl.rcParams["figure.facecolor"]
|
|
1729
|
+
background = tuple(int(x * 255) for x in mcolors.to_rgb(facecolor))
|
|
1730
|
+
# Written by the Rust core, with Pillow's options (see _imageio).
|
|
1731
|
+
_imageio.save(fname, np.require(rgba, requirements='C'), fmt, dpi=dpi,
|
|
1732
|
+
metadata=metadata, pil_kwargs=pil_kwargs, background=background)
|
|
1733
|
+
|
|
1734
|
+
|
|
1735
|
+
def pil_to_array(pilImage):
|
|
1736
|
+
"""
|
|
1737
|
+
Load a `PIL image`_ and return it as a numpy int array.
|
|
1738
|
+
|
|
1739
|
+
.. _PIL image: https://pillow.readthedocs.io/en/latest/reference/Image.html
|
|
1740
|
+
|
|
1741
|
+
Returns
|
|
1742
|
+
-------
|
|
1743
|
+
numpy.array
|
|
1744
|
+
|
|
1745
|
+
The array shape depends on the image type:
|
|
1746
|
+
|
|
1747
|
+
- (M, N) for grayscale images.
|
|
1748
|
+
- (M, N, 3) for RGB images.
|
|
1749
|
+
- (M, N, 4) for RGBA images.
|
|
1750
|
+
"""
|
|
1751
|
+
if pilImage.mode in ['RGBA', 'RGBX', 'RGB', 'L']:
|
|
1752
|
+
# return MxNx4 RGBA, MxNx3 RBA, or MxN luminance array
|
|
1753
|
+
return np.asarray(pilImage)
|
|
1754
|
+
elif pilImage.mode.startswith('I;16'):
|
|
1755
|
+
# return MxN luminance array of uint16
|
|
1756
|
+
raw = pilImage.tobytes('raw', pilImage.mode)
|
|
1757
|
+
if pilImage.mode.endswith('B'):
|
|
1758
|
+
x = np.frombuffer(raw, '>u2')
|
|
1759
|
+
else:
|
|
1760
|
+
x = np.frombuffer(raw, '<u2')
|
|
1761
|
+
return x.reshape(pilImage.size[::-1]).astype('=u2')
|
|
1762
|
+
else: # try to convert to an rgba image
|
|
1763
|
+
try:
|
|
1764
|
+
pilImage = pilImage.convert('RGBA')
|
|
1765
|
+
except ValueError as err:
|
|
1766
|
+
raise RuntimeError('Unknown image mode') from err
|
|
1767
|
+
return np.asarray(pilImage) # return MxNx4 RGBA array
|
|
1768
|
+
|
|
1769
|
+
|
|
1770
|
+
def _pil_png_to_float_array(pil_png):
|
|
1771
|
+
"""Convert a PIL `PNGImageFile` to a 0-1 float array."""
|
|
1772
|
+
# Unlike pil_to_array this converts to 0-1 float32s for backcompat with the
|
|
1773
|
+
# old libpng-based loader.
|
|
1774
|
+
# The supported rawmodes are from PIL.PngImagePlugin._MODES. When
|
|
1775
|
+
# mode == "RGB(A)", the 16-bit raw data has already been coarsened to 8-bit
|
|
1776
|
+
# by Pillow.
|
|
1777
|
+
mode = pil_png.mode
|
|
1778
|
+
rawmode = pil_png.png.im_rawmode
|
|
1779
|
+
if rawmode == "1": # Grayscale.
|
|
1780
|
+
return np.asarray(pil_png, np.float32)
|
|
1781
|
+
if rawmode == "L;2": # Grayscale.
|
|
1782
|
+
return np.divide(pil_png, 2**2 - 1, dtype=np.float32)
|
|
1783
|
+
if rawmode == "L;4": # Grayscale.
|
|
1784
|
+
return np.divide(pil_png, 2**4 - 1, dtype=np.float32)
|
|
1785
|
+
if rawmode == "L": # Grayscale.
|
|
1786
|
+
return np.divide(pil_png, 2**8 - 1, dtype=np.float32)
|
|
1787
|
+
if rawmode == "I;16B": # Grayscale.
|
|
1788
|
+
return np.divide(pil_png, 2**16 - 1, dtype=np.float32)
|
|
1789
|
+
if mode == "RGB": # RGB.
|
|
1790
|
+
return np.divide(pil_png, 2**8 - 1, dtype=np.float32)
|
|
1791
|
+
if mode == "P": # Palette.
|
|
1792
|
+
return np.divide(pil_png.convert("RGBA"), 2**8 - 1, dtype=np.float32)
|
|
1793
|
+
if mode == "LA": # Grayscale + alpha.
|
|
1794
|
+
return np.divide(pil_png.convert("RGBA"), 2**8 - 1, dtype=np.float32)
|
|
1795
|
+
if mode == "RGBA": # RGBA.
|
|
1796
|
+
return np.divide(pil_png, 2**8 - 1, dtype=np.float32)
|
|
1797
|
+
raise ValueError(f"Unknown PIL rawmode: {rawmode}")
|
|
1798
|
+
|
|
1799
|
+
|
|
1800
|
+
@_api.deprecated('3.11', alternative="Pillow's `PIL.Image.Image.thumbnail`")
|
|
1801
|
+
def thumbnail(infile, thumbfile, scale=0.1, interpolation='bilinear',
|
|
1802
|
+
preview=False):
|
|
1803
|
+
"""
|
|
1804
|
+
Make a thumbnail of image in *infile* with output filename *thumbfile*.
|
|
1805
|
+
|
|
1806
|
+
See `Pillow for a replacement
|
|
1807
|
+
<https://pillow.readthedocs.io/en/stable/handbook/tutorial.html#create-jpeg-thumbnails>`_.
|
|
1808
|
+
|
|
1809
|
+
Parameters
|
|
1810
|
+
----------
|
|
1811
|
+
infile : str or file-like
|
|
1812
|
+
The image file. Matplotlib relies on Pillow_ for image reading, and
|
|
1813
|
+
thus supports a wide range of file formats, including PNG, JPG, TIFF
|
|
1814
|
+
and others.
|
|
1815
|
+
|
|
1816
|
+
.. _Pillow: https://python-pillow.github.io
|
|
1817
|
+
|
|
1818
|
+
thumbfile : str or file-like
|
|
1819
|
+
The thumbnail filename.
|
|
1820
|
+
|
|
1821
|
+
scale : float, default: 0.1
|
|
1822
|
+
The scale factor for the thumbnail.
|
|
1823
|
+
|
|
1824
|
+
interpolation : str, default: 'bilinear'
|
|
1825
|
+
The interpolation scheme used in the resampling. See the
|
|
1826
|
+
*interpolation* parameter of `~.Axes.imshow` for possible values.
|
|
1827
|
+
|
|
1828
|
+
preview : bool, default: False
|
|
1829
|
+
If True, the default backend (presumably a user interface
|
|
1830
|
+
backend) will be used which will cause a figure to be raised if
|
|
1831
|
+
`~matplotlib.pyplot.show` is called. If it is False, the figure is
|
|
1832
|
+
created using `.FigureCanvasBase` and the drawing backend is selected
|
|
1833
|
+
as `.Figure.savefig` would normally do.
|
|
1834
|
+
|
|
1835
|
+
Returns
|
|
1836
|
+
-------
|
|
1837
|
+
`.Figure`
|
|
1838
|
+
The figure instance containing the thumbnail.
|
|
1839
|
+
"""
|
|
1840
|
+
|
|
1841
|
+
im = imread(infile)
|
|
1842
|
+
rows, cols, depth = im.shape
|
|
1843
|
+
|
|
1844
|
+
# This doesn't really matter (it cancels in the end) but the API needs it.
|
|
1845
|
+
dpi = 100
|
|
1846
|
+
|
|
1847
|
+
height = rows / dpi * scale
|
|
1848
|
+
width = cols / dpi * scale
|
|
1849
|
+
|
|
1850
|
+
if preview:
|
|
1851
|
+
# Let the UI backend do everything.
|
|
1852
|
+
import matplotlib_rs.pyplot as plt
|
|
1853
|
+
fig = plt.figure(figsize=(width, height), dpi=dpi)
|
|
1854
|
+
else:
|
|
1855
|
+
from matplotlib_rs.figure import Figure
|
|
1856
|
+
fig = Figure(figsize=(width, height), dpi=dpi)
|
|
1857
|
+
FigureCanvasBase(fig)
|
|
1858
|
+
|
|
1859
|
+
ax = fig.add_axes((0, 0, 1, 1), aspect='auto',
|
|
1860
|
+
frameon=False, xticks=[], yticks=[])
|
|
1861
|
+
ax.imshow(im, aspect='auto', resample=True, interpolation=interpolation)
|
|
1862
|
+
fig.savefig(thumbfile, dpi=dpi)
|
|
1863
|
+
return fig
|