Salome HOME
typo-fix by Kunda
[modules/med.git] / doc / tut / medcoupling / testpil.py
1 #!/usr/bin/env pytho
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2011-2016  CEA/DEN, EDF R&D
4 #
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License, or (at your option) any later version.
9 #
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18 #
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21
22 # This script illustrates how to create a matrix of pixels from data
23 # read in an image file. At the end, the cells of the matrix
24 # corresponds to the cells of a cartesian mesh that could hold a field
25 # whose value is the value of the pixel.
26 # (gboulant - 13/11/2011)
27
28 from PIL import Image
29 from PIL import ImageOps
30 import numpy
31
32 def image2matrix():
33     # Load the image
34     #img=Image.open("images/avatar.png")
35     img=Image.open("images/tests.pgm")
36     
37     # Get a grayscale version
38     imgbw=ImageOps.grayscale(img)
39     
40     # Save the image (optional)
41     imgbw.save(fp="testsbw.pgm")
42     
43     # Get the data
44     imgdata=imgbw.getdata()
45     width,height=imgbw.size
46     print list(imgdata)
47     print width,height
48
49     # Convert the data in a matrix using numpy
50     tab=numpy.array(imgdata,dtype='float64')
51     print list(tab)
52     print tab
53     nbRows=height
54     nbCols=width
55     matrix=numpy.reshape(tab,(nbRows,nbCols))
56     # Note that in the reshape function, the height (sizeY) of the image
57     # is specified first, because it corresponds to the number of rows.
58     print matrix
59     print list(matrix)
60
61 import MEDCoupling as MC
62 import MEDLoader as ML
63 def createMesh(meshname, sizeX, sizeY):
64     """
65     Creating a cartesian mesh with a grid of the size of the image.
66     sizeX and sizeY should be respectively the width and height of the
67     image.
68     """
69     # >>>
70     # WARNING: remember the problem of tics and spaces. The data values
71     # are considered as values defined on cells. With size values in a
72     # direction, we have to create size+1 mesh nodes in that direction.
73     # <<<
74     
75     # The mesh is created using MEDCoupling
76     cmesh=MC.MEDCouplingCMesh.New();
77     cmesh.setName(meshname)
78     
79     # We use an arbitrary step between cells (the value does not matter)
80     stepX = 0.1
81     nbNodesX = sizeX+1
82     arrX = [float(i * stepX) for i in range(nbNodesX)]
83     coordsX=MC.DataArrayDouble.New()
84     coordsX.setValues(arrX,nbNodesX,1)
85
86     # For the Y dimension, we have to reverse the coordinates (the
87     # first pixel is at y=height and not at y=0).
88     stepY = 0.1
89     nbNodesY = sizeY+1
90     lengthY = sizeY*stepY
91     arrY=[float(lengthY - i * stepY) for i in range(nbNodesY)]
92     coordsY=MC.DataArrayDouble.New()
93     coordsY.setValues(arrY,nbNodesY,1)
94     
95     cmesh.setCoords(coordsX,coordsY)
96     print "Imagem mesh dimension: %d"%cmesh.getSpaceDimension()
97     
98     # WARN: In the current state of development of MEDLoader, only
99     # unstructured meshes are supported for writing function in med
100     # files. We just have to convert the cartesian mesh in an unstructured
101     # mesh before creating the field.
102     umesh=cmesh.buildUnstructured();
103     umesh.setName("imagemesh")
104     
105     return umesh
106
107 def createField(fieldname, mesh, image):
108     """
109     Creating a scalar field on the mesh using image data
110     """    
111     # Create the field using MEDCoupling
112     field = MC.MEDCouplingFieldDouble.New(MC.ON_CELLS,MC.ONE_TIME);
113     field.setName(fieldname);
114     field.setMesh(mesh);
115     # OPTIONAL: We set an arbitrary time step for test purpose
116     field.setIteration(0);
117     field.setOrder(0)
118
119     imagedata=list(image.getdata())
120     width,height=image.size
121     nbCells = width*height
122     dataArray=MC.DataArrayDouble.New();
123     nbComponents=1 # For a scalar field
124     
125     dataArray.setValues(imagedata,nbCells,nbComponents)
126     field.setArray(dataArray);
127     
128     return field
129
130 def image2med():
131     img=Image.open("images/avatar.png")
132     #img=Image.open("images/irm.png")
133     imgbw=ImageOps.grayscale(img)
134     # We keep only the grayscale. Maybe, it could be useful to get
135     # the RGB scales each on one component of the field.
136     
137     width,height=imgbw.size
138     mesh=createMesh("mesh",width,height)
139     field=createField("field",mesh,imgbw)
140     
141     createFromScratch=True
142     ML.MEDLoader.WriteField("image.med",field,createFromScratch)
143
144
145 # ===================================================================
146     
147 if __name__ == "__main__":
148     #image2matrix()
149     image2med()