Skip to content

Commit 45c2df3

Browse files
helpmefindanameBenedikt Fuchs
andauthored
close PIL images when loading images to tensor/numpy (#1598)
Co-authored-by: Benedikt Fuchs <[email protected]>
1 parent 3f116ad commit 45c2df3

File tree

2 files changed

+6
-7
lines changed

2 files changed

+6
-7
lines changed

doctr/datasets/utils.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,8 @@ def crop_bboxes_from_image(img_path: Union[str, Path], geoms: np.ndarray) -> Lis
186186
-------
187187
a list of cropped images
188188
"""
189-
img: np.ndarray = np.array(Image.open(img_path).convert("RGB"))
189+
with Image.open(img_path) as pil_img:
190+
img: np.ndarray = np.array(pil_img.convert("RGB"))
190191
# Polygon
191192
if geoms.ndim == 3 and geoms.shape[1:] == (4, 2):
192193
return extract_rcrops(img, geoms.astype(dtype=int))

doctr/io/image/pytorch.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,8 @@ def read_img_as_tensor(img_path: AbstractPath, dtype: torch.dtype = torch.float3
5151
if dtype not in (torch.uint8, torch.float16, torch.float32):
5252
raise ValueError("insupported value for dtype")
5353

54-
pil_img = Image.open(img_path, mode="r").convert("RGB")
55-
56-
return tensor_from_pil(pil_img, dtype)
54+
with Image.open(img_path, mode="r") as pil_img:
55+
return tensor_from_pil(pil_img.convert("RGB"), dtype)
5756

5857

5958
def decode_img_as_tensor(img_content: bytes, dtype: torch.dtype = torch.float32) -> torch.Tensor:
@@ -71,9 +70,8 @@ def decode_img_as_tensor(img_content: bytes, dtype: torch.dtype = torch.float32)
7170
if dtype not in (torch.uint8, torch.float16, torch.float32):
7271
raise ValueError("insupported value for dtype")
7372

74-
pil_img = Image.open(BytesIO(img_content), mode="r").convert("RGB")
75-
76-
return tensor_from_pil(pil_img, dtype)
73+
with Image.open(BytesIO(img_content), mode="r") as pil_img:
74+
return tensor_from_pil(pil_img.convert("RGB"), dtype)
7775

7876

7977
def tensor_from_numpy(npy_img: np.ndarray, dtype: torch.dtype = torch.float32) -> torch.Tensor:

0 commit comments

Comments
 (0)