将图片读取为灰度numpy数组,然后将其保存回去 [英] Read the picture as a grayscale numpy array, and save it back

查看:471
本文介绍了将图片读取为灰度numpy数组,然后将其保存回去的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下操作,希望能看到源图像的灰度版本:

I tried the following, expecting to see the grayscale version of source image:

from PIL import Image
import numpy as np
img = Image.open("img.png").convert('L')
arr = np.array(img.getdata())
field = np.resize(arr, (img.size[1], img.size[0]))
out = field
img = Image.fromarray(out, mode='L')
img.show()

但是由于某种原因,整个图像上有很多点,中间有黑色.为什么会发生?

But for some reason, the whole image is pretty much a lot of dots with black in between. Why does it happen?

推荐答案

使用来自Pillow对象的图像数据创建numpy数组时,建议该数组的默认精度为int32.我假设您的数据实际上是uint8,因为在实践中看到的大多数图像都是这种方式.因此,您必须明确确保该数组与图像中的数组具有相同的类型.简而言之,请确保在获取图像数据后数组为uint8,这将是代码 1 中的第四行.

When you are creating the numpy array using the image data from your Pillow object, be advised that the default precision of the array is int32. I'm assuming that your data is actually uint8 as most images seen in practice are this way. Therefore, you must explicitly ensure that the array is the same type as what was seen in your image. Simply put, ensure that the array is uint8 after you get the image data, so that would be the fourth line in your code1.

arr = np.array(img.getdata(), dtype=np.uint8) # Note the dtype input


1.请注意,我一开始在您的代码中添加了两行,以导入必要的程序包以使该代码正常工作(尽管图像处于脱机状态).

这篇关于将图片读取为灰度numpy数组,然后将其保存回去的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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