使用Numpy将RGB像素阵列转换为灰度 [英] Use Numpy to convert rgb pixel array into grayscale
问题描述
使用Numpy将大小为(x,y,3)的rgb像素值数组转换为大小为(x,y,1)的灰度像素值的最佳方法是什么?
What's the best way to use Numpy to convert a size (x, y, 3) array of rgb pixel values to a size (x, y, 1) array of grayscale pixel values?
我有一个函数rgbToGrey(rgbArray),它可以使用[r,g,b]数组并返回灰度值.我想将其与Numpy一起使用以将数组的第3维从大小3缩小到大小1.
I have a function, rgbToGrey(rgbArray) that can take the [r,g,b] array and return the greyscale value. I'd like to use it along with Numpy to shrink the 3rd dimension of my array from size 3 to size 1.
我该怎么做?
注意:如果我有原始图像,并且可以先使用Pillow对其进行灰度处理,那么这将非常容易,但是我没有它.
Note: This would be pretty easy if I had the original image and could grayscale it first using Pillow, but I don't have it.
更新:
我正在寻找的功能是np.dot()
.
从答案到此问题:
假设我们通过以下公式将rgb转换为灰度:
Assuming we convert rgb into greyscale through the formula:
.3r * .6g * .1b =灰色,
.3r * .6g * .1b = grey,
我们可以执行np.dot(rgb[...,:3], [.3, .6, .1])
来获取我想要的东西,一个二维数组的纯灰色值.
we can do np.dot(rgb[...,:3], [.3, .6, .1])
to get what I'm looking for, a 2d array of grey-only values.
推荐答案
请参见本质上:
gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
这篇关于使用Numpy将RGB像素阵列转换为灰度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!