将RGB图像转换为灰度图像并在python中操作像素数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23935840/
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
Converting an RGB image to grayscale and manipulating the pixel data in python
提问by lovespeed
I have an RGB image which I want to convert to a grayscale image, so that I can have one number (maybe between 0 and 1) for each pixel. This gives me a matrix which has the dimensions equal to that of the pixels of the image. Then I want to do some manipulations on this matrix and generate a new grayscale image from this manipulated matrix. How can I do this?
我有一个 RGB 图像,我想将其转换为灰度图像,以便每个像素都有一个数字(可能在 0 和 1 之间)。这给了我一个矩阵,其尺寸等于图像像素的尺寸。然后我想对这个矩阵做一些操作,并从这个被操作的矩阵生成一个新的灰度图像。我怎样才能做到这一点?
回答by Aldo
I frequently work with images as NumPy arrays - I do it like so:
我经常将图像作为 NumPy 数组处理 - 我这样做:
import numpy as np
from PIL import Image
x=Image.open('im1.jpg','r')
x=x.convert('L') #makes it greyscale
y=np.asarray(x.getdata(),dtype=np.float64).reshape((x.size[1],x.size[0]))
<manipulate matrix y...>
y=np.asarray(y,dtype=np.uint8) #if values still in range 0-255!
w=Image.fromarray(y,mode='L')
w.save('out.jpg')
If your array values y are no longer in the range 0-255 after the manipulations, you could step up to 16-bit TIFFs or simply rescale.
如果您的数组值 y 在操作后不再在 0-255 范围内,您可以升级到 16 位 TIFF 或简单地重新缩放。
-Aldo
-奥尔多