Monday, September 8, 2008

Merging RGB channels in python

How to merge 3 images which each contain grayscale data for a single channel into a single RGB image.

With PIL.Image:
import wx, numpy, Image
r = numpy.asarray(Image.open("r.tif"))
g = numpy.asarray(Image.open("g.tif"))
b = numpy.asarray(Image.open("b.tif"))
imRGB = Image.fromarray(numpy.dstack((r[:,:,0], g[:,:,0], b[:,:,0])))



With wx.Image:
import numpy, wx
def Merge(ims):
  width = ims[0].GetWidth()
  height = ims[0].GetHeight()
  dn = [numpy.fromstring(im.GetData(), 'uint8')[::3] for im in ims[:3]]
  for d in dn:
    d.shape=(height,width)
  img = wx.EmptyImage(width,height)
  img.SetData(numpy.dstack([d for d in dn]).flatten())
  return img
ims[0] = wx.Image('r.tif')
ims[1] = wx.Image('g.tif')
ims[2] = wx.Image('b.tif')
Merge(ims)

No comments: