我有装入经由PIL一个numpy的阵列的RGB图像。我得到了一个行x cols x 3数组。修补后,我得到了下面的代码。我想学习如何在没有循环的情况下做这样的数组/矩阵操作。3x3矩阵转换而不循环(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
我可以使用http://pypi.python.org/pypi/colormath(通过Using Python to convert color formats?),但我用这个作为一个练习学习numpy的。
上述Colormath库使用的点积。
# Perform the adaptation via matrix multiplication.
result_matrix = numpy.dot(var_matrix, rgb_matrix)
我的数学不是它应该在的地方。 np.dot()是我最好的选择吗?
编辑。更深层次的阅读colormath的apply_RGB_matrix()之后 - color_conversions.py,我发现np.dot如果转换3x3s是不矩阵()的作品。奇怪的。
def convert_rgb_to_ycc(rgb) :
return np.dot(rgb, np.asarray(rgb_to_ycc).T)
啊!实际上,使用3x3作为阵列而不是矩阵是解决方案。并且内联转换矩阵的确会使代码更好看。谢谢!而np.allclose()是学习的新东西。 –