gpt4 book ai didi

python - 科学 : Convert RGB TIFF to grayscale TIFF and output it on Matplotlib

转载 作者:太空宇宙 更新时间:2023-11-03 14:31:19 27 4
gpt4 key购买 nike

我想在 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]]

知道如何解决这个问题吗?

最佳答案

我没有安装 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

关于python - 科学 : Convert RGB TIFF to grayscale TIFF and output it on Matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10404050/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com