使用numpy将棕褐色效果应用于3D数组

时间:2014-05-22 09:24:10

标签: python arrays numpy

在numpy中我想要一个3d数组的颜色值(2d代表一个图像,每个像素是一个RGB颜色)并为它应用一个棕褐色滤镜。假设颜色由r, g, b定义,应用棕褐色滤镜后应返回的颜色为:

sepia_r = .393*r + .769*g + .189&b
sepia_g = .349*r + .686*g + .168*b
sepia_b = .272*r + .534*g + .131*b

使用大型阵列(大概是一个由3个长向量组成的1080x864阵列)实时完成这项工作的最快方法是什么?

2 个答案:

答案 0 :(得分:4)

假设标准图像阵列组织为(height, width, channels),您可以直接使用numpy矩阵乘法。

from skimage.data import lena  # Color image version of lena. If you don't have skimage, use any image
import matplotlib.pyplot as plt

img = lena().astype(float) / 256.
plt.figure()
plt.subplot(1, 2, 1)
plt.imshow(img)

sepia_filter = np.array([[.393, .769, .189],
                         [.349, .686, .168],
                         [.272, .534, .131]])

# here goes the filtering
sepia_img = img.dot(sepia_filter.T)

# Unfortunately your filter lines do not have unit sum, so we need to rescale
sepia_img /= sepia_img.max()

plt.subplot(1, 2, 2)
plt.imshow(sepia_img)
plt.show()

答案 1 :(得分:1)

根据我对numpy速度的体验,总是试图找到完成整个工作的全局指令。 我应该安排一个带有r值的数组,另一个带有g值的数组和带有b值的最后一个数组,并使用multiply:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.multiply.html