rudster
rudster

Reputation: 1377

Scipy: Convert RGB TIFF to grayscale TIFF and output it on Matplotlib

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?

Upvotes: 3

Views: 9504

Answers (1)

Travis Vaught
Travis Vaught

Reputation: 358

I don't have gdal installed, but a similar approach using PIL looks like this:

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

It may be a simple matter of setting the color map to something besides the default ("jet") to get what you want, but I'm not sure what you're seeing.

Here are the images that are generated (don't ask me why the original is upside-down -- not sure what causes that):

first figure

second figure

third figure

Upvotes: 6

Related Questions