黑白图着彩色

# -*- coding: UTF-8 -*-

## https://github.com/richzhang/colorization
## model http://eecs.berkeley.edu/~rich.zhang/projects/2016_colorization/files/demo_v1/colorization_release_v1.caffemodel

import numpy as np
import cv2

prototxt = "colorization_deploy_v2.prototxt"
model = "colorization_release_v1.caffemodel"
points = "pts_in_hull.npy"
imagePath = "image.jpg"

print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(prototxt, model)
pts = np.load(points)

class8 = net.getLayerId("class8_ab")
conv8 = net.getLayerId("conv8_313_rh")
pts = pts.transpose().reshape(2, 313, 1, 1)
net.getLayer(class8).blobs = [pts.astype("float32")]
net.getLayer(conv8).blobs = [np.full([1, 313], 2.606, dtype="float32")]


image = cv2.imread(imagePath)
scaled = image.astype("float32") / 255.0
lab = cv2.cvtColor(scaled, cv2.COLOR_BGR2LAB)

# 将所有训练图像从RGB颜色空间转换为Lab颜色空间
resized = cv2.resize(lab, (224, 224))
L = cv2.split(resized)[0]
L -= 50

# 使用L通道作为网络的输入并训练网络预测ab通道
print("[INFO] colorizing image...")
net.setInput(cv2.dnn.blobFromImage(L))
ab = net.forward()[0, :, :, :].transpose((1, 2, 0))
 
# 将输入L通道与预测的ab通道组合
ab = cv2.resize(ab, (image.shape[1], image.shape[0]))

L = cv2.split(lab)[0]
colorized = np.concatenate((L[:, :, np.newaxis], ab), axis=2)
 
# 将Lab图像转换回RGB
colorized = cv2.cvtColor(colorized, cv2.COLOR_LAB2BGR)
colorized = np.clip(colorized, 0, 1)

colorized = (255 * colorized).astype("uint8")
 
# 展示
cv2.imshow("Original", image)
cv2.imshow("Colorized", colorized)
cv2.waitKey(0)



黑白图着彩色_第1张图片

 

 

你可能感兴趣的:(Python,Image,Caffe)