
有時技識訓增強藝術,有時它會破壞藝術,
為黑白電影著色是一個可以追溯到 1902 年的非常古老的想法,幾十年來,許多電影創作者反對為黑白電影著色的想法,并認為這是對他們藝術的破壞,今天,它被認為是對藝術形式的一種改進,
如果演算法不使用任何用戶輸入,那不是很酷嗎?
1.定義著色問題
讓我們首先根據 CIE Lab 色彩空間來定義著色問題,與 RGB 顏色空間一樣,它是一個 3 通道顏色空間,但與 RGB 顏色空間不同的是,顏色資訊僅在 a(綠-紅分量)和 b(藍-黃分量)通道中進行編碼, L(亮度)通道僅編碼強度資訊,
我們想要著色的灰度影像可以看作是影像在Lab顏色空間中的L通道,我們的目標是找到a和b分量,這樣得到的Lab影像可以使用標準顏色空間變換轉換為RGB顏色空間,例如,在OpenCV中,這可以使用帶有COLOR_BGR2Lab選項的cvtColor來實作,
為了簡化計算,Lab 顏色空間的 ab 空間被量化為 313 個 bin,如下圖所示,而不是為每個像素找到 a 和 b 值,因為這種量化,我們只需要找到一個介于 0 和 312之間的 bin 編號,另一種思考問題的方式是我們已經有了取值從 0 到 255 的 L 通道,我們需要找到取值在 0 到 312 之間的 ab 通道,所以顏色預測任務現在是變成了多分類問題,其中每個灰色像素有 313 個類別可供選擇,

2.用于著色的 CNN 架構
Zhang 等人提出的架構是具有多個卷積塊的 VGG 式網路,每個塊都有兩個或三個卷積層,后跟一個修正線性單元 (ReLU),并終止于一個批量歸一化層(BN),與 VGG 網路不同,它沒有池化或全連接層,

輸入影像被重新縮放為 224×224,讓我們用
X
X
X表示這個重新縮放的灰度輸入影像,
當它通過上圖所示的神經網路時,它會被神經網路轉化為 Z ^ \hat Z Z^,在數學上,網路的這種轉換可以寫成 Z ^ = G ( X ) \hat Z = G(X) Z^=G(X),
Z ^ \hat Z Z^的維度是 H ? W ? Q H*W*Q H?W?Q,其中 H ( = 56 ) H(=56) H(=56)和 W ( = 56 ) W(=56) W(=56)是最后一個卷積層輸出的高度和寬度,對于每個 H ? W H*W H?W像素, Z ^ \hat Z Z^包含一個 Q ( = 313 ) Q(=313) Q(=313)值向量,其中每個值表示像素屬于該類的概率,我們的目標是為每個概率分布 Z ^ h , w \hat Z_{h,w} Z^h,w?找到一對 ab 通道值,
3.從 Z ^ \hat Z Z^恢復彩色影像
上圖所示的 CNN 為我們提供了來自調整大小的輸入影像 X X X的分布集合 Z ^ \hat Z Z^,讓我們看看如何從 Z ^ \hat Z Z^ 中的每個分布中恢復單個 ab 值對,
您可能會認為我們可以簡單地取分布的平均值并選擇與最近的量化 bin 中心相對應的 ab 對,不幸的是,這種分布不是高斯分布,分布的均值僅對應于不自然的不飽和顏色,要理解這一點,請想一想天空的顏色——它有時是藍色的,有時是橙黃色的,天空顏色的分布是雙峰的,在為天空著色時,藍色或黃色都會產生合理的顏色,但是藍色和黃色的平均值是一種無趣的灰色,
那么為什么不使用分布模式來獲得藍色或黃色的天空呢?當然,作者嘗試過,雖然它提供了鮮艷的色彩,但有時會破壞空間一致性,他們的解決方案是在均值和模式估計之間進行插值,以獲得稱為退火均值的量,使用稱為溫度 (T) 的引數來控制插值程度, T=0.38 的最終值用作兩個極端之間的權衡,

