色彩转换 opencv_python
程序员文章站
2023-12-27 08:19:27
...
色彩转换
首先要导入我们要使用的包
import numpy as np
import cv2
然后计算各通道的均值和方差
def image_stats(image):
#计算各通道在均值和标准差
(l, a, b) = cv2.split(image)
(lMean, lStd) = (l.mean(), l.std())
(aMean, aStd) = (a.mean(), a.std())
(bMean, bStd) = (b.mean(), b.std())
return (lMean, lStd, aMean, aStd, bMean, bStd)
导入我们需要读取的图片进行预处理
#预处理
s = cv2.imread('red.png')
t = cv2.imread('redball.png')
source = cv2.cvtColor(s, cv2.COLOR_BGR2LAB).astype("float32")
target = cv2.cvtColor(t, cv2.COLOR_BGR2LAB).astype("float32")
red.png
redball.png
然后显示redball的图像
cv2.imshow('sorce', t)
cv2.waitKey(0)
cv2.destroyAllWindows()
对色彩转换后的图片的处理
#计算并存储各通道的均值和标准差
(lMeanSrc, lStdSrc, aMeanSrc, aStdSrc, bMeanSrc, bStdSrc) = image_stats(source)
(lMeanTar, lStdTar, aMeanTar, aStdTar, bMeanTar, bStdTar) = image_stats(target)
(l, a, b) = cv2.split(target)
l -= lMeanTar
a -= aMeanTar
b -= bMeanTar
#通过标准差进行缩放
l = (lStdTar / lStdSrc) *l
a = (aStdTar / aStdSrc) *a
b = (bStdTar / bStdSrc) *b
#加上源图像色彩基调(均值)
l += lMeanSrc
a += aMeanSrc
b += bMeanSrc
#删去(0,255)区间外的像素值
l = np.clip(l, 0, 255)
a = np.clip(a, 0, 255)
b = np.clip(b, 0, 255)
transfer = cv2.merge([l, a, b])
transfer = cv2.cvtColor(transfer.astype("uint8"), cv2.COLOR_LAB2BGR)
显示色彩转换后的图片
transfer = cv2.resize(transfer, (0, 0), fx=0.4, fy=0.4)
t2 = cv2.resize(t, (0,0), fx=0.4, fy=0.4)
s2 = cv2.resize(s, (0,0), fx=0.4, fy=0.4)
cv2.imshow('transfer', transfer)
cv2.imshow('t', t2)
cv2.imshow('s', s2)
cv2.waitKey(0)
cv2.destroyAllWindows()
推荐阅读