pythonimage-processingpytorchcolor-space

Make Image Blue Pytorch


I'm trying to "blueify" an image that I will use for a PyTorch application (AI), which works better with "bluer" images. Specifically, I want each pixel to be blueish. I will put the code inside a class which I will put in a transforms.Compose for and pass it to the torchvision.datasets. ImageFolder tranform key word argument.

I tried to use the PyTorch torchvision.transforms.functional functions (adjust_hue, adjust_saturation, adjust_brightness). However, I was always getting images with different colors (e.g. green & purple, red & blue). I will put them inside a class which I will put in a transforms.Compose for and pass it to the torchvision.datasets.ImageFolder tranform key word argument.

Can you please help?


Solution

  • You have to blend it with a blue image.

    from PIL import Image
    import torch
    import torchvision
    
    class MakeBlue:
        def __init__(self):
            self.dark_blue = Image.new("RGB", (224, 224), "#0000ff")
    
        def __call__(self, image):
            try:
                image = torchvision.transforms.ToPILImage()(image)
    
            except TypeError:
                try:
                    image = torchvision.transforms.ToPILImage()(image.byte())
    
                except Exception:
                    pass
    
            image = image.resize((224, 224))
            image = image.convert("RGB")
            image = Image.blend(image, self.dark_blue, 0.6)
            return image
    
    # ...
    transformation = torchvision.transforms.Compose((MakeBlue(), torchvision.transforms.ToTensor()))
    # ...