CoolFace
Apppublic

osanseviero/Neural_Image_Colorizer

sourceHugging Faceupdated 3y agoView on Hugging Face
8likes
predict.py80 linesDownload Raw Back to root
1import sys2sys.path.insert(0, './WordLM')3 4import PIL5import torch6import torch.nn as nn7import cv28from skimage.color import lab2rgb, rgb2lab, rgb2gray9from skimage import io10import matplotlib.pyplot as plt11import numpy as np12 13class ColorizationNet(nn.Module):14  def __init__(self, input_size=128):15    super(ColorizationNet, self).__init__()16 17    MIDLEVEL_FEATURE_SIZE = 12818    resnet=models.resnet18(pretrained=True)19    resnet.conv1.weight=nn.Parameter(resnet.conv1.weight.sum(dim=1).unsqueeze(1))20    21    self.midlevel_resnet =nn.Sequential(*list(resnet.children())[0:6])22 23    self.upsample = nn.Sequential(     24      nn.Conv2d(MIDLEVEL_FEATURE_SIZE, 128, kernel_size=3, stride=1, padding=1),25      nn.BatchNorm2d(128),26      nn.ReLU(),27      nn.Upsample(scale_factor=2),28      nn.Conv2d(128, 64, kernel_size=3, stride=1, padding=1),29      nn.BatchNorm2d(64),30      nn.ReLU(),31      nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),32      nn.BatchNorm2d(64),33      nn.ReLU(),34      nn.Upsample(scale_factor=2),35      nn.Conv2d(64, 32, kernel_size=3, stride=1, padding=1),36      nn.BatchNorm2d(32),37      nn.ReLU(),38      nn.Conv2d(32, 2, kernel_size=3, stride=1, padding=1),39      nn.Upsample(scale_factor=2)40    )41 42  def forward(self, input):43 44    # Pass input through ResNet-gray to extract features45    midlevel_features = self.midlevel_resnet(input)46 47    # Upsample to get colors48    output = self.upsample(midlevel_features)49    return output50 51    52    53def show_output(grayscale_input, ab_input):54  '''Show/save rgb image from grayscale and ab channels55     Input save_path in the form {'grayscale': '/path/', 'colorized': '/path/'}'''56  color_image = torch.cat((grayscale_input, ab_input), 0).detach().numpy() # combine channels57  color_image = color_image.transpose((1, 2, 0))  # rescale for matplotlib58  color_image[:, :, 0:1] = color_image[:, :, 0:1] * 10059  color_image[:, :, 1:3] = color_image[:, :, 1:3] * 255 - 128   60  color_image = lab2rgb(color_image.astype(np.float64))61  grayscale_input = grayscale_input.squeeze().numpy()62  # plt.imshow(grayscale_input)63  # plt.imshow(color_image)64  return color_image65 66model=torch.load("model-final.pth")67 68def colorize(img_path,print_img=True):69    img=cv2.imread(img_path)70    img=cv2.resize(img,(224,224))71    grayscale_input= torch.Tensor(rgb2gray(img))72    ab_input=model(grayscale_input.unsqueeze(0).unsqueeze(0)).squeeze(0)73    predicted=show_output(grayscale_input.unsqueeze(0), ab_input)74    if print_img:75        plt.imshow(predicted)76    return predicted77 78# out=colorize("download.png")79# print(out)80