有没有办法使用枕头"Image.convert()"?在现有变量上? [英] Is there a way to use Pillows "Image.convert()" on an existing variable?

查看:138
本文介绍了有没有办法使用枕头"Image.convert()"?在现有变量上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

也许这个问题看起来很愚蠢,但是我尝试使用枕头Image.convert()将图像转换为灰度.我已经将此图像存储在变量img中,因为我已经对其进行了预处理,但是没有使用Pillow(类型:numpy.ndarray).所以我输入:

maybe this question looks stupid, but I try to use Pillows Image.convert() to convert an image to grayscale. This image I have stored in a variable img because I already pre-processed it, but not with Pillow (type: numpy.ndarray). So I type:

img = Image.convert('LA')

但是它似乎不起作用,因为它说:

But it does not seem to work, as it says:

AttributeError: module 'PIL.Image' has no attribute 'convert'

如果我键入img = Image.open("picture.jpg").convert('LA'),它可以工作,但是我想在已经存在的变量上使用它.我也不想保存预处理的图像只是为了打开并使用上一个命令将其转换,因为这样效率更低(就速度和CPU功率而言). 因此:有适当的方法吗?

If I type img = Image.open("picture.jpg").convert('LA') it works, but I want to use it on a variable that already exists. I also do not want to save the preprocessed image just to open and convert it with the previous command because this is even more inefficient (in terms of speed and CPU-power). So: Is there a proper way to do this?

谢谢您的帮助!

推荐答案

尽管您可以很好地将Numpy数组转换为PIL图像,然后将其转换为灰度,然后再转换回Numpy数组,如下所示:

Whilst you could perfectly well convert your Numpy array to a PIL Image and then convert that to greyscale and then convert back to a Numpy array like this:

PILImage = Image.fromarray(Numpyimg)
PILgrey  = PILImage.convert('L')
Numpygrey= np.array(PILgrey)

您也可以自行进行ITU-R 601-2亮度转换,即

You might as well just do the ITU-R 601-2 luma transform yourself, i.e.

L = 0.299 * Red + 0.587 * Green + 0.114 * Blue

因此,您将得到:

Numpygrey = np.dot(Numpyimg[...,:3], [0.299, 0.587, 0.114]).astype(np.uint8)

这篇关于有没有办法使用枕头"Image.convert()"?在现有变量上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