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

rud*_*ter 3 python rgb matplotlib grayscale

我想在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()
Run Code Online (Sandbox Code Playgroud)

这些是数组:

[[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]]
Run Code Online (Sandbox Code Playgroud)

知道我该如何解决这个问题?

小智 5

我没有安装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")
Run Code Online (Sandbox Code Playgroud)

将颜色贴图设置为除默认值("jet")以外的其他内容可能很简单,以获得您想要的内容,但我不确定您所看到的内容.

以下是生成的图像(不要问我为什么原件是颠倒的 - 不确定是什么原因引起的):

第一个数字

第二个数字

第三个数字