Convert PIL image to numpy array of target format. Args: image (PIL.Image): a PIL image format (str): the format of output image Returns: (np.ndarray): also see `read_image`
(image, format)
| 57 | |
| 58 | |
| 59 | def convert_PIL_to_numpy(image, format): |
| 60 | """ |
| 61 | Convert PIL image to numpy array of target format. |
| 62 | |
| 63 | Args: |
| 64 | image (PIL.Image): a PIL image |
| 65 | format (str): the format of output image |
| 66 | |
| 67 | Returns: |
| 68 | (np.ndarray): also see `read_image` |
| 69 | """ |
| 70 | if format is not None: |
| 71 | # PIL only supports RGB, so convert to RGB and flip channels over below |
| 72 | conversion_format = format |
| 73 | if format in ["BGR", "YUV-BT.601"]: |
| 74 | conversion_format = "RGB" |
| 75 | image = image.convert(conversion_format) |
| 76 | image = np.asarray(image) |
| 77 | # PIL squeezes out the channel dimension for "L", so make it HWC |
| 78 | if format == "L": |
| 79 | image = np.expand_dims(image, -1) |
| 80 | |
| 81 | # handle formats not supported by PIL |
| 82 | elif format == "BGR": |
| 83 | # flip channels if needed |
| 84 | image = image[:, :, ::-1] |
| 85 | elif format == "YUV-BT.601": |
| 86 | image = image / 255.0 |
| 87 | image = np.dot(image, np.array(_M_RGB2YUV).T) |
| 88 | |
| 89 | return image |
| 90 | |
| 91 | |
| 92 | def convert_image_to_rgb(image, format): |