首页 > 解决方案 > 我需要获取每个像素亮度的像素值(0-255)

问题描述

描述:

我正在使用 python 2.7,并且安装了包 PIL、pip、pip-9.0.1-py2.7.egg-info 和 Pillow-4.1.1-py2.7.egg-info

我试图让python分析图像并输出像素0-255及其相关像素值,最好以直方图或列表的形式。

我正在寻找的结果:

0 5

1 6

2 8

3 7

...

...

...

尝试:

我已经尝试卸载 pil,但失败了我已经安装了软件包 Image 在我卸载 pil 之前我无法安装 Pillow 所有这些都是在 Python 命令行上完成的

代码尝试 1:

from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
Image.open('C:\\Users\\tsamimi\\Documents\\BasilIce\\FreqVal\\06.953_UTC-clear basil ice.jpg').load()

im = Image.open('C:\\Users\\tsamimi\\Documents\\BasilIce\\FreqVal\\06.953_UTC-clear basil ice.jpg', 'r')

pix_val = list(im.getdata())

pix_val_flat = [x for sets in pix_val for x in sets]

代码尝试2:

from PIL import Image, ImageFile

ImageFile.LOAD_TRUNCATED_IMAGES = True

Image.open('C:\\Users\\abbot\\Documents\\BasilIce\\FreqVal\\06.953_UTC-clear basil ice.jpg').load()

im = Image.open('C:\\Users\\abbot\\Documents\\BasilIce\\FreqVal\\06.953_UTC-clear basil ice.jpg', 'r')

width, height = im.size

pixel_values = list(im.getdata())

代码 1,2 的输出:Process finished with exit code 0

结果去哪儿了?是缺少缩进吗?

谢谢

标签: pythonpython-imaging-library

解决方案


我终于找到了你想要的——这是一个直方图!幸运的是,这很简单,所以从这个卡通开始:

在此处输入图像描述

#!/usr/bin/env python3

from PIL import Image

# Load image as greyscale and calculate histogram
im = Image.open('cartoon.jpg').convert('L')
h = im.histogram()

# Print histogram
for idx, val in enumerate(h):
    print(idx,val)

样本输出

0 41513
1 2362
2 1323
3 1057
4 889
5 780
6 887
7 454
...
...
249 44
250 65
251 119
252 179
253 275
254 246
255 20

请注意,如果您想要 RGB 图像的直方图,请将第三行更改为:

im = Image.open('cartoon.jpg')

然后您将打印出 768 个值,前 256 个是红色分量,接下来是 256 个是绿色分量,最后 256 个是蓝色分量。


推荐阅读