显示灰度图像

2024-05-17 12:14:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标:

  1. 将图像读入PIL格式。
  2. 将其转换为灰度。
  3. 使用pylab绘制图像。

这是我使用的代码:

from PIL import Image
from pylab import *
import numpy as np

inputImage='C:\Test\Test1.jpg'
##outputImage='C:\Test\Output\Test1.jpg'

pilImage=Image.open(inputImage)
pilImage.draft('L',(500,500))
imageArray= np.asarray(pilImage)

imshow(imageArray)

##pilImage.save(outputImage)

axis('off')

show()

我的问题: 图像显示得就像颜色颠倒一样。

This is the Original Image

This is how it appears in the Python Window

但我知道图像正在转换成灰度,因为当我把它写到磁盘上时,它看起来就像一个灰度图像(正如我所期望的那样)。

我觉得问题出在核转变的某个地方。

我刚开始用Python编写图像处理程序。 建议和指导也将不胜感激。


Tags: fromtest图像imageimportpilnp灰度
2条回答

这将生成黑白图像:

pilImage=Image.open(inputImage)
pilImage = pilImage.convert('1')   #this convert to black&white
pilImage.draft('L',(500,500))

pilImage.save('outfile.png')

convert方法docs

convert

im.convert(mode) => image

Returns a converted copy of an image.
When translating from a palette image, this translates pixels through the palette.
If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette.

When from a colour image to black and white, the library uses the ITU-R 601-2 luma transform:

    L = R * 299/1000 + G * 587/1000 + B * 114/1000
When converting to a bilevel image (mode "1"), the source image is first converted to black and white.
Resulting values larger than 127 are then set to white, and the image is dithered.
To use other thresholds, use the point method.

您希望覆盖默认颜色贴图:

imshow(imageArray, cmap="Greys_r")

Here's a page on plotting images and pseudocolor in matplotlib

相关问题 更多 >