How can I develop a transformation that performs JPEG compression with a random QF?

I need a transform that performs JPEG compression to the image in question. The QF must be random and belong to a given subset.

The imgaug library has a jpegcompression that takes a parameter on how much one wants to compress it. I’m guessing QF is quality factor?

And how do I add it to my simple_transform?

# Transforms
    simple_transform = transforms.Compose(
        [
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        ]
    )

    # Dataset
    train_dataset = datasets.ImageFolder('data/train/', simple_transform)
    valid_dataset = datasets.ImageFolder('data/valid/', simple_transform)

I’ve never done it but you could probably create a custom transform. Perhaps searching on google for pytorch lambda transform or whatever will help you find some working code of it

Edit: Did just that

def foo(x):
    return x / 255.0
transforms.Lambda(lambda x: foo(x))

Perfect @Oli

def randomJPEGcompression(image):
    qf = random.randrange(10, 100)
    outputIoStream = BytesIO()
    image.save(outputIoStream, "JPEG", quality=qf, optimice=True)
    outputIoStream.seek(0)
    return Image.open(outputIoStream)

# Transforms
    simple_transform = transforms.Compose(
        [
            transforms.Lambda(randomJPEGcompression),
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        ]
    )
4 Likes

Hi Ernesto,

You can develop a script to randomly select a Quantization Factor from a predefined subset and apply it during JPEG compression. Experiment with different QF values to find the right balance between image quality and file size on the other hand for jpeg compression you can use an online application such as https://jpegcompressor.com/ it compresses images efficiently.