Python 使用 Numpy 将 rgb 像素数组转换为灰度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41971663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use Numpy to convert rgb pixel array into grayscale
提问by SlothFriend
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?
使用 Numpy 将 rgb 像素值的大小 (x, y, 3) 数组转换为灰度像素值的大小 (x, y, 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.
我有一个函数 rgbToGrey(rgbArray) 可以采用 [r,g,b] 数组并返回灰度值。我想将它与 Numpy 一起使用,以将数组的第 3 维从大小 3 缩小到大小 1。
How can I do this?
我怎样才能做到这一点?
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.
注意:如果我有原始图像并且可以先使用 Pillow 对其进行灰度处理,这将非常容易,但我没有它。
UPDATE:
更新:
The function I was looking for was np.dot()
.
我正在寻找的功能是np.dot()
.
From the answer to this quesiton:
从这个问题的答案:
Assuming we convert rgb into greyscale through the formula:
假设我们通过公式将 rgb 转换为灰度:
.3r * .6g * .1b = grey,
.3r * .6g * .1b = 灰色,
we can do np.dot(rgb[...,:3], [.3, .6, .1])
to get what I'm looking for, a 2d array of grey-only values.
我们可以做得到np.dot(rgb[...,:3], [.3, .6, .1])
我正在寻找的东西,一个只有灰色值的二维数组。
回答by lange
See the answers in another thread.
请参阅另一个线程中的答案。
Essentially:
本质上:
gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
np.dot(rgb[...,:3], [0.299, 0.587, 0.114])