如何有效地将功能应用于图像中每个像素的每个通道(用于颜色转换)?

时间:2019-02-18 17:17:43

标签: python algorithm numpy opencv image-processing

我正在尝试实现Reinhard的方法,以使用目标图像的颜色分布对研究项目中传入的图像进行颜色归一化。我已经使代码可以正常工作并且可以正确输出,但是速度很慢。遍历300张图像大约需要20分钟。我很确定瓶颈是如何处理将功能应用于每个图像的瓶颈。我目前正在遍历图像的每个像素,并将以下功能应用于每个通道。

def reinhard(target, img):

    #converts image and target from BGR colorspace to l alpha beta
    lAB_img = cv2.cvtColor(img, cv2.COLOR_BGR2Lab)
    lAB_tar = cv2.cvtColor(target, cv2.COLOR_BGR2Lab)

    #finds mean and standard deviation for each color channel across the entire image
    (mean, std) = cv2.meanStdDev(lAB_img)
    (mean_tar, std_tar) = cv2.meanStdDev(lAB_tar)

    #iterates over image implementing formula to map color normalized pixels to target image
    for y in range(512):
        for x in range(512):
            lAB_tar[x, y, 0] = (lAB_img[x, y, 0] - mean[0]) / std[0] * std_tar[0] + mean_tar[0]
            lAB_tar[x, y, 1] = (lAB_img[x, y, 1] - mean[1]) / std[1] * std_tar[1] + mean_tar[1]
            lAB_tar[x, y, 2] = (lAB_img[x, y, 2] - mean[2]) / std[2] * std_tar[2] + mean_tar[2]
    mapped = cv2.cvtColor(lAB_tar, cv2.COLOR_Lab2BGR)
    return mapped

我的主管告诉我,我可以尝试使用矩阵一次全部应用该函数来改善运行时间,但是我不确定如何做到这一点。

2 个答案:

答案 0 :(得分:3)

原件和目标:

enter image description here enter image description here

使用5 ms中的Reinhard'方法重新进行颜色转移:

enter image description here enter image description here


我更喜欢在numpy vectorized operations之外的python loops中实现公式。

# implementing the formula
#(Io - mo)/so*st + mt  = Io * (st/so) + mt - mo*(st/so)
ratio = (std_tar/std_ori).reshape(-1)
offset = (mean_tar - mean_ori*std_tar/std_ori).reshape(-1)
lab_tar = cv2.convertScaleAbs(lab_ori*ratio + offset)

代码如下:

# 2019/02/19 by knight-金
# https://stackoverflow.com/a/54757659/3547485

import numpy as np
import cv2

def reinhard(target, original):
    # cvtColor: COLOR_BGR2Lab
    lab_tar = cv2.cvtColor(target, cv2.COLOR_BGR2Lab)
    lab_ori = cv2.cvtColor(original, cv2.COLOR_BGR2Lab)

    # meanStdDev: calculate mean and stadard deviation
    mean_tar, std_tar = cv2.meanStdDev(lab_tar)
    mean_ori, std_ori = cv2.meanStdDev(lab_ori)

    # implementing the formula
    #(Io - mo)/so*st + mt  = Io * (st/so) + mt - mo*(st/so)
    ratio = (std_tar/std_ori).reshape(-1)
    offset = (mean_tar - mean_ori*std_tar/std_ori).reshape(-1)
    lab_tar = cv2.convertScaleAbs(lab_ori*ratio + offset)

    # convert back
    mapped = cv2.cvtColor(lab_tar, cv2.COLOR_Lab2BGR)
    return mapped

if __name__ == "__main__":
    ori = cv2.imread("ori.png")
    tar = cv2.imread("tar.png")

    mapped = reinhard(tar, ori)
    cv2.imwrite("mapped.png", mapped)

    mapped_inv = reinhard(ori, tar)
    cv2.imwrite("mapped_inv.png", mapped)

答案 1 :(得分:1)

在查看numpy文档后,我设法弄清楚了。我只需要用适当的数组访问替换嵌套的for循环。花费不到一分钟的时间来遍历所有300张图像。

if (channelData.ContainsKey("postback"))