datumaro icon indicating copy to clipboard operation
datumaro copied to clipboard

Add RescaleTransform: allow to resize images while maintaining aspect ratio.

Open Abdul-Mukit opened this issue 1 year ago • 5 comments

Is your feature request related to a problem? Please describe. I want to resize my dataset to have a maximum dimension of 640, in either x or y axis, while maintaining the aspect ratio.
Current ResizeTransform expects both width and height as input arguments. If the images in the input dataset are of different aspect ratio then the output dataset will loose that information forever if I use ResizeTransform. However, I am looking to use something like the following:
datum transform -t resize -o output_dataset input_dataset -- -size 640 -keep_ratio True

Describe the solution you'd like to propose. Can we have a class like ResizeTransform, that allows for only changing the max dimension to size while keeping the aspect ratio intact. Maybe a class called RescaleTransform.

datum transform -t rescale -o output_dataset input_dataset -- -max_size 640

Describe alternatives you've considered The requested behavior is that the image will be resized to have the longest dimension of size 640 while maintaining the original aspect ratio.

e.g.

Input image shape: [1920, 2560]
Output image shape: [480, 640]

Input image shape: [2560, 1920]
Output image shape: [640, 480]

Additional context My dataset has images of different aspect ratios and resolutions. Most of them are high resolution, like 3200x1920. Some are low resolution, like 294x480. All annotated using CVAT. I don't want to resize them and potentially change their aspect ratio forever in the dataset. Instead, if I can resize maintaining aspect ratio, then I can make the dataset smaller while not losing aspect ratio information.

Abdul-Mukit avatar Oct 23 '25 18:10 Abdul-Mukit

I made an initial solution and it seems to be working well. I just extended ResizeTransform. Mostly unchanged. Resized an instance segmentation dataset with polygons and bbox.
Would love to know the opinions of the maintainers. Happy to send a PR.

class RescaleTransform(ItemTransform):
    """
    Rescales images and annotations in the dataset to the specified max size along the longest dimension
    while maintaining aspect ratio.
    Supports upscaling, downscaling and mixed variants.|n
    |n
    Examples:|n
        - Rescale all images to have size of 640 along the longest dimension|n

        .. code-block::

        |s|s%(prog)s -max_size 
    """

    @classmethod
    def build_cmdline_parser(cls, **kwargs):
        parser = super().build_cmdline_parser(**kwargs)
        parser.add_argument("-max_size", "--max_size", type=int, help="Destination image max size along any axis.")
        return parser

    def __init__(self, extractor: IDataset, max_size: int) -> None:
        super().__init__(extractor)

        assert max_size > 0
        self.max_size = max_size

    @staticmethod
    def _lazy_resize_image(image, new_size):
        def _resize_image():
            h, w = image.size
            yscale = new_size[0] / float(h)
            xscale = new_size[1] / float(w)

            # LANCZOS4 is preferable for upscaling, but it works quite slow
            method = cv2.INTER_AREA if (xscale * yscale) < 1 else cv2.INTER_CUBIC

            resized_image = cv2.resize(image.data / 255.0, new_size[::-1], interpolation=method)
            resized_image *= 255.0
            return resized_image

        return Image.from_numpy(_resize_image, ext=image.ext, size=new_size)

    @staticmethod
    def _lazy_resize_mask(mask, new_size):
        def _resize_image():
            # Can use only NEAREST for masks,
            # because we can't have interpolated values
            rescaled_mask = cv2.resize(
                mask.image.astype(np.float32), new_size[::-1], interpolation=cv2.INTER_NEAREST
            )
            return rescaled_mask.astype(np.uint8)

        return _resize_image

    @staticmethod
    def _lazy_resize_rlemask(mask, new_size):
        def _resize_image():
            # Can use only NEAREST for masks,
            # because we can't have interpolated values
            rescaled_mask = cv2.resize(mask.image, new_size[::-1], interpolation=cv2.INTER_NEAREST)
            return mask_utils.encode(np.asfortranarray(rescaled_mask.astype(np.uint8)))

        return _resize_image

    def transform_item(self, item):
        if not isinstance(item.media, Image):
            raise DatumaroError(
                "Item %s: image info is required for this " "transform" % (item.id,)
            )

        h, w = item.media.size

        if h > w:
            oh = self.max_size
            ow = int(self.max_size * w / h)
        else:
            ow = self.max_size
            oh = int(self.max_size * h / w)

        xscale = ow / float(w)
        yscale = oh / float(h)

        new_size = (oh, ow)

        resized_image = None
        if item.media.has_data:
            resized_image = self._lazy_resize_image(item.media, new_size)

        resized_annotations = []
        for ann in item.annotations:
            if isinstance(ann, Bbox):
                resized_annotations.append(
                    ann.wrap(
                        x=ann.x * xscale,
                        y=ann.y * yscale,
                        w=ann.w * xscale,
                        h=ann.h * yscale,
                    )
                )
            elif isinstance(ann, (Polygon, Points, PolyLine)):
                resized_annotations.append(
                    ann.wrap(
                        points=[
                            p
                            for t in ((x * xscale, y * yscale) for x, y in take_by(ann.points, 2))
                            for p in t
                        ]
                    )
                )
            elif isinstance(ann, RleMask):
                rescaled_mask = self._lazy_resize_rlemask(ann, new_size)
                resized_annotations.append(ann.wrap(rle=rescaled_mask))
            elif isinstance(ann, Mask):
                rescaled_mask = self._lazy_resize_mask(ann, new_size)
                resized_annotations.append(ann.wrap(image=rescaled_mask))
            elif isinstance(ann, (Caption, Label)):
                resized_annotations.append(ann)
            else:
                assert False, f"Unexpected annotation type {type(ann)}"

        return self.wrap_item(item, media=resized_image, annotations=resized_annotations)

Usage:

sourceDataset  = Dataset.import_from(path=sourceDatasetPath, format="coco")
sourceDataset.transform(RescaleTransform, max_size=640)

Abdul-Mukit avatar Oct 23 '25 19:10 Abdul-Mukit

Hi Abdul, we are currently preparing for a new major release where most of the existing dataset logic will be rewritten. At this moment, we are not accepting new PRs like your suggestion, as the logic would have to be rewritten to fit the new dataset class. In a month or two we should have a new release, at which point we will also accept PRs again.

AlbertvanHouten avatar Nov 03 '25 15:11 AlbertvanHouten

Got it. Looking forward to the new changes. Thank you for this very useful platform.

Abdul-Mukit avatar Nov 03 '25 15:11 Abdul-Mukit

@AlbertvanHouten How is this looking now. Did the refactor get released?

thepian avatar May 07 '26 15:05 thepian

Hi, the refactor is currently living in the experimental directory but it is missing many of the original datumaro features. At this point I am not sure if we will reimplement every feature within the newly refactored logic.

Since we are unsure if we will fully release this new experimental logic, feel free to open any PRs again such as the implementation for this feature.

AlbertvanHouten avatar May 11 '26 12:05 AlbertvanHouten