Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I want to manipulate RGB bands in a TIFF file and output the grayscale map on matplotlib. So far I have this code, but I couldn't get it on grayscale:

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()

And these are the arrays:

[[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]]

Any idea how can I fix this?

share|improve this question
1  
can you expand on what isn't working? what happens if you try to display one band (say red)? –  iant May 2 '12 at 12:18

1 Answer 1

Let's check if the gray is a 2D array (it should be) :

import numpy as np
np.shape(gray)
(10, 11) # just an as example

then plot it using a gray colormap

pyplot.imshow(gray, cmap = pyplot.cm.gist_gray)

Take a look of the available color maps at Cookbook/Matplotlib/Show colormaps.

Cheers.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.