Skip to content
The Chat Archive
gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)

este codigo no da un resultado de imagen con el canal alpha, está malo def resize(path,…

  1. User

    este codigo no da un resultado de imagen con el canal alpha, está malo def resize(path, new_width_height = 1280, save_image = False, convert_RGB = True, clip_full_hd = False, quality = 100): ''' Resize and return Given Image args: path: Image Path new_width_height = Reshaped image's width and height. # If integer is given, it'll keep the aspect ratio as it is by shrinking the Bigger dimension (width or height) to the max of new_width_height and then shring the smaller dimension accordingly save_image = Whether to save the image or not convert_RGB: Whether to Convert the RGBA image to RGB (by default backgroud is white) ''' image = Image.open(path) w, h = image.size

    fixed_size = new_width_height if isinstance(new_width_height, int) else False

    if fixed_size: if h > w: fixed_height = fixed_size height_percent = (fixed_height / float(h)) width_size = int((float(w) * float(height_percent))) image = image.resize((width_size, fixed_height), Image.NEAREST)

    else:
      fixed_width = fixed_size
      width_percent = (fixed_width / float(w))
      height_size = int((float(h) * float(width_percent)))
      image = image.resize((fixed_width, height_size), Image.NEAREST) # Try Image.ANTIALIAS inplace of Image.NEAREST
    

    else: image = image.resize(new_width_height)

    if image.mode == "RGBA" and convert_RGB: image.load() # required for png.split() new = Image.new("RGB", image.size, (255, 255, 255)) # White Background image = new.paste(image, mask=image.split()[3]) # 3 is the alpha channel #new.paste(image, (0, 0), image) new.paste(image, mask=alpha_channel) # Paste the image along with its alpha channel

      # new = Image.new("RGBA", image.size, "WHITE") # Create a white rgba background
      #new.paste(image, (0, 0), image) # Paste the image on the background.
    

    mage = new.convert('RGBA')

    if save_image: image.save(path, quality = quality)

    return image

    class DummyFlags(): def init(self, ckpt_path:str, task:str, input_dir: str = "./maxim/images/Enhancement", output_dir:str = "./maxim/images/Results", has_target:bool = False, save_images:bool = True, geometric_ensemble:bool = False): ''' Builds the dummy flags which replicates the behaviour of Terminal CLI execution (same as ArgParse) args: ckpt_path: Saved Model CheckPoint: Find all the checkpoints for pre trained models at https://console.cloud.google.com/storage/browser/gresearch/maxim/ckpt/ task: Task for which the model waas trained. Each task uses different Data and Checkpoints. Find the details of tasks and respective checkpoints details at: https://github.com/google-research/maxim#results-and-pre-trained-models input_dir: Input Directory. We do not need it here as we are directly passing one image at a time output_dir: Also not needed in out code has_target: Used to calculate PSNR and SSIM calculation. Not needed in our case save_images: Used in CLI command where images were saved in loop. Not needed in our case geometric_ensemble: Was used in training part and as it is just an Inference part, it is not needed

    '''
    self.ckpt_path = ckpt_path
    self.task = task
    self.input_dir = input_dir
    self.output_dir = output_dir
    self.has_target = has_target
    self.save_images = save_images
    self.geometric_ensemble = geometric_ensemble
    
  2. Assistant

    There are several issues in the code provided, here are some of them:

    1. In the line image = new.paste(image, mask=image.split()[3]), the paste() function returns None and modifies the new image. Therefore, image will be set to None in this case.

    2. In the line mage = new.convert('RGBA'), mage should be image. This is a typo.

    3. The alpha_channel variable is not defined. It seems like it should be set to image.split()[3] based on the commented-out code.

    Here's a corrected version of the resize() function:

    def resize(path, new_width_height=1280, save_image=False, convert_RGB=True, clip_full_hd=False, quality=100):
        '''
        Resize and return Given Image
        args:
          path: Image Path
          new_width_height = Reshaped image's width and height. # If integer is given, it'll keep the aspect ratio as it is by shrinking the Bigger dimension (width or height) to the max of new_width_height  and then shring the smaller dimension accordingly 
          save_image = Whether to save the image or not
          convert_RGB: Whether to Convert the RGBA image to RGB (by default backgroud is white)
        '''
        image = Image.open(path)
        w, h = image.size
    
        fixed_size = new_width_height if isinstance(new_width_height, int) else False
    
        if fixed_size:
            if h > w:
                fixed_height = fixed_size
                height_percent = (fixed_height / float(h))
                width_size = int((float(w) * float(height_percent)))
                image = image.resize((width_size, fixed_height), Image.NEAREST)
    
            else:
                fixed_width = fixed_size
                width_percent = (fixed_width / float(w))
                height_size = int((float(h) * float(width_percent)))
                image = image.resize((fixed_width, height_size), Image.NEAREST)  # Try Image.ANTIALIAS inplace of Image.NEAREST
    
        else:
            image = image.resize(new_width_height)
    
        if image.mode == "RGBA" and convert_RGB:
            image.load()  # required for png.split()
            alpha_channel = image.split()[3]
            new = Image.new("RGB", image.size, (255, 255, 255))  # White Background
            new.paste(image, mask=alpha_channel)  # Paste the image along with its alpha channel
            image = new.convert('RGBA')
    
        if save_image:
            image.save(path, quality=quality)
    
        return image
    

    Note: There may be other issues in the rest of the code that were not addressed in this answer.

  3. User

    if image.mode == "RGBA" and convert_RGB: image.load() # required for png.split() new = Image.new("RGB", image.size, (255, 255, 255)) # White Background mage = new.paste(image, mask=image.split()[3]) # 3 is the alpha channel

    #new = Image.new("RGBA", image.size, "WHITE") # Create a white rgba background
    new.paste(image, (0, 0), image) # Paste the image on the background.
    image = new.convert('RGBA')
    

    if save_image: image.save(path, quality = quality)

    return image

  4. Assistant

    There are two issues with this code:

    1. The paste() method returns None, not the new image with the pasted pixel values. Therefore, mage will be None and the resulting image will be incorrect.

    2. The old code had correctly recovered the alpha channel and used it as the mask argument to paste() function. But in this code snippet, the alpha channel is not used.

    Here is corrected code:

    if image.mode == "RGBA" and convert_RGB:
        image.load() # required for png.split()
        alpha = image.split()[3] # get alpha channel
        new = Image.new("RGB", image.size, (255, 255, 255)) # White Background
        new.paste(image, mask=alpha) # Paste the image along with its alpha channel
        image = new.convert('RGBA')
    
    if save_image:
        image.save(path, quality=quality)
    
    return image
    

    This code copies the RGB channels of the original image to a new white background, using the alpha channel (if present) as a mask. The resulting image is saved as PNG with the given quality (if save_image is True) and returned.

  5. User

    cambia el siguiente codigo para que el archivo procesado copie el canal alpha del archivo original y lo aplique a la imagen que se guardará. images = ["/content/gdrive/MyDrive/castle/"+i for i in os.listdir("/content/gdrive/MyDrive/castle/") if i.endswith(('jpeg', 'png', 'jpg',"PNG","JPEG","JPG"))]

    # _ = [resize(path, 1920, save_image=True) for path in images] # Resize Images to 1920 as the max dimension's size else it'll blow the GPU / CPU memory

    for path in images: with open(path, "rb") as f: input_img, height, width, height_even, width_even = pre_process(f) preds = predict(input_img) result = post_process(preds, height, width, height_even, width_even) im = Image.fromarray(result) im.save("/content/gdrive/MyDrive/castle/processed/"+path.split('/')[-1])

  6. Assistant

    Here is the modified code to copy the alpha channel from the original image and apply it to the processed image:

    for path in images:
        with open(path, "rb") as f:
            input_img, height, width, height_even, width_even = pre_process(f)
            preds = predict(input_img)
            result = post_process(preds, height, width, height_even, width_even)
        im = Image.fromarray(result)
    
        # Copy alpha channel from original image (if present)
        orig_im = Image.open(path)
        if orig_im.mode == "RGBA":
            alpha = orig_im.split()[3]
            im.putalpha(alpha)
    
        # Save processed image with alpha channel copied from original
        im.save("/content/gdrive/MyDrive/castle/processed/"+path.split('/')[-1])
    

    This code opens the original image and checks if it has an alpha channel. If so, it extracts the alpha channel and applies it to the processed image using the putalpha method. Then, it saves the processed image with the copied alpha channel to the "processed" directory.