Read an image from a file into an array. .. note:: This function exists for historical reasons. It is recommended to use `PIL.Image.open` instead for loading images. Parameters ---------- fname : str or file-like The image file to read: a filename, a
(fname, format=None)
| 1513 | |
| 1514 | |
| 1515 | def imread(fname, format=None): |
| 1516 | """ |
| 1517 | Read an image from a file into an array. |
| 1518 | |
| 1519 | .. note:: |
| 1520 | |
| 1521 | This function exists for historical reasons. It is recommended to |
| 1522 | use `PIL.Image.open` instead for loading images. |
| 1523 | |
| 1524 | Parameters |
| 1525 | ---------- |
| 1526 | fname : str or file-like |
| 1527 | The image file to read: a filename, a URL or a file-like object opened |
| 1528 | in read-binary mode. |
| 1529 | |
| 1530 | Passing a URL is deprecated. Please open the URL |
| 1531 | for reading and pass the result to Pillow, e.g. with |
| 1532 | ``np.array(PIL.Image.open(urllib.request.urlopen(url)))``. |
| 1533 | format : str, optional |
| 1534 | The image file format assumed for reading the data. The image is |
| 1535 | loaded as a PNG file if *format* is set to "png", if *fname* is a path |
| 1536 | or opened file with a ".png" extension, or if it is a URL. In all |
| 1537 | other cases, *format* is ignored and the format is auto-detected by |
| 1538 | `PIL.Image.open`. |
| 1539 | |
| 1540 | Returns |
| 1541 | ------- |
| 1542 | `numpy.array` |
| 1543 | The image data. The returned array has shape |
| 1544 | |
| 1545 | - (M, N) for grayscale images. |
| 1546 | - (M, N, 3) for RGB images. |
| 1547 | - (M, N, 4) for RGBA images. |
| 1548 | |
| 1549 | PNG images are returned as float arrays (0-1). All other formats are |
| 1550 | returned as int arrays, with a bit depth determined by the file's |
| 1551 | contents. |
| 1552 | """ |
| 1553 | # hide imports to speed initial import on systems with slow linkers |
| 1554 | from urllib import parse |
| 1555 | |
| 1556 | if format is None: |
| 1557 | if isinstance(fname, str): |
| 1558 | parsed = parse.urlparse(fname) |
| 1559 | # If the string is a URL (Windows paths appear as if they have a |
| 1560 | # length-1 scheme), assume png. |
| 1561 | if len(parsed.scheme) > 1: |
| 1562 | ext = 'png' |
| 1563 | else: |
| 1564 | ext = Path(fname).suffix.lower()[1:] |
| 1565 | elif hasattr(fname, 'geturl'): # Returned by urlopen(). |
| 1566 | # We could try to parse the url's path and use the extension, but |
| 1567 | # returning png is consistent with the block above. Note that this |
| 1568 | # if clause has to come before checking for fname.name as |
| 1569 | # urlopen("file:///...") also has a name attribute (with the fixed |
| 1570 | # value "<urllib response>"). |
| 1571 | ext = 'png' |
| 1572 | elif hasattr(fname, 'name'): |
searching dependent graphs…