2014-02-27 71 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圖片: