Convert a PIL `PNGImageFile` to a 0-1 float array.
(pil_png)
| 1758 | |
| 1759 | |
| 1760 | def _pil_png_to_float_array(pil_png): |
| 1761 | """Convert a PIL `PNGImageFile` to a 0-1 float array.""" |
| 1762 | # Unlike pil_to_array this converts to 0-1 float32s for backcompat with the |
| 1763 | # old libpng-based loader. |
| 1764 | # The supported rawmodes are from PIL.PngImagePlugin._MODES. When |
| 1765 | # mode == "RGB(A)", the 16-bit raw data has already been coarsened to 8-bit |
| 1766 | # by Pillow. |
| 1767 | mode = pil_png.mode |
| 1768 | rawmode = pil_png.png.im_rawmode |
| 1769 | if rawmode == "1": # Grayscale. |
| 1770 | return np.asarray(pil_png, np.float32) |
| 1771 | if rawmode == "L;2": # Grayscale. |
| 1772 | return np.divide(pil_png, 2**2 - 1, dtype=np.float32) |
| 1773 | if rawmode == "L;4": # Grayscale. |
| 1774 | return np.divide(pil_png, 2**4 - 1, dtype=np.float32) |
| 1775 | if rawmode == "L": # Grayscale. |
| 1776 | return np.divide(pil_png, 2**8 - 1, dtype=np.float32) |
| 1777 | if rawmode == "I;16B": # Grayscale. |
| 1778 | return np.divide(pil_png, 2**16 - 1, dtype=np.float32) |
| 1779 | if mode == "RGB": # RGB. |
| 1780 | return np.divide(pil_png, 2**8 - 1, dtype=np.float32) |
| 1781 | if mode == "P": # Palette. |
| 1782 | return np.divide(pil_png.convert("RGBA"), 2**8 - 1, dtype=np.float32) |
| 1783 | if mode == "LA": # Grayscale + alpha. |
| 1784 | return np.divide(pil_png.convert("RGBA"), 2**8 - 1, dtype=np.float32) |
| 1785 | if mode == "RGBA": # RGBA. |
| 1786 | return np.divide(pil_png, 2**8 - 1, dtype=np.float32) |
| 1787 | raise ValueError(f"Unknown PIL rawmode: {rawmode}") |
| 1788 | |
| 1789 | |
| 1790 | @_api.deprecated('3.11', alternative="Pillow's `PIL.Image.Image.thumbnail`") |