osanseviero/Neural_Image_Colorizer
8
1import PIL2import torch3import torch.nn as nn4import cv25from skimage.color import lab2rgb, rgb2lab, rgb2gray6from skimage import io7import matplotlib.pyplot as plt8import numpy as np9 10class ColorizationNet(nn.Module):11 def __init__(self, input_size=128):12 super(ColorizationNet, self).__init__()13 14 MIDLEVEL_FEATURE_SIZE = 12815 resnet=models.resnet18(pretrained=True)16 resnet.conv1.weight=nn.Parameter(resnet.conv1.weight.sum(dim=1).unsqueeze(1))17 18 self.midlevel_resnet =nn.Sequential(*list(resnet.children())[0:6])19 20 self.upsample = nn.Sequential( 21 nn.Conv2d(MIDLEVEL_FEATURE_SIZE, 128, kernel_size=3, stride=1, padding=1),22 nn.BatchNorm2d(128),23 nn.ReLU(),24 nn.Upsample(scale_factor=2),25 nn.Conv2d(128, 64, kernel_size=3, stride=1, padding=1),26 nn.BatchNorm2d(64),27 nn.ReLU(),28 nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),29 nn.BatchNorm2d(64),30 nn.ReLU(),31 nn.Upsample(scale_factor=2),32 nn.Conv2d(64, 32, kernel_size=3, stride=1, padding=1),33 nn.BatchNorm2d(32),34 nn.ReLU(),35 nn.Conv2d(32, 2, kernel_size=3, stride=1, padding=1),36 nn.Upsample(scale_factor=2)37 )38 39 def forward(self, input):40 41 # Pass input through ResNet-gray to extract features42 midlevel_features = self.midlevel_resnet(input)43 44 # Upsample to get colors45 output = self.upsample(midlevel_features)46 return output47 48 49 50def show_output(grayscale_input, ab_input):51 '''Show/save rgb image from grayscale and ab channels52 Input save_path in the form {'grayscale': '/path/', 'colorized': '/path/'}'''53 color_image = torch.cat((grayscale_input, ab_input), 0).detach().numpy() # combine channels54 color_image = color_image.transpose((1, 2, 0)) # rescale for matplotlib55 color_image[:, :, 0:1] = color_image[:, :, 0:1] * 10056 color_image[:, :, 1:3] = color_image[:, :, 1:3] * 255 - 128 57 color_image = lab2rgb(color_image.astype(np.float64))58 grayscale_input = grayscale_input.squeeze().numpy()59 # plt.imshow(grayscale_input)60 # plt.imshow(color_image)61 return color_image62 63def colorize(img,print_img=True):64 # img=cv2.imread(img)65 img=cv2.resize(img,(224,224))66 grayscale_input= torch.Tensor(rgb2gray(img))67 ab_input=model(grayscale_input.unsqueeze(0).unsqueeze(0)).squeeze(0)68 predicted=show_output(grayscale_input.unsqueeze(0), ab_input)69 if print_img:70 plt.imshow(predicted)71 return predicted72 73# device=torch.device("cuda" if torch.cuda.is_available() else "cpu")74# torch.load with map_location=torch.device('cpu') 75model=torch.load("model-final.pth",map_location ='cpu')76 77 78import streamlit as st79st.title("Image Colorizer")80st.write('\n')81st.write('Find more info at: https://github.com/Pranav082001/Neural-Image-Colorizer or at https://medium.com/@pranav.kushare2001/colorize-your-black-and-white-photos-using-ai-4652a34e967.')82 83# Sidebar84st.sidebar.title("Upload Image")85file=st.sidebar.file_uploader("Please upload a Black and White image",type=["jpg","jpeg","png"])86 87if st.sidebar.button("Colorize image"):88 with st.spinner('Colorizing...'):89 file_bytes = np.asarray(bytearray(file.read()), dtype=np.uint8)90 opencv_image = cv2.imdecode(file_bytes, 1)91 im=colorize(opencv_image)92 st.text("Original")93 st.image(file)94 st.text("Colorized!!")95 st.image(im)96 