使
用
溫
度
(
T
)
的
退
火
均
值
用
于
在
分
布
的
均
值
和
眾
數
之
間
進
行
插
值
,
使用溫度 (T) 的退火均值用于在分布的均值和眾數之間進行插值,
使用溫度(T)的退火均值用于在分布的均值和眾數之間進行插值,
對應于 Z ^ \hat Z Z^分布的退火均值的 ab 對表示為 Y ^ h , w \hat Y_{h,w} Y^h,w?,可以寫成原始分布 Z ^ h , w \hat Z_{h,w} Z^h,w?的變換 Y ^ = H ( Z ^ ) \hat Y=H(\hat Z) Y^=H(Z^)
請注意,當影像通過 CNN 時,其大小減小到 56×56,因此,預測的 ab 影像 Y ^ \hat Y Y^也具有 56×56 的維度,為了獲得彩色影像,將其上采樣到原始影像大小,然后添加到亮度通道 L,以生成最終的彩色影像,
4.具有顏色重新平衡的多項式損失函式
所有神經網路都是通過定義損失函式來訓練的,訓練程序的目標是最小化訓練集的損失,在著色問題中,訓練資料由數千張彩色影像及其灰度版本組成,
CNN 的輸出是 Z ^ \hat Z Z^,輸入影像是 X X X,我們需要將訓練集中的所有彩色影像轉換為其對應的值,在數學上,我們只是想反轉映射 H H H Z = H ? 1 ( Y ) Z=H^{-1}(Y) Z=H?1(Y)
對于輸出影像 Y Y Y的每個像素 Y h , w Y_{h,w} Yh,w?,我們可以簡單地找到最近的 ab bin 并將 Z h , w Z_{h,w} Zh,w?表示為一個獨熱向量,其中我們將 1 分配給最近的 ab bin,將 0 分配給所有其他 312 個 bin,但為了獲得更好的結果,我們考慮了5個最近鄰,并使用高斯分布來計算分布 Z h , w Z_{h,w} Zh,w?,這取決于與真實值的距離,
如果您之前使用過 CNN,您可能會想使用標準交叉熵損失來比較真實值
Z
Z
Z和預測值
Z
^
\hat Z
Z^,
L
(
Z
^
,
Z
)
=
?
1
H
W
∑
h
,
w
∑
q
Z
h
,
w
,
q
l
o
g
(
Z
^
h
,
w
,
q
)
L(\hat Z, Z) = -\frac{1}{HW}\sum_{h,w}\sum_qZ_{h,w,q}log(\hat Z_{h,w,q})
L(Z^,Z)=?HW1?h,w∑?q∑?Zh,w,q?log(Z^h,w,q?)
不幸的是,上述損失函式會產生非常暗淡的顏色,這是因為 ImageNet 中的顏色分布在灰線周圍很重,
5.彩色化的結果
作者分享了兩個版本的經過訓練的 Caffe 模型 - 有和沒有顏色重新平衡,我們嘗試了兩個版本,并在下圖中分享了結果,中間一列顯示沒有重新平衡顏色的版本,最后一列顯示重新平衡的版本,
正如我們所見,色彩重新平衡使許多影像非常生動活潑,它們中的大多數都是似是而非的顏色,另一方面,有時它也會為某些影像添加一些不需要的飽和色塊,
請記住,當我們嘗試將灰度影像轉換為彩色影像時,可能有多種合理的解決方案,因此,評估良好著色的方法不是它與基本事實的匹配程度,而是它在人眼中看起來的可信度和愉悅度,
5.1 動物
該模型在動物影像上表現非常好,尤其是貓和狗,這是因為 ImageNet 包含非常大的這些動物集合,


5.2戶外場景
該模型在表現藍天和綠色植被的戶外場景方面也做得非常好,另請注意,給定一棵樹的輪廓,該模型預測橙色天空表明它已捕捉到日落的概念,




5.3草圖
最后,即使是草圖,模型也會產生合理的著色,



