OpenCVとPythonと私 vol.6

#!/usr/bin/python

import cv, numpy
from opencv import highgui

import sys
import getopt

filename = None
debug    = False
rows     = 0
columns  = 0
span     = 0
sourceFile = None
destinationFile = 'result.png'

def main () :

        global filename
        global debug
        global rows
        global columns
        global span
        global sourceFile
        global destinationFile

        try:
                opts, args = getopt.getopt( sys.argv[1:], "hdr:c:s:u:o:",["help","debug","rows","columns","span","undistort","output"])
        except getopt.GetoptError, err :
                print str( err )
                usage()
                sys.exit(2)

        if len( args ) != 0 :
                filename = args[:]
        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
                elif o in ( "-r", "--rows" ) :
                        rows = int( a )
                elif o in ( "-c", "--columns" ) :
                        columns = int( a )
                elif o in ( "-s", "--span" ) :
                        span = int( a )
                elif o in ( "-u", "--undistort" ) :
                        sourceFile = a
                elif o in ( "-o", "--output" ) :
                        destinationFile = a
                else :
                        assert False, "unhandled option"

def debugout ( str ) :
        if debug == True :
                print str
   
def usage () :
        print "Usage: undistortTest.py [OPTION] FILE"
        print " "
        print " -h, --help      Display this message."
        print " -d, --debug     Output debug log."
        print " -r, --rows      Row counts of chessboard's corners"
        print " -c, --columns   Column counts of chessboard's corners"
        print " -s, --span      Length of between 2 corners"
        print " -u, --undistort Specify distorted image."
        print " -o, --output    Set undistorted output file name."
       
if __name__ == "__main__" :

        main()

        objectPointsList =
        imagePointsList =


        for element in filename :
                '''
                debugout( "Input file name is " + element )
                '''
                img = cv.LoadImage( element , cv.CV_LOAD_IMAGE_GRAYSCALE )
                corners = cv.FindChessboardCorners( img, ( columns, rows ) )

                for corner in corners[1] :
                        imagePointsList.append( list( corner ) )

                ytmp = range( columns )
                ytmp.reverse()
                for x in range( rows ) :
                        for y in ytmp :
                                objectPoint = []
                                objectPoint.append( x * span )
                                objectPoint.append( y * span )
                                objectPoint.append( 0 )
                                objectPointsList.append( objectPoint )
                                del objectPoint

        imagePointsArray = numpy.array( imagePointsList, 'float' )
        imagePoints = cv.fromarray( imagePointsArray )

        objectPointsArray = numpy.array( objectPointsList, 'float' )
        objectPoints = cv.fromarray( objectPointsArray )

        cameraMatrix = cv.CreateMat( 3, 3, cv.CV_32FC1 )
        distortionCoeffs = cv.CreateMat( 1, 4, cv.CV_32FC1 )
        rotationVector = cv.CreateMat( len( filename ), 3, cv.CV_32FC1 )
        translationVector = cv.CreateMat( len( filename ), 3, cv.CV_32FC1 )

        pointCountsArray = rows * columns * numpy.ones( ( len( filename ), 1 ) ,'int32')
        pointCounts = cv.fromarray( pointCountsArray )

        try:
                cv.CalibrateCamera2( objectPoints, imagePoints, \
                                             pointCounts ,\
                                             ( img.height, img.width ) ,\
                                             cameraMatrix, distortionCoeffs,\
                                             rotationVector, translationVector, 0 )
        except cv.error, err :
                print str( err )
                sys.exit(2)

        distortedImage = cv.LoadImageM( sourceFile )
        undistortedImage = cv.LoadImageM( sourceFile )

        cv.Undistort2( distortedImage, undistortedImage, cameraMatrix, distortionCoeffs )

        cv.NamedWindow( "Before", cv.CV_WINDOW_AUTOSIZE )
        cv.NamedWindow( "After", cv.CV_WINDOW_AUTOSIZE )
        cv.MoveWindow( "Before", 100, 100)
        cv.MoveWindow( "After", 100, 200 )

        cv.ShowImage( "Before", distortedImage )
        cv.ShowImage( "After", undistortedImage )

        cv.SaveImage( destinationFile, undistortedImage )

        print "Hit any key."
        cv.WaitKey( 0 )

        cv.DestroyWindow( "Before" )
        cv.DestroyWindow( "After" )

OpenCV いろいろ確認

別にビルドしたいわけではないんだけどちょっと確認

