【发布时间】:2011-11-04 14:38:55
【问题描述】:
我通过 PIL 将 RGB 图像加载到 numpy 数组中。我得到一个 rows x cols x 3 数组。修修补补后,我得到了以下代码。我想学习如何在没有循环的情况下进行这样的数组/矩阵操作。
# 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 之后,我发现如果我的转换 3x3 是 not 矩阵,则 np.dot() 有效。诡异的。
def convert_rgb_to_ycc( rgb ) :
return np.dot( rgb, np.asarray( rgb_to_ycc ).T )
【问题讨论】:
标签: python image-processing numpy