Morph-M Python - Basic Operator

This following example show you, by 8 bits image Inversion, how you can create and call your operator.

#Don't forget morphee importation
import morphee

# pixel's inversion Operator (8 bits version) :
def invert8(val):
    return 255-val

# image inversion function:
def testInvert8(im):
    morphee.ImUnaryOperation(im,invert8,im)

# lambda version :
def testInvert8_lambda(im):
    # instead of invert8, we can use a lambda-fonction  
    # Better and lighter
    morphee.ImUnaryOperation(im, lambda x:255-x,im)

im8=morphee.fileRead(os.path.join(images_dir_gray,"foreman.png"))
testInvert8(im8)
morphee.fileWrite(im8,os.path.join(temp_dir,"invert8.png"))
testInvert8_lambda(im8)
morphee.fileWrite(im8,os.path.join(temp_dir,"foreman.png"))

An other example: Color conversion (RGB to Gray) :

#Don't forget morphee importation
import morphee

def RGBtoGray(valRGB):
    # valRGB est normalement un pixel_3<UINT8> converti
    # en un 3-tuple.
    assert(type(valRGB)==type((),))# Check type (we need tuple)
    assert(len(valRGB)==3)# Check if it is 3-tuple

    # Hmm, beautiful conversion !
    return (valRGB[0]+valRGB[1]+valRGB[2])/3

def testRGBtoGray(imRGB,imGray):
    morphee.ImUnaryOperation(imRGB,RGBtoGray,imGray)

imRGB=morphee.fileRead(os.path.join(images_dir_color,"ours1.bmp"))
imRGB_Gray=morphee.getSameOf(imRGB,morphee.dataCategory.dtScalar,morphee.scalarDataType.sdtUINT8)
testRGBtoGray(imRGB,imRGB_Gray)
morphee.fileWrite(imRGB_Gray,os.path.join(temp_dir,"rgbtogray.png"))

This example show you an method to construct an operator by using class

#Don't forget morphee importation
import morphee

#Add a constant
class AddNum:
    def __init__(self, n):
        self.number=n
    def __call__(self, val):
        if val+self.number > 255:
            return 255
        else:
            return val+self.number

def testAddCte(im, k):
    op=AddNum(100)
    # The __call__() function is simply used to
        #call on a callable object like the callback() 
        #function outside the class
    morphee.ImUnaryOperation(im,op, im)

im8=morphee.pngFileRead(os.path.join(images_dir_gray,"foreman.png"))
testAddCte(im8,100)
morphee.fileWrite(im8,os.path.join(temp_dir,"add100.png"))

You can create Binary Operator

#Don't forget morphee importation
from morphee import *

im = morphee.createImage( dataCategory.dtScalar,scalarDataType.sdtUINT32 )
im.setSize(3,3)
im.allocateImage()
imOut=morphee.getSame(self.im)
L=[ 1,2,3,4,5,6,7,8,9]
im.fromList(L)

im2 = getSame(im)
ImCopy(im,im2)    

im3 = getSame(im)

#Lambda function with our operator which add 2 images 
ImBinaryOperation(self.im,self.im2, lambda x,y:x+y, self.im3)

#test result
for p1,p3 in zip(self.im.imageData(),self.im3.imageData()):
            self.assertEqual(p3,2*p1)