Morph-M Python - Basic Operator » History » Version 2
Serge Koudoro, 10/26/2009 11:29 AM
1 | 1 | Serge Koudoro | h1. Morph-M Python - Basic Operator |
---|---|---|---|
2 | |||
3 | This following example show you, by 8 bits image Inversion, how you can create and call your operator. |
||
4 | |||
5 | <pre><code class="ruby"> |
||
6 | 2 | Serge Koudoro | #Don't forget morphee importation |
7 | import morphee |
||
8 | |||
9 | 1 | Serge Koudoro | # pixel's inversion Operator (8 bits version) : |
10 | def invert8(val): |
||
11 | return 255-val |
||
12 | |||
13 | # image inversion function: |
||
14 | def testInvert8(im): |
||
15 | morphee.ImUnaryOperation(im,invert8,im) |
||
16 | |||
17 | # lambda version : |
||
18 | def testInvert8_lambda(im): |
||
19 | # instead of invert8, we can use a lambda-fonction |
||
20 | # Better and lighter |
||
21 | morphee.ImUnaryOperation(im, lambda x:255-x,im) |
||
22 | </code></pre> |
||
23 | |||
24 | An other example: Color conversion (RGB to Gray) : |
||
25 | |||
26 | <pre><code class="ruby"> |
||
27 | 2 | Serge Koudoro | #Don't forget morphee importation |
28 | import morphee |
||
29 | |||
30 | 1 | Serge Koudoro | def RGBtoGray(valRGB): |
31 | # valRGB est normalement un pixel_3<UINT8> converti |
||
32 | # en un 3-tuple. |
||
33 | assert(type(valRGB)==type((),))# Check type (we need tuple) |
||
34 | assert(len(valRGB)==3)# Check if it is 3-tuple |
||
35 | |||
36 | # Hmm, beautiful conversion ! |
||
37 | return (valRGB[0]+valRGB[1]+valRGB[2])/3 |
||
38 | |||
39 | def testRGBtoGray(imRGB,imGray): |
||
40 | morphee.ImUnaryOperation(imRGB,RGBtoGray,imGray) |
||
41 | </code></pre> |
||
42 | |||
43 | This example show you an method to construct an operator by using class |
||
44 | |||
45 | <pre><code class="ruby"> |
||
46 | 2 | Serge Koudoro | #Don't forget morphee importation |
47 | import morphee |
||
48 | |||
49 | 1 | Serge Koudoro | #Add a constant |
50 | class AddNum: |
||
51 | def __init__(self, n): |
||
52 | self.number=n |
||
53 | def __call__(self, val): |
||
54 | if val+self.number > 255: |
||
55 | return 255 |
||
56 | else: |
||
57 | return val+self.number |
||
58 | |||
59 | def testAddCte(im, k): |
||
60 | op=AddNum(100) |
||
61 | # The __call__() function is simply used to |
||
62 | #call on a callable object like the callback() |
||
63 | #function outside the class |
||
64 | morphee.ImUnaryOperation(im,op, im) |
||
65 | </code></pre> |