2014-02-27 172 views
1

我想将图像的颜色基础从RGB更改为其他颜色。我有一个矩阵M,我想应用于每个像素的RGB,我们可以将其定义为x ij将转换矩阵应用于OpenCV图像中的像素

我正在迭代NumPy图像的每个像素并手动计算Mx ij。我甚至无法在行上进行矢量化,因为RGB是1x3而不是3x1阵列。

有没有更好的方法来做到这一点?也许在OpenCV或NumPy中的函数?

+0

http://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html#cv2.cvtColor – berak

+1

@berak我想做一个自定义转换,而不是cvtColor的标准转换之一 – wennho

回答

2

记不清规范的方式做到这一点(可能避免转置),但这应该工作:

import numpy as np 

M = np.random.random_sample((3, 3)) 

rgb = np.random.random_sample((5, 4, 3)) 

slow_result = np.zeros_like(rgb) 
for i in range(rgb.shape[0]): 
    for j in range(rgb.shape[1]): 
     slow_result[i, j, :] = np.dot(M, rgb[i, j, :]) 

# faster method 
rgb_reshaped = rgb.reshape((rgb.shape[0] * rgb.shape[1], rgb.shape[2])) 
result = np.dot(M, rgb_reshaped.T).T.reshape(rgb.shape) 

print np.allclose(slow_result, result) 

如果它是标准的色彩空间之间的转换,那么你应该使用Scikit图片: