OpenCVとPythonと私 vol.3

#!/usr/bin/python

import cv
from opencv import highgui
import sys
import getopt

filename = None
debug = False

def main () :

        global filename
        global debug

        try :
                opts, args = getopt.getopt( sys.argv[1:], "hd", ["help","debug"] )
        except getopt.GetoptError, err :
                print str( err )
                usage()
                sys.exit(2)

        if len( args ) != 0 :
                filename = args[0]
        else :
                usage()
                sys.exit(0)

        for o, a in opts :
   
                if o in ( "-h", "--help" ) :
                        usage()
                        sys.exit(0)
                elif o in ( "-d", "--debug" ) :
                        debug = True
                else :
                        assert False, "unhandled option"

def debugout ( str ) :
        if debug == True :
                print str

def usage() :
        print "Usage: showImage.py [OPTION] FILE"
        print " "
        print " -h, --help   Display this message."
        print " -d, --debug  Output debug log."

if __name__ == "__main__" :

        main()
        debugout( "Input file name is " + filename )

        before = cv.LoadImage( filename )

        debugout( "width : " + str( before.width  ) )
        debugout( "height: " + str( before.height ) )

        if before.width % 2 != 0 or before.height % 2 != 0 :
                assert False, "input file cannot do with PyrDown"

        cv.NamedWindow( "Before", 1 )
        cv.MoveWindow( "Before", 100, 100 )

        cv.NamedWindow( "After", 1 )
        cv.MoveWindow( "After", 100+before.width, 100 )

        size = ( before.width/2, before.height/2 )
        after = cv.CreateImage( size , \
                                before.depth, before.nChannels )

        cv.PyrDown( before, after )
        cv.ShowImage( "Before", before )
        cv.ShowImage( "After" , after  )

        print "Hit any key."
        cv.WaitKey(0)
        cv.DestroyWindow( "Before" )
        cv.DestroyWindow( "After" )