# python – 无循环的3×3矩阵转换(RGB颜色转换)

``````# Note using matrix not array.
rgb_to_ycc = np.matrix(
(0.2990,  0.5870,  0.1140,
-0.1687, -0.3313,  0.5000,
0.5000, -0.4187, -0.0813,)
).reshape( 3,3 )

ycc_to_rgb = np.matrix(
( 1.0, 0.0, 1.4022,
1.0, -0.3456, -0.7145,
1.0, 1.7710, 0, )
).reshape( 3, 3 )

def convert_ycc_to_rgb( ycc ) :
# convert back to RGB
rgb = np.zeros_like( ycc )
for row in range(ycc.shape[0]) :
rgb[row] = ycc[row] * ycc_to_rgb.T
return rgb

def convert_rgb_to_ycc( rgb ) :
ycc = np.zeros_like( rgb )
for row in range(rgb.shape[0]):
ycc[row] = rgb[row] * rgb_to_ycc.T
return ycc
``````

``````# Perform the adaptation via matrix multiplication.
result_matrix = numpy.dot(var_matrix, rgb_matrix)
``````

``````def convert_rgb_to_ycc( rgb ) :
return np.dot( rgb, np.asarray( rgb_to_ycc ).T )
``````

convert RGB to YCC,所以我不想声称这是完整的计算,但是为了简化你发布的功能,是的,使用np.dot和numpy数组而不是numpy矩阵.

np.dot比numpy矩阵更通用.当使用*与numpy矩阵时,两个矩阵必须是2维的.

np.dot的文档说：

``````    For N dimensions it is a sum product over the last axis of `a` and
the second-to-last of `b`::

dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
``````

``````import numpy as np

def rgb_to_ycc(rgb):
M = np.array(
(0.2990,  0.5870,  0.1140,
-0.1687, -0.3313,  0.5000,
0.5000, -0.4187, -0.0813,)
).reshape( 3,3 )
return np.dot(rgb, M.T)

def convert_rgb_to_ycc( rgb ) :
M = np.matrix(
(0.2990,  0.5870,  0.1140,
-0.1687, -0.3313,  0.5000,
0.5000, -0.4187, -0.0813,)
).reshape( 3,3 )
shape=rgb.shape
rgb=rgb.reshape((-1,3))
ycc = np.zeros_like( rgb )
for i in range(len(rgb)):
ycc[i] = rgb[i] * M.T
return ycc.reshape(shape)

rgb=np.random.random((100,100,3))
assert np.allclose(rgb_to_ycc(rgb),convert_rgb_to_ycc(rgb))
``````