edit · print · PDF

Please note that all the SIEpedia's articles address specific issues or questions raised by IAC users, so they do not attempt to be rigorous or exhaustive, and may or may not be useful or applicable in different or more general contexts.

How to do an RGB-composite image with pyraf/python

R. Azzollini

#! /usr/bin/env python

def combineRGB(imageR,i mageG, imageB, outimage='RGB_out', outext='jpg', scales={'R':1.,'G':1.,'B':1.}, zrange=(0,1.), doLog=False, doBack=False, backRGB={'R':0,'G':0,'B':0}):
    # IMPORT STUFF
    from pyraf import iraf
    import sys
    import numarray as num
    import os
    import pyfits
    from time import time
    import string
    try: from mystop import stop
    except ImportError: print 'mystop module not found. But I can go on...'
    # END IMPORT

    # EXAMPLE OF INPUTS
    # imageR = 'GOODS-Sz_2048zero.fits'
    # imageG = 'GOODS-Sv_2048zero.fits'
    # imageB = 'GOODS-Sb_2048zero.fits'
    # outimage = 'GOODS-Srgb'
    # outext = 'png'

    # doLog = False
    # doBack = True
    # scales = {'R':2.11,'G':0.46,'B':1.}
    # zrange = (0.,0.5)
    # backRGB = {'R':155,'G':62,'B':21}

    # NAME SOME TEMPORAL FILES

    ttag = string.replace('%f'%time(),'.','_')

    tmpR = 'tmp_Rimg_%s.fits' % ttag
    tmpG = 'tmp_Gimg_%s.fits' % ttag
    tmpB = 'tmp_Bimg_%s.fits' % ttag

    isthere = os.path.exists

    # INNER TASK

    def rescaleit(image,newimage,scale=1.,zrange=(0.,1.),doLog=False,\
    backRGB=0.,blank=-1):
        # Read-out

        img = pyfits.getdata(image).copy()

        # Rescaling

        img *= scale

        img[num.where(img<zrange[0])] = zrange[0]
        img[num.where(img>zrange[1])] = zrange[1]

        # All values between 0 and 1
        img = (img - zrange[0]) / (zrange[1]-zrange[0])

        # Log scale (optional)
        if doLog:
            img += 1.
            img = num.log10(img)
            img = img / num.log10(2.)

        # Background

        if blank is not -1:
            back = backRGB / 255.
            img[num.where(blank)] = img[num.where(blank)]*0.+back

        # Write out
        pyfits.writeto(newimage,img)


    if doBack:
        blank = pyfits.getdata(imageR) == 0
        blank = blank & (pyfits.getdata(imageG) == 0)
        blank = blank & (pyfits.getdata(imageB) == 0)
    else :
        blank = -1

    # RE-SCALING OF INPUT IMAGES

    rescaleit(imageR, tmpR, scale=scales['R'], zrange = zrange,\
    doLog = True,backRGB = backRGB['R'],blank = blank)

    rescaleit(imageG, tmpG, scale=scales['G'], zrange = zrange, doLog = True,\
    backRGB = backRGB['G'],blank = blank)

    rescaleit(imageB, tmpB, scale=scales['B'], zrange = zrange, doLog = True,\
    backRGB = backRGB['B'],blank = blank)

    # CALL EXPORT TO DO RGB-COMBINATION (CORE)

    iraf.dataio(_doprint=0)
    iraf.export('%s,%s,%s'%(tmpR,tmpG,tmpB),outimage,'ppm',outtype="",\
    outbands="zscale(b1,0,1),zscale(b2,0,1),zscale(b3,0,1)")

    # FORMAT CONVERSION

    os.system('convert %s %s' % (outimage+'.ppm',outimage+'.'+outext))

    # DELETE TEMPORAL FILES

    os.system('rm %s %s %s' % (tmpR,tmpG,tmpB))
    os.system('rm %s' % (outimage+'.ppm',))

###############################################################################################
## to execute the program from the console ####################################################

if __name__=="__main__":

    from optparse import OptionParser
    import string
    import sys
    try : from mystop import stop
    except ImportError:
        print '\nI did not find "mystop" module... hope everything goes fine...'

    print \
    """\n'combineRGB' is a very simple script devised and shared by        
    Ruyman Azzollini
    (if you have any trouble with the program, contact him at :
ruyman@iac.es, and/or pray for half an hour)\n"
""

    parser = OptionParser()
    parser.add_option("-i","--images", dest="images", default=None, \
    help="Input images. EXAMPLE: -i 'R.fits,G.fits,B.fits'.")

    parser.add_option("-o","--outimage",dest="outimage",default='RGB_out',\
    help="Output image (without extension). Default is 'RGB_out'. EXAMPLE: -o Churri.")

    parser.add_option("-e","--extension",dest="extension",default='jpg',\
    help="Output image extension. Default is 'jpg'. EXAMPLE: -e png.")

    parser.add_option("-s","--scales",dest="scales",default='1,1,1',\
    help="Factor by which every image must be multiplied prior to combination, in RGB order. Default is 1 for every band. EXAMPLE: -s '1,1,1'.")

    parser.add_option("-z","--zrange",dest="zrange",\
    default='0,1',help="Zrange to apply to images prior to combination. Default is (0,1). EXAMPLE: -z '0,1'.")

    parser.add_option("-l","--log",dest="doLog",\
    default='False', help = "Apply logarithmic scaling to images. Default is False. EXAMPLE: -l True.")

    parser.add_option("-b","--background",dest="backRGB",\
    default='0,0,0',help="'Paint' zones valued as zero in all 3 images in a color given as an RGB 3-value. Default is to leave blank zones in black. EXAMPLE: -b '255,0,0' [Red like Hell].")

    (options, args) = parser.parse_args()

    if options.images:
        R, G, B = string.split(string.replace(options.images,',',' '),' ')
    else :
        sys.exit('\nNo input images... no output image!\n')

    if options.outimage:
       outimage = options.outimage
    else:
        print '\nOutput image will be named "%s" \n' % outimage

    if options.extension:
        extension = options.extension
    else :
        print '\nOutput image will have "%s" extension\n' % extension

    if options.scales:
        scales_str = string.split(string.replace(options.scales,',',' '),' ')
        sl = [float(item) for item in scales_str]
        scales = {'R':sl[0],'G':sl[1],'B':sl[2]}
    else :
        print '\nInput images will not be rescaled\n'

    if options.zrange:
       zrange_str = string.split(string.replace(options.zrange,',',' '),' ')
       zrange = tuple([float(item) for item in zrange_str])
    else:
        print '\nZrange will be (0,1)\n'

    if options.doLog:
       doLog = string.lower(options.doLog) == 'true'
    else :
        print '\nLinear scaling\n'

    if options.backRGB:
        doBack = True
        backRGB_str = string.split(string.replace(options.backRGB,',',' '),' ')
        bt = tuple([int(item) for item in backRGB_str])
        backRGB = {'R':bt[0],'G':bt[1],'B':bt[2]}
    else:
        print '\nBlank zones will appear in Black.\n'


    combineRGB(R,G,B,outimage,extension,scales,zrange,doLog,doBack,backRGB)
 

Section: HOWTOs

edit · print · PDF
Page last modified on April 07, 2008, at 10:02 PM