Statistics
| Revision:

root / trunk / extensions / extGeoreferencing / src / org / gvsig / georeferencing / process / GeoreferencingProcess.java @ 20914

History | View | Annotate | Download (13 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.GeoTransformProcess;
48
import org.gvsig.raster.IProcessActions;
49
import org.gvsig.raster.RasterProcess;
50
import org.gvsig.raster.buffer.BufferFactory;
51
import org.gvsig.raster.buffer.RasterBuffer;
52
import org.gvsig.raster.buffer.RasterBufferInvalidAccessException;
53
import org.gvsig.raster.buffer.RasterBufferInvalidException;
54
import org.gvsig.raster.buffer.WriterBufferServer;
55
import org.gvsig.raster.dataset.GeoRasterWriter;
56
import org.gvsig.raster.dataset.IBuffer;
57
import org.gvsig.raster.dataset.IRasterDataSource;
58
import org.gvsig.raster.dataset.NotSupportedExtensionException;
59
import org.gvsig.raster.dataset.io.RasterDriverException;
60
import org.gvsig.raster.datastruct.GeoPoint;
61
import org.gvsig.raster.grid.Grid;
62
import org.gvsig.raster.grid.GridExtent;
63
import org.gvsig.raster.grid.GridInterpolated;
64
import org.gvsig.raster.grid.OutOfGridException;
65
import org.gvsig.raster.util.RasterToolsUtil;
66

    
67
import com.iver.andami.PluginServices;
68

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

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

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

    
316

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

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

    
362
        
363
        /*
364
         * (non-Javadoc)
365
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getLabel()
366
         */
367
        public String getLog() {
368
                return PluginServices.getText(this,"georreferencing_log_message");
369
        }
370

    
371
        
372
        public void interrupted() {
373
                // TODO Auto-generated method stub        
374
        }
375

    
376
        public void end(Object param) {        
377
        }
378

    
379
}