Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extGeoreferencing / src / org / gvsig / georeferencing / process / GeoreferencingProcess.java @ 20005

History | View | Annotate | Download (13.2 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
         *
3
         * Copyright (C) 2006 Instituto de Desarrollo Regional and Generalitat Valenciana.
4
         *
5
         * This program is free software; you can redistribute it and/or
6
         * modify it under the terms of the GNU General Public License
7
         * as published by the Free Software Foundation; either version 2
8
         * of the License, or (at your option) any later version.
9
         *
10
         * This program 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
13
         * GNU General Public License for more details.
14
         *
15
         * You should have received a copy of the GNU General Public License
16
         * along with this program; if not, write to the Free Software
17
         * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
         *
19
         * For more information, contact:
20
         *
21
         *  Generalitat Valenciana
22
         *   Conselleria d'Infraestructures i Transport
23
         *   Av. Blasco Iba?ez, 50
24
         *   46010 VALENCIA
25
         *   SPAIN
26
         *
27
         *      +34 963862235
28
         *   gvsig@gva.es
29
         *      www.gvsig.gva.es
30
         *
31
         *    or
32
         *
33
         *   Instituto de Desarrollo Regional (Universidad de Castilla La-Mancha)
34
         *   Campus Universitario s/n
35
         *   02071 Alabacete
36
         *   Spain
37
         *
38
         *   +34 967 599 200
39
         */
40

    
41
package org.gvsig.georeferencing.process;
42

    
43
import java.awt.geom.AffineTransform;
44
import java.io.IOException;
45

    
46
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
47
import org.gvsig.georeferencing.process.geotransform.GeoTransformDataResult;
48
import org.gvsig.georeferencing.process.geotransform.GeoTransformProcess;
49
import org.gvsig.raster.IProcessActions;
50
import org.gvsig.raster.RasterProcess;
51
import org.gvsig.raster.buffer.BufferFactory;
52
import org.gvsig.raster.buffer.RasterBuffer;
53
import org.gvsig.raster.buffer.RasterBufferInvalidAccessException;
54
import org.gvsig.raster.buffer.RasterBufferInvalidException;
55
import org.gvsig.raster.buffer.WriterBufferServer;
56
import org.gvsig.raster.dataset.GeoRasterWriter;
57
import org.gvsig.raster.dataset.IBuffer;
58
import org.gvsig.raster.dataset.IRasterDataSource;
59
import org.gvsig.raster.dataset.NotSupportedExtensionException;
60
import org.gvsig.raster.dataset.io.RasterDriverException;
61
import org.gvsig.raster.datastruct.GeoPoint;
62
import org.gvsig.raster.grid.Grid;
63
import org.gvsig.raster.grid.GridExtent;
64
import org.gvsig.raster.grid.GridInterpolated;
65
import org.gvsig.raster.grid.OutOfGridException;
66
import org.gvsig.raster.util.RasterToolsUtil;
67

    
68
import com.iver.andami.PluginServices;
69

    
70
/**
71
 *  Clase que representa una proceso de georreferenciacion de un raster.
72
 *  
73
 *  @author Alejandro Mu?oz Sanchez (alejandro.munoz@uclm.es)
74
 *         @version 10/2/2008
75
 **/
76
public class GeoreferencingProcess extends RasterProcess implements IProcessActions{
77
        
78
        //Capa a georreferenciar
79
        private FLyrRasterSE             rasterSE                        = null;
80
        
81
        //Grid resultante de georreferenciacion
82
        private Grid                     imageGrid          = null;
83
        
84
        //Fichero de salida
85
        private String                   filename           = null;
86
        
87
        // resutado de la transformacion 
88
        private GeoTransformDataResult   transformData      = null;
89
        
90
        // Lista puntos de control
91
        private GeoPoint                 gpcs[]             = null;
92
        
93
        //Extend de imagen corregida
94
        GridExtent                       newExtend          = null;
95
        
96
        // Metodo de resampleado utilizado
97
        private int                      rMethod            = 0;
98
        
99
        //Indicador de progreso
100
        private int                      percent            = 0;
101
        
102
        // Grid resultado
103
        private Grid                     gridResult         = null;
104
        
105
        WriterBufferServer               writerBufferServer = null;
106

    
107
        private int                      orden              = 0;
108
        
109
        private int[]                    bands              = null;
110
        
111
        //Tama?o de celda en X si es pasada por el usuario
112
        private double                   xCellSize           = 0;
113
        //Tama?o de celda en Y si es pasada por el usuario
114
        private double                   yCellSize           = 0;
115
        
116
        /** Metodo que recoge los parametros del proceso georreferenciacion de un raster
117
        * <LI>rasterSE: capa a georeferenciar</LI>
118
        * <LI>filename: path con el fichero de salida</LI>
119
        * <LI>method: metodo de resampleo </LI>
120
        */
121
        public void init() {
122
                
123
                rasterSE = (FLyrRasterSE)getParam("fLayer");
124
                filename = (String)getParam("filename");
125
                rMethod = (int)getIntParam("method");
126
                gpcs = (GeoPoint[])getParam("gpcs");
127
                orden= (int)getIntParam("orden");
128
                bands = new int[rasterSE.getBandCount()];
129
                xCellSize = (double)getDoubleParam("xCellSize");
130
                yCellSize = (double)getDoubleParam("yCellSize");
131
                
132
                for(int i=0; i<rasterSE.getBandCount(); i++)
133
                        bands[i]= i;
134
                // Inicializacion del grid correspondiente a la imagen a corregir
135
                IRasterDataSource dsetCopy = null; 
136
                dsetCopy = rasterSE.getDataSource().newDataset();
137
                BufferFactory bufferFactory = new BufferFactory(dsetCopy);
138
                if (!RasterBuffer.loadInMemory(dsetCopy))
139
                        bufferFactory.setReadOnly(true);        
140
                try {
141
                                imageGrid = new Grid(bufferFactory);        
142
                }catch (RasterBufferInvalidException e) {
143
                        e.printStackTrace();                        
144
                }
145
        }
146
        
147

    
148
        public void process() throws InterruptedException {
149
                
150
                GeoTransformProcess transform = new GeoTransformProcess();
151
                transform.setActions(this);
152
                transform.addParam("gpcs",gpcs);
153
                transform.addParam("orden",new Integer(orden));
154
                transform.run();                
155
                
156
                // Obtenida la transformacion la aplicamos a los puntos extremos de la imagen
157
                double p1[]=transformData.getCoordMap(0,0);                
158
                double p2[]=transformData.getCoordMap(0,imageGrid.getNY());
159
                double p3[]=transformData.getCoordMap(imageGrid.getNX(),0);                
160
                double p4[]=transformData.getCoordMap(imageGrid.getNX(),imageGrid.getNY());        
161
                                
162
                
163
                double xmin=Math.min( Math.min(p1[0],p2[0]),Math.min(p3[0],p4[0]));
164
                double ymin=Math.min( Math.min(p1[1],p2[1]),Math.min(p3[1],p4[1]));
165
                double xmax=Math.max( Math.max(p1[0],p2[0]),Math.max(p3[0],p4[0]));        
166
                double ymax=Math.max( Math.max(p1[1],p2[1]),Math.max(p3[1],p4[1]));
167
                
168
                
169
                // OJO CON EL TAMA?O DE CELDA: CONSULTAR PARA EJEMPLO DE JOSE ES 25
170
                if(xCellSize <= 1)
171
                        xCellSize = (xmax - xmin) / (double)rasterSE.getPxWidth();
172
                if(yCellSize <= 1)
173
                        yCellSize = (ymax - ymin) / (double)rasterSE.getPxHeight();
174
                        
175
                newExtend= new GridExtent(xmin, ymin, xmax, ymax, xCellSize);
176
                int datatype= rasterSE.getBufferFactory().getRasterBuf().getDataType();
177
                
178
                try {
179
                        gridResult = new Grid(newExtend, newExtend, datatype, bands);
180
                } catch (RasterBufferInvalidException e) {
181
                        RasterToolsUtil.messageBoxError("error_grid", this, e);
182
                }
183
                
184
                double minPointX=gridResult.getGridExtent().getMin().getX();
185
                double maxPointY=gridResult.getGridExtent().getMax().getY();
186
                double cellsize=gridResult.getCellSize();
187
        
188
                
189
                GridInterpolated gridInterpolated=null;
190
                gridInterpolated = new GridInterpolated((RasterBuffer)imageGrid.getRasterBuf(),imageGrid.getGridExtent(),imageGrid.getGridExtent(),bands);
191
                
192
                // SE ESTABLECE EL METODO DE INTERPOLACION (por defecto vecino mas proximo)
193
                if(rMethod==GridInterpolated.INTERPOLATION_BicubicSpline)
194
                        gridInterpolated.setInterpolationMethod(GridInterpolated.INTERPOLATION_BicubicSpline);
195
                else if(rMethod==GridInterpolated.INTERPOLATION_Bilinear)
196
                        gridInterpolated.setInterpolationMethod(GridInterpolated.INTERPOLATION_Bilinear);
197
                else
198
                        gridInterpolated.setInterpolationMethod(GridInterpolated.INTERPOLATION_NearestNeighbour);
199
                
200
                double coord[]=null;
201
                try {
202
                
203
                        if(datatype==IBuffer.TYPE_BYTE)
204
                        {
205
                                byte values[]=new byte[bands.length];
206
                                int progress=0;
207
                                // OPTIMIZACION. Se esta recorriendo secuencialmente cada banda.
208
                                for(int band=0; band<bands.length;band++){
209
                                        gridResult.setBandToOperate(band);
210
                                        gridInterpolated.setBandToOperate(band);
211
                                        for(int row=0; row<gridResult.getLayerNY(); row++){
212
                                                progress++;
213
                                                for(int col=0; col<gridResult.getLayerNX();col++)
214
                                                        {
215
                                                                coord=transform.getCoordPixel(col*cellsize+minPointX, maxPointY-row*cellsize);        
216
                                                                values[band] = (byte)gridInterpolated._getValueAt(coord[0],coord[1]);
217
                                                                gridResult.setCellValue(col,row,(byte)values[band]);
218
                                                        }
219
                                                percent=(int)( progress*100/(gridResult.getLayerNY()*bands.length));        
220
                                        }        
221
                                }        
222
                        }
223
                        
224
                        if(datatype==IBuffer.TYPE_SHORT)
225
                        {
226
                                short values[]=new short[bands.length];
227
                                int progress=0;
228
                                // OPTIMIZACION. Se esta recorriendo secuencialmente cada banda.
229
                                for(int band=0; band<bands.length;band++){
230
                                        gridResult.setBandToOperate(band);
231
                                        gridInterpolated.setBandToOperate(band);
232
                                        for(int row=0; row<gridResult.getLayerNY(); row++){
233
                                                progress++;
234
                                                for(int col=0; col<gridResult.getLayerNX();col++)
235
                                                        {
236
                                                                coord=transform.getCoordPixel(col*cellsize+minPointX, maxPointY-row*cellsize);        
237
                                                                values[band] = (short)gridInterpolated._getValueAt(coord[0],coord[1]);
238
                                                                gridResult.setCellValue(col,row,(short)values[band]);
239
                                                        }
240
                                                percent=(int)( progress*100/(gridResult.getLayerNY()*bands.length));        
241
                                        }        
242
                                }        
243
                        }
244
                        
245
                        if(datatype==IBuffer.TYPE_INT)
246
                        {
247
                                int values[]=new int[bands.length];
248
                                int progress=0;
249
                                // OPTIMIZACION. Se esta recorriendo secuencialmente cada banda.
250
                                for(int band=0; band<bands.length;band++){
251
                                        gridResult.setBandToOperate(band);
252
                                        gridInterpolated.setBandToOperate(band);
253
                                        for(int row=0; row<gridResult.getLayerNY(); row++){
254
                                                progress++;
255
                                                for(int col=0; col<gridResult.getLayerNX();col++)
256
                                                        {
257
                                                                coord=transform.getCoordPixel(col*cellsize+minPointX, maxPointY-row*cellsize);        
258
                                                                values[band] = (int)gridInterpolated._getValueAt(coord[0],coord[1]);
259
                                                                gridResult.setCellValue(col,row,(int)values[band]);
260
                                                        }
261
                                                percent=(int)( progress*100/(gridResult.getLayerNY()*bands.length));        
262
                                        }        
263
                                }        
264
                        }
265
                        
266
                        if(datatype==IBuffer.TYPE_FLOAT)
267
                        {        
268
                                float values[]=new float[bands.length];
269
                                int progress=0;
270
                                // OPTIMIZACION. Se esta recorriendo secuencialmente cada banda.
271
                                for(int band=0; band<bands.length;band++){
272
                                        gridResult.setBandToOperate(band);
273
                                        gridInterpolated.setBandToOperate(band);
274
                                        for(int row=0; row<gridResult.getLayerNY(); row++){
275
                                                progress++;
276
                                                for(int col=0; col<gridResult.getLayerNX();col++)
277
                                                        {
278
                                                                coord=transform.getCoordPixel(col*cellsize+minPointX, maxPointY-row*cellsize);        
279
                                                                values[band] = (float)gridInterpolated._getValueAt(coord[0],coord[1]);
280
                                                                gridResult.setCellValue(col,row,(float)values[band]);
281
                                                        }
282
                                                percent=(int)( progress*100/(gridResult.getLayerNY()*bands.length));        
283
                                        }        
284
                                }        
285
                        }
286
                        
287
                        if(datatype==IBuffer.TYPE_DOUBLE)
288
                        {
289
                                double values[]=new double[bands.length];
290
                                int progress=0;
291
                                // OPTIMIZACION. Se esta recorriendo secuencialmente cada banda.
292
                                for(int band=0; band<bands.length;band++){
293
                                        gridResult.setBandToOperate(band);
294
                                        gridInterpolated.setBandToOperate(band);
295
                                        for(int row=0; row<gridResult.getLayerNY(); row++){
296
                                                progress++;
297
                                                for(int col=0; col<gridResult.getLayerNX();col++)
298
                                                        {
299
                                                                coord=transform.getCoordPixel(col*cellsize+minPointX, maxPointY-row*cellsize);        
300
                                                                values[band] = (double)gridInterpolated._getValueAt(coord[0],coord[1]);
301
                                                                gridResult.setCellValue(col,row,(double)values[band]);
302
                                                        }
303
                                                percent=(int)( progress*100/(gridResult.getLayerNY()*bands.length));        
304
                                        }        
305
                                }        
306
                        }
307
                        
308
                } catch (OutOfGridException e) {
309
                        e.printStackTrace();
310
                } catch (RasterBufferInvalidAccessException e) {
311
                        e.printStackTrace();
312
                } catch (RasterBufferInvalidException e) {
313
                        e.printStackTrace();
314
                }
315
                
316
                generateLayer();
317
                if(externalActions!=null)
318
                        externalActions.end(filename);
319
        }
320

    
321

    
322
        private void generateLayer(){        
323
        
324
                GeoRasterWriter grw = null;
325
                IBuffer buffer= gridResult.getRasterBuf();
326
            writerBufferServer = new WriterBufferServer(buffer);
327
                AffineTransform aTransform = new AffineTransform(newExtend.getCellSize(),0.0,0.0,-newExtend.getCellSize(),newExtend.getMin().getX(),newExtend.getMax().getY());
328
                int endIndex =filename.lastIndexOf(".");
329
                if (endIndex < 0)
330
                        endIndex = filename.length();
331
                try {
332
                        grw = GeoRasterWriter.getWriter(writerBufferServer, filename,gridResult.getRasterBuf().getBandCount(),aTransform, gridResult.getRasterBuf().getWidth(),gridResult.getRasterBuf().getHeight(), gridResult.getRasterBuf().getDataType(), GeoRasterWriter.getWriter(filename).getParams(),null);
333
                        grw.dataWrite();
334
                        grw.setWkt(rasterSE.getWktProjection());
335
                        grw.writeClose();
336
                } catch (NotSupportedExtensionException e1) {
337
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer_notsupportedextension"), this, e1);
338
                } catch (RasterDriverException e1) {
339
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer"), this, e1);        
340
                } catch (IOException e) {
341
                        RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
342
                } catch (InterruptedException e) {
343
                        Thread.currentThread().interrupt();
344
                }
345
        }
346
                
347

    
348
        /*
349
         * (non-Javadoc)
350
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
351
         */
352
        public String getTitle() {
353
                return PluginServices.getText(this,"georreferenciacion_process");
354
        }
355
        
356
        /*
357
         * (non-Javadoc)
358
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getLabel()
359
         */
360
        public int getPercent() {
361
                if(writerBufferServer==null)
362
                        return percent;
363
                else
364
                        return writerBufferServer.getPercent();
365
        }
366

    
367
        
368
        
369
        public void interrupted() {
370
                // TODO Auto-generated method stub        
371
        }
372

    
373
        public void end(Object param) {        
374
                transformData = (GeoTransformDataResult)param;        
375
        }
376

    
377
}