|
18 | 18 | import matplotlib.colors as mcolors |
19 | 19 | import matplotlib.cm as cm |
20 | 20 | import matplotlib.cbook as cbook |
| 21 | +import matplotlib.units as munits |
21 | 22 | # For clarity, names from _image are given explicitly in this module: |
22 | 23 | import matplotlib._image as _image |
23 | 24 | # For user convenience, the names from _image are also imported into |
@@ -696,6 +697,7 @@ def set_data(self, A): |
696 | 697 | """ |
697 | 698 | if isinstance(A, PIL.Image.Image): |
698 | 699 | A = pil_to_array(A) # Needed e.g. to apply png palette. |
| 700 | + A = self._convert_units(A) |
699 | 701 | self._A = cbook.safe_masked_invalid(A, copy=True) |
700 | 702 |
|
701 | 703 | if (self._A.dtype != np.uint8 and |
@@ -733,6 +735,30 @@ def set_data(self, A): |
733 | 735 | self._rgbacache = None |
734 | 736 | self.stale = True |
735 | 737 |
|
| 738 | + def _convert_units(self, A): |
| 739 | + # Take the first element since units expects a 1D sequence, not 2D |
| 740 | + converter = munits.registry.get_converter(A[0]) |
| 741 | + if converter is None: |
| 742 | + return A |
| 743 | + |
| 744 | + try: |
| 745 | + units = converter.default_units(A, self) |
| 746 | + except Exception as e: |
| 747 | + raise RuntimeError( |
| 748 | + f'{converter} failed when trying to return the default units ' |
| 749 | + f'for this image. This may be because {converter} has not ' |
| 750 | + 'implemented support for images in the default_units() method.' |
| 751 | + ) from e |
| 752 | + |
| 753 | + try: |
| 754 | + return converter.convert(A, units, self) |
| 755 | + except Exception as e: |
| 756 | + raise RuntimeError( |
| 757 | + f'{converter} failed when trying to convert the units ' |
| 758 | + f'for this image. This may be because {converter} has not ' |
| 759 | + 'implemented support for images in the convert() method.' |
| 760 | + ) from e |
| 761 | + |
736 | 762 | def set_array(self, A): |
737 | 763 | """ |
738 | 764 | Retained for backwards compatibility - use set_data instead. |
|
0 commit comments