Skip to content

Commit 04410e5

Browse files
authored
fix: 🐛 improve image handling in read_image_as_pil for CHW format (#1287)
Signed-off-by: Onuralp SEZER <[email protected]>
1 parent 8b62abc commit 04410e5

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

sahi/utils/cv.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -204,8 +204,12 @@ def read_image_as_pil(image: Image.Image | str | np.ndarray, exif_fix: bool = Tr
204204
else:
205205
raise TypeError(f"image with shape: {image_sk.shape[3]} is not supported.")
206206
elif isinstance(image, np.ndarray):
207-
if image.shape[0] < 5: # image in CHW
208-
image = image[:, :, ::-1]
207+
# check if image is in CHW format (Channels, Height, Width)
208+
# heuristic: 3 dimensions, first dim (channels) < 5, last dim (width) > 4
209+
if image.ndim == 3 and image.shape[0] < 5: # image in CHW
210+
if image.shape[2] > 4:
211+
# convert CHW to HWC (Height, Width, Channels)
212+
image = np.transpose(image, (1, 2, 0))
209213
image_pil = Image.fromarray(image)
210214
else:
211215
raise TypeError("read image with 'pillow' using 'Image.open()'")

0 commit comments

Comments
 (0)