将RGB图像转换为灰度并在python中操作像素数据 [英] Converting an RGB image to grayscale and manipulating the pixel data in python
问题描述
我有一个RGB图像,我想将其转换为灰度图像,这样我就可以为每个像素提供一个数字(可能在0和1之间)。这给了我一个矩阵,其尺寸等于图像像素的尺寸。然后我想对这个矩阵进行一些操作,并从这个被操纵的矩阵生成一个新的灰度图像。我怎么能这样做?
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?
推荐答案
我经常将图像用作NumPy数组 - 我这样做:
I frequently work with images as NumPy arrays - I do it like so:
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')
如果操作后你的数组值y不再在0-255范围内,你可以升级到16位TIFF或者只是重新缩放。
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.
-Aldo
这篇关于将RGB图像转换为灰度并在python中操作像素数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!