6.在 OpenCV 中實作著色
作者在此位置的 GitHub 中提供了預訓練模型和網路詳細資訊,下面,我們將回顧 Python 和 C++ 代碼,使用這些預訓練模型對給定的灰度影像進行著色,我們的代碼基于 OpenCV 示例代碼,我們使用了 OpenCV 4.5.1 版,我們還提供代碼來為給定的灰度視頻著色,
鏈接:https://pan.baidu.com/s/14_my8daL2SxgFVymQy-0Dg
提取碼:1v8m
(1)Python
影像著色代碼:
# colorizeImage.py
# Usage
# python colorizeImage.py --input greyscaleImage.png
import numpy as np
import cv2 as cv
import argparse
import os.path
parser = argparse.ArgumentParser(description='Colorize GreyScale Image')
parser.add_argument('--input', help='Path to image.', default="greyscaleImage.png")
args = parser.parse_args()
if args.input==None:
print('Please give the input greyscale image name.')
print('Usage example: python3 colorizeImage.py --input greyscaleImage.png')
exit()
if os.path.isfile(args.input)==0:
print('Input file does not exist')
exit()
# 讀取輸入影像
frame = cv.imread(args.input)
# 指定 2 個模型檔案的路徑
protoFile = "./models/colorization_deploy_v2.prototxt"
weightsFile = "./models/colorization_release_v2.caffemodel"
# weightsFile = "./models/colorization_release_v2_norebal.caffemodel"
# 加載聚類中心
pts_in_hull = np.load('./pts_in_hull.npy')
# 將網路讀入記憶體
net = cv.dnn.readNetFromCaffe(protoFile, weightsFile)
# 將聚類中心填充為 1x1 卷積核
pts_in_hull = pts_in_hull.transpose().reshape(2, 313, 1, 1)
net.getLayer(net.getLayerId('class8_ab')).blobs = [pts_in_hull.astype(np.float32)]
net.getLayer(net.getLayerId('conv8_313_rh')).blobs = [np.full([1, 313], 2.606, np.float32)]
#來自 opencv 示例
W_in = 224
H_in = 224
img_rgb = (frame[:,:,[2, 1, 0]] * 1.0 / 255).astype(np.float32)
img_lab = cv.cvtColor(img_rgb, cv.COLOR_RGB2Lab)
img_l = img_lab[:,:,0] # 拉出L通道
# 將亮度通道調整為網路輸入大小
img_l_rs = cv.resize(img_l, (W_in, H_in)) #
img_l_rs -= 50 # 減去50中心化
net.setInput(cv.dnn.blobFromImage(img_l_rs))
ab_dec = net.forward()[0,:,:,:].transpose((1,2,0)) # 這是我們的結果
(H_orig,W_orig) = img_rgb.shape[:2] # 原始影像大小
ab_dec_us = cv.resize(ab_dec, (W_orig, H_orig))
img_lab_out = np.concatenate((img_l[:,:,np.newaxis],ab_dec_us),axis=2) # 與原始影像 L 連接
img_bgr_out = np.clip(cv.cvtColor(img_lab_out, cv.COLOR_Lab2BGR), 0, 1)
outputFile = args.input[:-4]+'_colorized.png'
cv.imwrite(outputFile, (img_bgr_out*255).astype(np.uint8))
print('Colorized image saved as '+outputFile)
print('Done !!!')
視頻著色代碼
# colorizeVideo.py
# Usage
# python colorizeVideo.py --input greyscaleVideo.mp4
import numpy as np
import cv2 as cv
import argparse
import os.path
parser = argparse.ArgumentParser(description='Colorize GreyScale Video')
parser.add_argument('--input', help='Path to video file.', default="greyscaleVideo.mp4")
args = parser.parse_args()
if args.input == None:
print('Please give the input greyscale video file.')
print('Usage example: python colorizeVideo.py --input greyscaleVideo.mp4')
exit()
if os.path.isfile(args.input) == 0:
print('Input file does not exist')
exit()
# 讀取輸入視頻
cap = cv.VideoCapture(args.input)
hasFrame, frame = cap.read()
outputFile = args.input[:-4] + '_colorized.avi'
vid_writer = cv.VideoWriter(outputFile, cv.VideoWriter_fourcc('M', 'J', 'P', 'G'), 60, (frame.shape[1], frame.shape[0]))
# 指定 2 個模型檔案的路徑
protoFile = "./models/colorization_deploy_v2.prototxt"
weightsFile = "./models/colorization_release_v2.caffemodel"
# weightsFile = "./models/colorization_release_v2_norebal.caffemodel"
# 加載聚類中心
pts_in_hull = np.load('./pts_in_hull.npy')
# 將網路讀入記憶體
net = cv.dnn.readNetFromCaffe(protoFile, weightsFile)
# 將聚類中心填充為 1x1 卷積核
pts_in_hull = pts_in_hull.transpose().reshape(2, 313, 1, 1)
net.getLayer(net.getLayerId('class8_ab')).blobs = [pts_in_hull.astype(np.float32)]
net.getLayer(net.getLayerId('conv8_313_rh')).blobs = [np.full([1, 313], 2.606, np.float32)]
# 來自 opencv 示例
W_in = 224
H_in = 224
while cv.waitKey(1):
hasFrame, frame = cap.read()
frameCopy = np.copy(frame)
if not hasFrame:
break
img_rgb = (frame[:, :, [2, 1, 0]] * 1.0 / 255).astype(np.float32)
img_lab = cv.cvtColor(img_rgb, cv.COLOR_RGB2Lab)
img_l = img_lab[:, :, 0] # 拉出L通道
# 將亮度通道調整為網路輸入大小
img_l_rs = cv.resize(img_l, (W_in, H_in))
img_l_rs -= 50 # 減去50中心化
net.setInput(cv.dnn.blobFromImage(img_l_rs))
ab_dec = net.forward()[0, :, :, :].transpose((1, 2, 0)) # 結果
(H_orig, W_orig) = img_rgb.shape[:2] # 原始影像尺寸
ab_dec_us = cv.resize(ab_dec, (W_orig, H_orig))
img_lab_out = np.concatenate((img_l[:, :, np.newaxis], ab_dec_us), axis=2) # 與原始 L 通道拼接
img_bgr_out = np.clip(cv.cvtColor(img_lab_out, cv.COLOR_Lab2BGR), 0, 1)
vid_writer.write((img_bgr_out * 255).astype(np.uint8))
vid_writer.release()
print('Colorized video saved as ' + outputFile)
print('Done !!!')
(2)C++
影像著色代碼
// colorizeImage.cpp
// Usage
// ./colorizeImage.out greyscaleImage.png
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace cv::dnn;
using namespace std;
// 來自 pts_in_hull.npy 的 313 個 ab 聚類中心(已經轉置)
static float hull_pts[] = {
-90., -90., -90., -90., -90., -80., -80., -80., -80., -80., -80., -80., -80., -70., -70., -70., -70., -70., -70., -70., -70.,
-70., -70., -60., -60., -60., -60., -60., -60., -60., -60., -60., -60., -60., -60., -50., -50., -50., -50., -50., -50., -50., -50.,
-50., -50., -50., -50., -50., -50., -40., -40., -40., -40., -40., -40., -40., -40., -40., -40., -40., -40., -40., -40., -40., -30.,
-30., -30., -30., -30., -30., -30., -30., -30., -30., -30., -30., -30., -30., -30., -30., -20., -20., -20., -20., -20., -20., -20.,
-20., -20., -20., -20., -20., -20., -20., -20., -20., -10., -10., -10., -10., -10., -10., -10., -10., -10., -10., -10., -10., -10.,
-10., -10., -10., -10., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 10., 10., 10., 10., 10., 10., 10.,
10., 10., 10., 10., 10., 10., 10., 10., 10., 10., 10., 20., 20., 20., 20., 20., 20., 20., 20., 20., 20., 20., 20., 20., 20., 20.,
20., 20., 20., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 40., 40., 40., 40.,
40., 40., 40., 40., 40., 40., 40., 40., 40., 40., 40., 40., 40., 40., 40., 40., 50., 50., 50., 50., 50., 50., 50., 50., 50., 50.,
50., 50., 50., 50., 50., 50., 50., 50., 50., 60., 60., 60., 60., 60., 60., 60., 60., 60., 60., 60., 60., 60., 60., 60., 60., 60.,
60., 60., 60., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 80., 80., 80.,
80., 80., 80., 80., 80., 80., 80., 80., 80., 80., 80., 80., 80., 80., 80., 80., 90., 90., 90., 90., 90., 90., 90., 90., 90., 90.,
90., 90., 90., 90., 90., 90., 90., 90., 90., 100., 100., 100., 100., 100., 100., 100., 100., 100., 100., 50., 60., 70., 80., 90.,
20., 30., 40., 50., 60., 70., 80., 90., 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., -20., -10., 0., 10., 20., 30., 40., 50.,
60., 70., 80., 90., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100., -40., -30., -20., -10., 0., 10., 20.,
30., 40., 50., 60., 70., 80., 90., 100., -50., -40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100., -50.,
-40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100., -60., -50., -40., -30., -20., -10., 0., 10., 20.,
30., 40., 50., 60., 70., 80., 90., 100., -70., -60., -50., -40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., 80., 90.,
100., -80., -70., -60., -50., -40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., -80., -70., -60., -50.,
-40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., -90., -80., -70., -60., -50., -40., -30., -20., -10.,
0., 10., 20., 30., 40., 50., 60., 70., 80., 90., -100., -90., -80., -70., -60., -50., -40., -30., -20., -10., 0., 10., 20., 30.,
40., 50., 60., 70., 80., 90., -100., -90., -80., -70., -60., -50., -40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70.,
80., -110., -100., -90., -80., -70., -60., -50., -40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., 80., -110., -100.,
-90., -80., -70., -60., -50., -40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., 80., -110., -100., -90., -80., -70.,
-60., -50., -40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., -110., -100., -90., -80., -70., -60., -50., -40., -30.,
-20., -10., 0., 10., 20., 30., 40., 50., 60., 70., -90., -80., -70., -60., -50., -40., -30., -20., -10., 0.
};
int main(int argc, char **argv)
{
string imageFileName;
// 從命令列獲取引數
if (argc < 2)
{
cout << "Please input the greyscale image filename." << endl;
cout << "Usage example: ./colorizeImage.out greyscaleImage.png" << endl;
return 1;
}
imageFileName = argv[1];
Mat img = imread(imageFileName);
if (img.empty())
{
cout << "Can't read image from file: " << imageFileName << endl;
return 2;
}
string protoFile = "./models/colorization_deploy_v2.prototxt";
string weightsFile = "./models/colorization_release_v2.caffemodel";
//string weightsFile = "./models/colorization_release_v2_norebal.caffemodel";
double t = (double) cv::getTickCount();
// 預訓練網路的固定輸入大小
const int W_in = 224;
const int H_in = 224;
Net net = dnn::readNetFromCaffe(protoFile, weightsFile);
// 設定額外的層:
int sz[] = {2, 313, 1, 1};
const Mat pts_in_hull(4, sz, CV_32F, hull_pts);
Ptr<dnn::Layer> class8_ab = net.getLayer("class8_ab");
class8_ab->blobs.push_back(pts_in_hull);
Ptr<dnn::Layer> conv8_313_rh = net.getLayer("conv8_313_rh");
conv8_313_rh->blobs.push_back(Mat(1, 313, CV_32F, Scalar(2.606)));
// 提取L通道并減去平均值
Mat lab, L, input;
img.convertTo(img, CV_32F, 1.0/255);
cvtColor(img, lab, COLOR_BGR2Lab);
extractChannel(lab, L, 0);
resize(L, input, Size(W_in, H_in));
input -= 50;
// 通過網路運行L通道
Mat inputBlob = blobFromImage(input);
net.setInput(inputBlob);
Mat result = net.forward();
// 從網路輸出中檢索計算出的 a,b 通道
Size siz(result.size[2], result.size[3]);
Mat a = Mat(siz, CV_32F, result.ptr(0,0));
Mat b = Mat(siz, CV_32F, result.ptr(0,1));
resize(a, a, img.size());
resize(b, b, img.size());
// 合并,并轉換回 BGR
Mat color, chn[] = {L, a, b};
merge(chn, 3, lab);
cvtColor(lab, color, COLOR_Lab2BGR);
t = ((double)cv::getTickCount() - t)/cv::getTickFrequency();
cout << "Time taken : " << t << " secs" << endl;
string str = imageFileName;
str.replace(str.end()-4, str.end(), "");
str = str+"_colorized.png";
color = color*255;
color.convertTo(color, CV_8U);
imwrite(str, color);
cout << "Colorized image saved as " << str << endl;
return 0;
}
視頻著色代碼
// colorizeVideo.cpp
// Usage
// ./colorizeVideo.out greyscaleVideo.mp4
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace cv::dnn;
using namespace std;
// 來自 pts_in_hull.npy 的 313 個 ab 聚類中心(已經轉置)
static float hull_pts[] = {
-90., -90., -90., -90., -90., -80., -80., -80., -80., -80., -80., -80., -80., -70., -70., -70., -70., -70., -70., -70., -70.,
-70., -70., -60., -60., -60., -60., -60., -60., -60., -60., -60., -60., -60., -60., -50., -50., -50., -50., -50., -50., -50., -50.,
-50., -50., -50., -50., -50., -50., -40., -40., -40., -40., -40., -40., -40., -40., -40., -40., -40., -40., -40., -40., -40., -30.,
-30., -30., -30., -30., -30., -30., -30., -30., -30., -30., -30., -30., -30., -30., -30., -20., -20., -20., -20., -20., -20., -20.,
-20., -20., -20., -20., -20., -20., -20., -20., -20., -10., -10., -10., -10., -10., -10., -10., -10., -10., -10., -10., -10., -10.,
-10., -10., -10., -10., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 10., 10., 10., 10., 10., 10., 10.,
10., 10., 10., 10., 10., 10., 10., 10., 10., 10., 10., 20., 20., 20., 20., 20., 20., 20., 20., 20., 20., 20., 20., 20., 20., 20.,
20., 20., 20., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 30., 40., 40., 40., 40.,
40., 40., 40., 40., 40., 40., 40., 40., 40., 40., 40., 40., 40., 40., 40., 40., 50., 50., 50., 50., 50., 50., 50., 50., 50., 50.,
50., 50., 50., 50., 50., 50., 50., 50., 50., 60., 60., 60., 60., 60., 60., 60., 60., 60., 60., 60., 60., 60., 60., 60., 60., 60.,
60., 60., 60., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 70., 80., 80., 80.,
80., 80., 80., 80., 80., 80., 80., 80., 80., 80., 80., 80., 80., 80., 80., 80., 90., 90., 90., 90., 90., 90., 90., 90., 90., 90.,
90., 90., 90., 90., 90., 90., 90., 90., 90., 100., 100., 100., 100., 100., 100., 100., 100., 100., 100., 50., 60., 70., 80., 90.,
20., 30., 40., 50., 60., 70., 80., 90., 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., -20., -10., 0., 10., 20., 30., 40., 50.,
60., 70., 80., 90., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100., -40., -30., -20., -10., 0., 10., 20.,
30., 40., 50., 60., 70., 80., 90., 100., -50., -40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100., -50.,
-40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100., -60., -50., -40., -30., -20., -10., 0., 10., 20.,
30., 40., 50., 60., 70., 80., 90., 100., -70., -60., -50., -40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., 80., 90.,
100., -80., -70., -60., -50., -40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., -80., -70., -60., -50.,
-40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., -90., -80., -70., -60., -50., -40., -30., -20., -10.,
0., 10., 20., 30., 40., 50., 60., 70., 80., 90., -100., -90., -80., -70., -60., -50., -40., -30., -20., -10., 0., 10., 20., 30.,
40., 50., 60., 70., 80., 90., -100., -90., -80., -70., -60., -50., -40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70.,
80., -110., -100., -90., -80., -70., -60., -50., -40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., 80., -110., -100.,
-90., -80., -70., -60., -50., -40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., 80., -110., -100., -90., -80., -70.,
-60., -50., -40., -30., -20., -10., 0., 10., 20., 30., 40., 50., 60., 70., -110., -100., -90., -80., -70., -60., -50., -40., -30.,
-20., -10., 0., 10., 20., 30., 40., 50., 60., 70., -90., -80., -70., -60., -50., -40., -30., -20., -10., 0.
};
int main(int argc, char **argv)
{
string videoFileName;
// 從命令列獲取引數
if (argc < 2)
{
cout << "Please input the greyscale video filename." << endl;
cout << "Usage example: ./colorizeVideo.out greyscaleVideo.mp4" << endl;
return 1;
}
videoFileName = argv[1];
cv::VideoCapture cap(videoFileName);
if (!cap.isOpened())
{
cerr << "Unable to open video" << endl;
return 1;
}
string protoFile = "./models/colorization_deploy_v2.prototxt";
string weightsFile = "./models/colorization_release_v2.caffemodel";
//string weightsFile = "./models/colorization_release_v2_norebal.caffemodel";
Mat frame, frameCopy;
int frameWidth = cap.get(CAP_PROP_FRAME_WIDTH);
int frameHeight = cap.get(CAP_PROP_FRAME_HEIGHT);
string str = videoFileName;
str.replace(str.end()-4, str.end(), "");
string outVideoFileName = str+"_colorized.avi";
VideoWriter video(outVideoFileName, VideoWriter::fourcc('M','J','P','G'), 60, Size(frameWidth,frameHeight));
// 預訓練網路的固定輸入大小
const int W_in = 224;
const int H_in = 224;
Net net = dnn::readNetFromCaffe(protoFile, weightsFile);
// 設定附加層
int sz[] = {2, 313, 1, 1};
const Mat pts_in_hull(4, sz, CV_32F, hull_pts);
Ptr<dnn::Layer> class8_ab = net.getLayer("class8_ab");
class8_ab->blobs.push_back(pts_in_hull);
Ptr<dnn::Layer> conv8_313_rh = net.getLayer("conv8_313_rh");
conv8_313_rh->blobs.push_back(Mat(1, 313, CV_32F, Scalar(2.606)));
for(;;)
{
cap >> frame;
if (frame.empty()) break;
frameCopy = frame.clone();
// 提取L通道并減去平均值
Mat lab, L, input;
frame.convertTo(frame, CV_32F, 1.0/255);
cvtColor(frame, lab, COLOR_BGR2Lab);
extractChannel(lab, L, 0);
resize(L, input, Size(W_in, H_in));
input -= 50;
// 通過網路運行L通道
Mat inputBlob = blobFromImage(input);
net.setInput(inputBlob);
Mat result = net.forward();
// 從網路輸出中提取計算出的 a,b 通道
Size siz(result.size[2], result.size[3]);
Mat a = Mat(siz, CV_32F, result.ptr(0,0));
Mat b = Mat(siz, CV_32F, result.ptr(0,1));
resize(a, a, frame.size());
resize(b, b, frame.size());
// 合并,并轉換回 BGR
Mat coloredFrame, chn[] = {L, a, b};
merge(chn, 3, lab);
cvtColor(lab, coloredFrame, COLOR_Lab2BGR);
coloredFrame = coloredFrame*255;
coloredFrame.convertTo(coloredFrame, CV_8U);
video.write(coloredFrame);
}
cout << "Colorized video saved as " << outVideoFileName << endl << "Done !!!" << endl;
cap.release();
video.release();
return 0;
}
7.代碼決議
7.1讀取模型
我們在代碼中提供了protoFile和weightsFile的路徑,選擇合適的模型,這取決于你是否想要使用顏色平衡,我們默認使用顏色再平衡模型,讀取輸入影像并定義網路的輸入大小為224×224,將網路讀入記憶體,
python
# 指定模型檔案的路徑
protoFile = "./models/colorization_deploy_v2.prototxt"
weightsFile = "./models/colorization_release_v2.caffemodel"
#weightsFile = "./models/colorization_release_v2_norebal.caffemodel";
# 讀取輸入影像
frame = cv.imread("./dog-greyscale.png")
W_in = 224
H_in = 224
# 將網路讀入記憶體
net = cv.dnn.readNetFromCaffe(protoFile, weightsFile)
C++
// 指定 2 個檔案的路徑
string protoFile = "./models/colorization_deploy_v2.prototxt";
string weightsFile = "./models/colorization_release_v2.caffemodel";
//string weightsFile = "./models/colorization_release_v2_norebal.caffemodel";
Mat img = imread(imageFile);
const int W_in = 224;
const int H_in = 224;
// 將網路讀入記憶體
Net net = readNetFromCaffe(protoFile, weightsFile);
7.1加載量化的 bin 聚類中心
接下來,我們加載量化的 bin 聚類中心,然后我們為313個bin聚類中心中的每個聚類中心分配1x1核,并將它們分配到網路中相應的層,最后,我們添加一個非零值的縮放層,
python
# 加載 bin 聚類中心
pts_in_hull = np.load('./pts_in_hull.npy')
# 將聚類中心填充為 1x1 卷積核
pts_in_hull = pts_in_hull.transpose().reshape(2, 313, 1, 1)
net.getLayer(net.getLayerId('class8_ab')).blobs = [pts_in_hull.astype(np.float32)]
net.getLayer(net.getLayerId('conv8_313_rh')).blobs = [np.full([1, 313], 2.606, np.float32)]
C++
// 將聚類中心填充為 1x1 卷積核
int sz[] = {2, 313, 1, 1};
const Mat pts_in_hull(4, sz, CV_32F, hull_pts);
Ptr<dnn::Layer> class8_ab = net.getLayer("class8_ab");
class8_ab->blobs.push_back(pts_in_hull);
Ptr<dnn::Layer> conv8_313_rh = net.getLayer("conv8_313_rh");
conv8_313_rh->blobs.push_back(Mat(1, 313, CV_32F, Scalar(2.606)));
7.3將影像轉換為 CIE Lab 色彩空間
對輸入的RGB影像進行縮放,使其值在0-1的范圍內,然后將其轉換為Lab顏色空間并提取出亮度通道,
python
# 將輸入影像的 rgb 值轉換為 0 到 1 的范圍
img_rgb = (frame[:,:,[2, 1, 0]] * 1.0 / 255).astype(np.float32)
img_lab = cv.cvtColor(img_rgb, cv.COLOR_RGB2Lab)
img_l = img_lab[:,:,0] # 拉出L通道
C++
Mat lab, L, input;
img.convertTo(img, CV_32F, 1.0/255);
cvtColor(img, lab, COLOR_BGR2Lab);
extractChannel(lab, L, 0);
原始影像中的亮度通道被調整為網路輸入大小,在這種情況下為 (224,224),通常,亮度通道的范圍是 0 到 100,所以我們減去 50 使其以 0 為中心,
python
# 將亮度通道調整為網路輸入大小
img_l_rs = cv.resize(img_l, (W_in, H_in))
img_l_rs -= 50 # 中心化
C++
Mat lab, L, input;
img.convertTo(img, CV_32F, 1.0/255);
cvtColor(img, lab, COLOR_BGR2Lab);
extractChannel(lab, L, 0);
然后我們將縮放后的均值中心亮度通道作為前向傳遞的輸入提供給網路,前向傳遞的輸出是影像的預測 ab 通道,將其縮放回原始影像大小,然后與原始大小的亮度影像(在原始解析度中較早提取)合并以獲得輸出 Lab 影像,然后將其轉換為 RGB 顏色空間以獲得最終的彩色影像,然后我們可以保存輸出影像,
python
net.setInput(cv.dnn.blobFromImage(img_l_rs))
ab_dec = net.forward()[0,:,:,:].transpose((1,2,0)) # 結果
(H_orig,W_orig) = img_rgb.shape[:2] # 原始影像尺寸
ab_dec_us = cv.resize(ab_dec, (W_orig, H_orig))
img_lab_out = np.concatenate((img_l[:,:,np.newaxis],ab_dec_us),axis=2) # 與原始影像 L 拼接
img_bgr_out = np.clip(cv.cvtColor(img_lab_out, cv.COLOR_Lab2BGR), 0, 1)
cv.imwrite('dog_colorized.png', cv.resize(img_bgr_out*255, imshowSize))
C++
// 通過網路運行L通道
Mat inputBlob = blobFromImage(input);
net.setInput(inputBlob);
Mat result = net.forward();
// 從網路輸出中提取計算出的 a,b 通道并將它們調整為原始影像大小
Size siz(result.size[2], result.size[3]);
Mat a = Mat(siz, CV_32F, result.ptr(0,0));
Mat b = Mat(siz, CV_32F, result.ptr(0,1));
resize(a, a, img.size());
resize(b, b, img.size());
// 合并并轉換回 BGR
Mat color, chn[] = {L, a, b};
merge(chn, 3, lab);
cvtColor(lab, color, COLOR_Lab2BGR);
結果展示

參考目錄
https://learnopencv.com/convolutional-neural-network-based-image-colorization-using-opencv/
https://github.com/richzhang/colorization/blob/caffe/colorization/demo/colorization_demo_v2.ipynb
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/312244.html
標籤:其他
