12def read_image(file_name, format=None):
13 """
14 Read an image into the given format.
15 Will apply rotation and flipping if the image has such exif information.
16 Args:
17 file_name (str): image file path
18 format (str): one of the supported image modes in PIL, or "BGR"
19 Returns:
20 image (np.ndarray): an HWC image
21 """
22 with PathManager.open(file_name, "rb") as f:
23 image = Image.open(f)
24
25
26 try:
27 image = ImageOps.exif_transpose(image)
28 except Exception:
29 pass
30
31 if format is not None:
32
33 conversion_format = format
34 if format == "BGR":
35 conversion_format = "RGB"
36 image = image.convert(conversion_format)
37 image = np.asarray(image)
38 if format == "BGR":
39
40 image = image[:, :, ::-1]
41
42 if format == "L":
43 image = np.expand_dims(image, -1)
44 image = Image.fromarray(image)
45 return image