Scipy:将RGB TIFF转换为灰度TIFF并在Matplotlib上输出

3

我想要在TIFF文件中操作RGB波段,并将灰度地图输出到matplotlib上。目前我的代码是这样的,但是我无法将其转换为灰度:

import scipy as N
import gdal
import sys
import matplotlib.pyplot as pyplot

tif = gdal.Open('filename.tif')

band1 = tif.GetRasterBand(1)
band2 = tif.GetRasterBand(2)
band3 = tif.GetRasterBand(3)


red = band1.ReadAsArray()
green = band2.ReadAsArray()
blue = band3.ReadAsArray()

gray = (0.299*red + 0.587*green + 0.114*blue)

pyplot.figure()
pyplot.imshow(gray)
pylab.show()

以下是数组:

[[255 255 255 ..., 237 237 251]
 [255 255 255 ..., 237 237 251]
 [255 255 255 ..., 237 237 251]
 ..., 
 [237 237 237 ..., 237 237 251]
 [237 237 237 ..., 237 237 251]
 [242 242 242 ..., 242 242 252]]

[[255 255 255 ..., 239 239 251]
 [255 255 255 ..., 239 239 251]
 [255 255 255 ..., 239 239 251]
 ..., 
 [239 239 239 ..., 239 239 251]
 [239 239 239 ..., 239 239 251]
 [243 243 243 ..., 243 243 252]]

[[255 255 255 ..., 234 234 250]
 [255 255 255 ..., 234 234 250]
 [255 255 255 ..., 234 234 250]
 ..., 
 [234 234 234 ..., 234 234 250]
 [234 234 234 ..., 234 234 250]
 [239 239 239 ..., 239 239 251]]

有什么办法可以解决这个问题吗?

band1Array, band2Array, band3Array 的用途是什么,它们没有被引用。该转换为灰度的公式看起来是正确的。 - lukecampbell
@lukecampbell 嗯,这个tiff文件由3个波段R、G和B组成,因此band1Array、band2Array和band3Array只是将这些波段转换为数组。 - rudster
1
你用于 red green blue 的不就是这个吗? - lukecampbell
@lukecampbell 哎呀,谢谢提醒!我复制错了,哈哈。已编辑过。 - rudster
1
最后两行应该是 pyplot.imshow(gray, cmap='gray');pyplot.show()。对我来说有效。 - cgohlke
1个回答

6

我没有安装gdal,但使用PIL进行类似处理的方法如下:

import numpy as np
import Image
import matplotlib.pyplot as pyplot

img = Image.open("/Users/travis/Desktop/new_zealand.tif")

img.getdata()
r, g, b = img.split()

ra = np.array(r)
ga = np.array(g)
ba = np.array(b)

gray = (0.299*ra + 0.587*ga + 0.114*ba)

pyplot.figure()
pyplot.imshow(img)
pyplot.figure()
pyplot.imshow(gray)
pyplot.figure()
pyplot.imshow(gray, cmap="gray")

可能只需将颜色映射设置为除默认值(“jet”)之外的其他内容即可得到所需效果,但我不确定您看到了什么。
这些是生成的图像(不要问我为什么原始图像是倒置的——不确定是什么原因): first figure second figure third figure

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接