↓このURLに当たれば大体いいでしょう。

http://opencv.willowgarage.com/wiki/InstallGuide%20%3A%20Debian

apt-get install build-essential
apt-get install cmake
apt-get install pkg-config
apt-get install libpng12-0 libpng12-dev libpng++-dev libpng3
apt-get install libpnglite-dev libpngwriter0-dev libpngwriter0c2
apt-get install zlib1g-dbg zlib1g zlib1g-dev
apt-get install libjasper-dev libjasper-runtime libjasper1
apt-get install pngtools libtiff4-dev libtiff4 libtiffxx0c2 libtiff-tools
apt-get install libjpeg8 libjpeg8-dev libjpeg8-dbg libjpeg-prog
apt-get install ffmpeg libavcodec-dev libavcodec52 libavformat52 libavformat-dev
apt-get install libgstreamer0.10-0-dbg libgstreamer0.10-0  libgstreamer0.10-dev
apt-get install libxine1-ffmpeg  libxine-dev libxine1-bin
apt-get install libunicap2 libunicap2-dev
apt-get install libdc1394-22-dev libdc1394-22 libdc1394-utils
apt-get install swig
apt-get install libv4l-0 libv4l-dev
apt-get install python-numpy

以下、自分の環境の確認

インストール済み

build-essential pkg-config libpng12-0 libpng12-dev zlib1g zlib1g-dev libjasper1 libtiff4 libjpeg8 libavcodec-dev libavformat-dev
libgstreamer0.10-0  libdc1394-22 python-numpy swig libv4l-0

バージョン違いだけどインストールされてる

libavcodec52 ->  libavcodec53
libavformat52 -> libavformat53

インストールされてない

cmake libpng++-dev libpng3 libpnglite-dev zlib1g-dbg libjasper-dev libjasper-runtime pngtools libtiff4-dev libtiffxx0c2 libtiff-tools libjpeg8-dev libjpeg8-dbg libjpeg-prog ffmpeg libgstreamer0.10-dev libgstreamer0.10-0-dbg libxine1-ffmpeg libxine-dev libxine1-bin libunicap2 libunicap2-dev libdc1394-22-dev libdc1394-utils libv4l-dev

Ubuntu 11.10にはこのパッケージは見つからなかった

libpngwriter0-dev libpngwriter0c2

OpenCVとPythonと私 vol.5

#!/usr/bin/python

import cv, numpy
from opencv import highgui

import sys
import getopt

filename = None
debug    = False
rows     = 0
columns  = 0
span     = 0

def main () :

        global filename
        global debug
        global rows
        global columns
        global span

        try:
                opts, args = getopt.getopt( sys.argv[1:], "hdr:c:s:",["help","debug","rows","columns","span"])
        except getopt.GetoptError, err :
                print str( err )
                usage()
                sys.exit(2)

        if len( args ) != 0 :
                filename = args[:]
        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
                elif o in ( "-r", "--rows" ) :
                        rows = int( a )
                elif o in ( "-c", "--columns" ) :
                        columns = int( a )
                elif o in ( "-s", "--span" ) :
                        span = int( a )
                else :
                        assert False, "unhandled option"

def debugout ( str ) :
        if debug == True :
                print str
    
def usage () :
        print "Usage: calibrateCamera.py [OPTION] FILE"
        print " "
        print " -h, --help    Display this message."
        print " -d, --debug   Output debug log."
        print " -r, --rows    Row counts of chessboard's corners"
        print " -c, --columns Column counts of chessboard's corners"
        print " -s, --span    Length of between 2 corners"

