From 0960b46dc3f2093e6ec056e229626622ea8764cc Mon Sep 17 00:00:00 2001 From: RavSinghChandan Date: Thu, 29 Oct 2026 19:42:10 +0530 Subject: [PATCH] [transforms] Crop an image without any box in crop_detection --- doctr/transforms/functional/base.py | 2 ++ doctr/transforms/functional/pytorch.py | 2 +- tests/pytorch/test_transforms_pt.py | 6 ++++++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/doctr/transforms/functional/base.py b/doctr/transforms/functional/base.py index f578f0445d..b313fc3a1a 100644 --- a/doctr/transforms/functional/base.py +++ b/doctr/transforms/functional/base.py @@ -26,6 +26,8 @@ def crop_boxes( the cropped boxes """ boxes = boxes.copy() + if boxes.shape[0] == 0: # nothing to crop (e.g. an image without any text) + return boxes is_box_rel = boxes.max() <= 1 is_crop_rel = max(crop_box) <= 1 diff --git a/doctr/transforms/functional/pytorch.py b/doctr/transforms/functional/pytorch.py index 028e98939e..8ce088f754 100644 --- a/doctr/transforms/functional/pytorch.py +++ b/doctr/transforms/functional/pytorch.py @@ -117,7 +117,7 @@ def crop_detection( xmax, ymax = int(round(crop_box[2] * w)), int(round(crop_box[3] * h)) cropped_img = F.crop(img, ymin, xmin, ymax - ymin, xmax - xmin) # Crop the box - boxes = crop_boxes(boxes, crop_box if boxes.max() <= 1 else (xmin, ymin, xmax, ymax)) + boxes = crop_boxes(boxes, crop_box if boxes.size == 0 or boxes.max() <= 1 else (xmin, ymin, xmax, ymax)) return cropped_img, boxes diff --git a/tests/pytorch/test_transforms_pt.py b/tests/pytorch/test_transforms_pt.py index 27bf488338..dee9ee7853 100644 --- a/tests/pytorch/test_transforms_pt.py +++ b/tests/pytorch/test_transforms_pt.py @@ -408,6 +408,12 @@ def test_crop_detection(): with pytest.raises(AssertionError): crop_detection(img, abs_boxes, (2, 6, 24, 56)) + # An image without any box (e.g. no text) is still cropped, and keeps no box + img = torch.ones((3, 50, 50), dtype=torch.float32) + c_img, c_boxes = crop_detection(img, np.zeros((0, 4), dtype=np.float32), (0.24, 0.46, 1.0, 1.0)) + assert c_img.shape == (3, 27, 38) + assert c_boxes.shape == (0, 4) + @pytest.mark.parametrize( "target",