【问题标题】:Scipy: Convert RGB TIFF to grayscale TIFF and output it on MatplotlibScipy:将 RGB TIFF 转换为灰度 TIFF 并在 Matplotlib 上输出
【发布时间】:2012-05-11 08:31:03
【问题描述】:

我想在 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 好吧,这个 tiff 文件由 3 个波段组成,R、G 和 B 所以,band1Array、band2Array 和 band3Array 只是将这些波段转换为数组。
  • 这不是你用的redgreenblue吗?
  • @lukecampbell 哎呀,谢谢你的收获!我抄错了,哈哈。已编辑。
  • 最后两行应该是pyplot.imshow(gray, cmap='gray');pyplot.show()。为我工作。

标签: python matplotlib rgb grayscale


【解决方案1】:

我没有安装 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”)之外的其他值可能很简单,以获得您想要的东西,但我不确定您看到的是什么。

这是生成的图像(不要问我为什么原件是颠倒的——不知道是什么原因造成的):

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 2021-06-10
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多