if __name__ == "__main__" :

        main()

        objectPointsList =
        imagePointsList =


        for element in filename :

                debugout( "Input file name is " + element )
                
                img = cv.LoadImage( element , cv.CV_LOAD_IMAGE_GRAYSCALE )
                corners = cv.FindChessboardCorners( img, ( columns, rows ) )

                for corner in corners[1] :
                        imagePointsList.append( list( corner ) )
                        tmp = list( corner )
                        debugout( "x_1 = " + str( tmp[0] ) + " / x_2 = " + str( tmp[1] ) )
                        del tmp

                ytmp = range( columns )
                ytmp.reverse()
                for x in range( rows ) :
                        for y in ytmp :
                                objectPoint = []
                                objectPoint.append( x * span )
                                objectPoint.append( y * span )
                                objectPoint.append( 0 )
                                debugout( "X_1 = " + str( x * span ) + " / X_2 = " + str( y * span ) )
                                objectPointsList.append( objectPoint )
                                del objectPoint

        imagePointsArray = numpy.array( imagePointsList, 'float' )
        imagePoints = cv.fromarray( imagePointsArray )
        debugout( "imagepoints: <size : " + str( cv.GetDims(imagePoints) ) + " >\n" + \
                          "              <channels : " + str( cv.CV_MAT_CN(cv.GetElemType(imagePoints) ) ) + " >" )

        objectPointsArray = numpy.array( objectPointsList, 'float' )
        objectPoints = cv.fromarray( objectPointsArray )
        debugout( "objectpoints: <size : " + str( cv.GetDims(objectPoints) ) + " >\n" + \
                          "              <channels : " + str( cv.CV_MAT_CN(cv.GetElemType(objectPoints) ) ) + " >" )

        cameraMatrix = cv.CreateMat( 3, 3, cv.CV_32FC1 )
        distortionCoeffs = cv.CreateMat( 1, 4, cv.CV_32FC1 )
        rotationVector = cv.CreateMat( len( filename ), 3, cv.CV_32FC1 )
        translationVector = cv.CreateMat( len( filename ), 3, cv.CV_32FC1 )

        pointCountsArray = rows * columns * numpy.ones( ( len( filename ), 1 ) ,'int32')
        pointCounts = cv.fromarray( pointCountsArray )

        debugout( "pointcounts: <size : " + str( cv.GetDims(pointCounts) ) + " >\n" + \
                          "              <channels : " + str( cv.CV_MAT_CN(cv.GetElemType(pointCounts) ) ) + " >" )
        try:
                cv.CalibrateCamera2( objectPoints, imagePoints, \
                                             pointCounts ,\
                                             ( img.height, img.width ) ,\
                                             cameraMatrix, distortionCoeffs,\
                                             rotationVector, translationVector, 0 )
        except cv.error, err :
                print str( err )
                sys.exit(2)

        print "CameraMatrix :"
        print [ cameraMatrix[0,i] for i in range(3) ]
        print [ cameraMatrix[1,i] for i in range(3) ]
        print [ cameraMatrix[2,i] for i in range(3) ]
        print "\n"

        print "Distortion Coeffecients:"
        print [ distortionCoeffs[0,i] for i in range(4) ]
        print "\n"

        print "Rotation Vector:"
        print [ rotationVector[0,i] for i in range(3) ]
        print "\n"

        print "Translation Vector:"
        print [ translationVector[0,i] for i in range(3) ]
        print "\n"

OpenCVとPythonと私 vol.4

実験用のチェスボードは

http://blog.livedoor.jp/hen_cyberne/archives/2010-08.html

こちらの勉強されている方のを使わせていただきました。

で、FindChessboardCornersとDrawChessboardCornersを使ってみました。簡単ですね、OpenCV

 

#!/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: detectChessboard.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 )
    
        img    = cv.LoadImage( filename , cv.CV_LOAD_IMAGE_GRAYSCALE )
        output = cv.LoadImage( filename )        

        crnrs = cv.FindChessboardCorners( img, (6,8) )
        
        cv.DrawChessboardCorners( output, (6,8), crnrs[1], crnrs[0] )

        cv.NamedWindow( "result", cv.CV_WINDOW_AUTOSIZE )
        cv.MoveWindow( "result", 100, 100)
        cv.ShowImage( "result", output )

        cv.SaveImage( "result.png", output )

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

 

OpenCVとPythonと私 appendix A

#!/usr/bin/python

import cv
from opencv import highgui
import sys
import getopt

inputName  = None
outputName = None
debug = False

def main () :

        global inputName 
        global outputName
        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 :
               
                debugout( "Argument 0 :" + args[0] )
                debugout( "Argument 0 :" + args[1] )

                outputName = args[0]
                inputName  = args[1]

        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  : " + inputName  )
        debugout( "Output file name is : " + outputName )

        before = cv.LoadImageM( inputName , cv.CV_LOAD_IMAGE_GRAYSCALE )

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

        cv.SaveImage( outputName , before )

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

OpenCVとPythonと私 vol.2

#!/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.LoadImageM( filename )

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

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

        after = cv.CreateImage( cv.GetSize( before ), cv.IPL_DEPTH_8U, 3 )
        cv.Smooth( before, after, cv.CV_GAUSSIAN , 3 , 3 )

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

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