def resize(path, newwidthheight = 1280, saveimage = False, convertRGB = True, clipfullhd…
- User
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.NEARESTelse: 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 = 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('RGB')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
- Assistant
import tensorflow as tf from PIL import Image
def apply_model(image, flags): model = tf.saved_model.load(flags.ckpt_path) task = flags.task
# Preprocessing image image = image.convert('RGB') image = tf.cast(tf.image.resize(image, (256, 256)), dtype=tf.float32) / 255. image = tf.expand_dims(image, axis=0) # Model Prediction if task == 'denoise': predictions = model.denoise(image, training=False) elif task == 'superres': predictions = model.superres(image, training=False) elif task == 'colorization': predictions = model.colorize(image, training=False) else: print("Invalid task") return None # Post Processing Predictions if task == "colorization": predictions = predictions.numpy()[0] * 255. _, height, width, _ = predictions.shape image = Image.fromarray(predictions.astype('uint8')).resize((width * 2, height * 2)) else: predictions = tf.clip_by_value(predictions, clip_value_min=0., clip_value_max=1.) * 255. image = tf.squeeze(predictions).numpy().astype('uint8') image = Image.fromarray(image) return imagedef predict(path, flags): image = resize(path) output_image = apply_model(image, flags)
- User
File "", line 36 new = Image.new("RGBA", image.size, "WHITE") # Create a white rgba background ^ IndentationError: unindent does not match any outer indentation level
- Assistant
This error occurs because the indentation level of this line is not matching with the indentation level of the previous line. It seems like this line was mistakenly indented by four spaces more than it should be.
To fix this error, we just need to remove the extra four-space indentation from this line:
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 = 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('RGB')Alternatively, we can add four-space indentation to the previous line:
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 = 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('RGB') - User
explicame en español
- Assistant
Este error ocurre porque el nivel de indentación de esta línea no coincide con el nivel de indentación de la línea anterior. Parece que esta línea accidentalmente está indentada con cuatro espacios más de lo que debería.
Para solucionar este error, simplemente debemos eliminar la indentación extra de cuatro espacios de esta línea o agregar cuatro espacios de indentación a la línea anterior. Es una buena práctica mantener constante el nivel de indentación en todas las líneas del código para evitar este tipo de errores.
- User
escribe la correccion con identacion de codigo
- Assistant
Por supuesto, aquí está la corrección del código con indentación adecuada:
if image.mode == "RGBA" and convert_RGB: image.load() # se requiere para png.split() new = Image.new("RGB", image.size, (255, 255, 255)) # Fondo blanco image = new.paste(image, mask=image.split()[3]) # 3 es el canal alfa new = Image.new("RGBA", image.size, "WHITE") # Crea un fondo RGBA blanco new.paste(image, (0, 0), image) # Pega la imagen en el fondo image = new.convert('RGB')En este código, se agregó una indentación adicional de cuatro espacios a las líneas 3 y 4 para que coincidan con la indentación de la línea 2. También se mantuvo la indentación correcta en las líneas restantes para que todas las líneas encajen adecuadamente.
- User
- Assistant