Load a `PIL image`_ and return it as a numpy array. .. _PIL image: https://pillow.readthedocs.io/en/latest/reference/Image.html Returns ------- numpy.array The array shape depends on the image type: - (M, N) for grayscale images. - (M, N, 3) for RGB images
(pilImage)
| 1435 | |
| 1436 | |
| 1437 | def pil_to_array(pilImage): |
| 1438 | """Load a `PIL image`_ and return it as a numpy array. |
| 1439 | |
| 1440 | .. _PIL image: https://pillow.readthedocs.io/en/latest/reference/Image.html |
| 1441 | |
| 1442 | Returns |
| 1443 | ------- |
| 1444 | numpy.array |
| 1445 | |
| 1446 | The array shape depends on the image type: |
| 1447 | |
| 1448 | - (M, N) for grayscale images. |
| 1449 | - (M, N, 3) for RGB images. |
| 1450 | - (M, N, 4) for RGBA images. |
| 1451 | |
| 1452 | """ |
| 1453 | if pilImage.mode in ['RGBA', 'RGBX', 'RGB', 'L']: |
| 1454 | # return MxNx4 RGBA, MxNx3 RBA, or MxN luminance array |
| 1455 | return np.asarray(pilImage) |
| 1456 | elif pilImage.mode.startswith('I;16'): |
| 1457 | # return MxN luminance array of uint16 |
| 1458 | raw = pilImage.tobytes('raw', pilImage.mode) |
| 1459 | if pilImage.mode.endswith('B'): |
| 1460 | x = np.fromstring(raw, '>u2') |
| 1461 | else: |
| 1462 | x = np.fromstring(raw, '<u2') |
| 1463 | return x.reshape(pilImage.size[::-1]).astype('=u2') |
| 1464 | else: # try to convert to an rgba image |
| 1465 | try: |
| 1466 | pilImage = pilImage.convert('RGBA') |
| 1467 | except ValueError: |
| 1468 | raise RuntimeError('Unknown image mode') |
| 1469 | return np.asarray(pilImage) # return MxNx4 RGBA array |
| 1470 | |
| 1471 | |
| 1472 | def thumbnail(infile, thumbfile, scale=0.1, interpolation='bilinear', |