Update pintar.py
Browse files1234567811 unmodified lines2021222324252622 unmodified lines495051525354555657585960616263646566676 unmodified lines7475767778798081828384858687888990919293949596979899100101102103104105import osimport numpy as npfrom skimage import color, ioimport torchimport torch.nn.functional as Ffrom PIL import Imagefrom models import ColorEncoder, ColorUNetfrom extractor.manga_panel_extractor import PanelExtractor11 unmodified linesimg_ab = img_lab[:,1:,:,:]img_l = img_l + 50pred_lab = torch.cat((img_l, img_ab), 1)[0,...].numpy()out = (np.clip(color.lab2rgb(pred_lab.transpose(1, 2, 0)), 0, 1) * 255).astype("uint8")return outdef RGB2Lab(inputs):22 unmodified linesreturn img.unsqueeze(0), img_lab.unsqueeze(0)if __name__ == "__main__":parser = argparse.ArgumentParser(description="Colorize manga images.")parser.add_argument("-i", "--input", type=str, required=True, help="Path to input image directory")parser.add_argument("-r", "--reference", type=str, required=True, help="Path to reference image")parser.add_argument("-o", "--output", type=str, required=True, help="Output directory")parser.add_argument("-ckpt", "--checkpoint", type=str, required=True, help="Path to model checkpoint")args = parser.parse_args()device = "cuda"input_image_dir = args.inputoutput_directory = args.outputckpt_path = args.checkpointreference_image_path = args.referenceimgsize = 256ckpt = torch.load(ckpt_path, map_location=lambda storage, loc: storage)6 unmodified linescolorUNet.load_state_dict(ckpt["colorUNet"])colorUNet.eval()img_name = os.path.splitext(os.path.basename(img_path))[0]img1 = Image.open(img_path).convert("RGB")width, height = img1.sizeimg1, img1_lab = preprocessing(img1)img2, img2_lab = preprocessing(Image.open(reference_image_path).convert("RGB"))img1 = img1.to(device)img1_lab = img1_lab.to(device)img2 = img2.to(device)img2_lab = img2_lab.to(device)with torch.no_grad():img2_resize = F.interpolate(img2 / 255., size=(imgsize, imgsize), mode='bilinear', recompute_scale_factor=False, align_corners=False)img1_L_resize = F.interpolate(img1_lab[:,:1,:,:] / 50., size=(imgsize, imgsize), mode='bilinear', recompute_scale_factor=False, align_corners=False)color_vector = colorEncoder(img2_resize)fake_ab = colorUNet((img1_L_resize, color_vector))fake_ab = F.interpolate(fake_ab*110, size=(height, width), mode='bilinear', recompute_scale_factor=False, align_corners=False)fake_img = torch.cat((img1_lab[:,:1,:,:], fake_ab), 1)fake_img = Lab2RGB_out(fake_img)out_folder = os.path.dirname(img_path)mkdirs(out_folder)out_img_path = os.path.join(out_folder, f'{img_name}_color.png')io.imsave(out_img_path, fake_img)print(f'Colored image has been saved to {out_img_path}.')1234567891011 unmodified lines2223242526272822 unmodified lines51525354555657585960616263646566676869706 unmodified lines7778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115import osimport numpy as npfrom skimage import color, ioimport torchimport torch.nn.functional as Ffrom PIL import Imagefrom models import ColorEncoder, ColorUNetfrom extractor.manga_panel_extractor import PanelExtractor11 unmodified linesimg_ab = img_lab[:,1:,:,:]img_l = img_l + 50pred_lab = torch.cat((img_l, img_ab), 1)[0,...].numpy()out = (np.clip(color.lab2rgb(pred_lab.transpose(1, 2, 0)), 0, 1)* 255).astype("uint8")return outdef RGB2Lab(inputs):22 unmodified linesreturn img.unsqueeze(0), img_lab.unsqueeze(0)if __name__ == "__main__":parser = argparse.ArgumentParser(description="Colorize manga images based on a single reference image.")parser.add_argument("-i", "--input_folder", type=str, required=True, help="Path to the input folder containing images to be colorized.")parser.add_argument("-r", "--reference_image", type=str, required=True, help="Path to the reference image.")parser.add_argument("-c", "--ckpt", type=str, required=True, help="Path to the model checkpoint file.")parser.add_argument("-o", "--output_folder", type=str, required=True, help="Path to the output folder to save colorized images.")args = parser.parse_args()device = "cuda"input_folder = args.input_folderreference_image_path = args.reference_imageckpt_path = args.ckptoutput_folder = args.output_folderimgsize = 256ckpt = torch.load(ckpt_path, map_location=lambda storage, loc: storage)6 unmodified linescolorUNet.load_state_dict(ckpt["colorUNet"])colorUNet.eval()# Recorre recursivamente el directorio de entrada y procesa cada imagen encontradafor root, dirs, files in os.walk(input_folder):for file in files:if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):input_image_path = os.path.join(root, file)img_name = os.path.splitext(os.path.basename(input_image_path))[0]img1 = Image.open(input_image_path).convert("RGB")width, height = img1.sizeimg1, img1_lab = preprocessing(img1)img2, img2_lab = preprocessing(Image.open(reference_image_path).convert("RGB"))img1 = img1.to(device)img1_lab = img1_lab.to(device)img2 = img2.to(device)img2_lab = img2_lab.to(device)with torch.no_grad():img2_resize = F.interpolate(img2 / 255., size=(imgsize, imgsize), mode='bilinear', recompute_scale_factor=False, align_corners=False)img1_L_resize = F.interpolate(img1_lab[:,:1,:,:] / 50., size=(imgsize, imgsize), mode='bilinear', recompute_scale_factor=False, align_corners=False)color_vector = colorEncoder(img2_resize)fake_ab = colorUNet((img1_L_resize, color_vector))fake_ab = F.interpolate(fake_ab*110, size=(height, width), mode='bilinear', recompute_scale_factor=False, align_corners=False)fake_img = torch.cat((img1_lab[:,:1,:,:], fake_ab), 1)fake_img = Lab2RGB_out(fake_img)out_subfolder = os.path.join(output_folder, os.path.relpath(root, input_folder))out_folder = os.path.join(out_subfolder, 'color')mkdirs(out_folder)out_img_path = os.path.join(out_folder, f'{img_name}_color.png')io.imsave(out_img_path, fake_img)print(f'Colored images have been saved to {output_folder}.')
pintar.py+43-33