Statistics
| Revision:

root / trunk / extensions / extRemoteSensing / src / org / gvsig / remotesensing / mosaic / process / MosaicProcess.java @ 20733

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.remotesensing.mosaic.process;
42

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

    
47
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
48
import org.gvsig.raster.RasterProcess;
49
import org.gvsig.raster.buffer.BufferFactory;
50
import org.gvsig.raster.buffer.RasterBuffer;
51
import org.gvsig.raster.buffer.RasterBufferInvalidException;
52
import org.gvsig.raster.buffer.WriterBufferServer;
53
import org.gvsig.raster.dataset.GeoRasterWriter;
54
import org.gvsig.raster.dataset.IBuffer;
55
import org.gvsig.raster.dataset.IRasterDataSource;
56
import org.gvsig.raster.dataset.InvalidSetViewException;
57
import org.gvsig.raster.dataset.NotSupportedExtensionException;
58
import org.gvsig.raster.dataset.io.RasterDriverException;
59
import org.gvsig.raster.grid.Grid;
60
import org.gvsig.raster.grid.GridExtent;
61
import org.gvsig.raster.grid.OutOfGridException;
62
import org.gvsig.raster.util.RasterToolsUtil;
63

    
64
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
65
import com.iver.andami.PluginServices;
66
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
67
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
68
import com.iver.cit.gvsig.fmap.layers.FLayer;
69
import com.iver.cit.gvsig.fmap.layers.FLayers;
70

    
71

    
72
/** 
73
* Clase que implementa el de construccion de un mosaico.
74
* 
75
* @author aMu?oz (alejandro.mu?oz@uclm.es)
76
* @version 30/4/2008
77
* */
78

    
79
public class MosaicProcess extends RasterProcess {
80

    
81
        // Layers que intervienen en el proceso
82
        private FLayers layers = null;
83

    
84
        // Extend completo del mosaico
85
        private GridExtent fullExtend= null;
86
        
87
        // Grid resultante
88
        Grid mosaicGrid = null;
89
        
90
        // Buffers con las imagenes
91
        RasterBuffer buffers[]= null;
92
        
93
        // Codigo operacion mayor, menor,media valor de la situada encima.
94
        int codOp= 0; 
95
        
96
        // indicador de proceso
97
         int percent=0;
98
         
99
        // writer para escritura en fichero 
100
        WriterBufferServer writerBufferServer =null;
101
         
102
         
103
        /** Inicializaci?n de los par?metros
104
         *  layers -  FLayers con los layers seleccionados para el mosaico.
105
         * 
106
         *         En la inicializacion se calcula el grid resultante.
107
         * */
108
        
109
        public void init() {
110
                layers= (FLayers)getParam("layers");
111
                codOp= getIntParam("codOp");
112
                
113
                // Calculo del extend resultante
114
                fullExtend= calculateExtend(layers);
115
                try {
116
                                mosaicGrid= new Grid(fullExtend,fullExtend,IBuffer.TYPE_BYTE,new int[]{0,1,2});
117
                } catch (RasterBufferInvalidException e) {
118
                        RasterToolsUtil.messageBoxError("buffer_incorrecto", this, e);
119
                }
120
        }
121

    
122
        
123
        /**
124
         *  Proceso
125
         * */
126
        public void process() throws InterruptedException {
127
                
128
                // Parte de carga de los datos
129
                buffers= new RasterBuffer[layers.getLayersCount()];
130
                IRasterDataSource dsetCopy = null; 
131
                try {
132
                
133
                        double minX= fullExtend.getMin().getX();
134
                        double minY= fullExtend.getMin().getY();
135
                        double maxX=  fullExtend.getMax().getX();
136
                        double maxY=  fullExtend.getMax().getY();
137
                        // Se cargan todos los raster en los grid correspondientes
138
                        percent=0;
139
                        for(int i=0; i< layers.getLayersCount();i++)
140
                        {
141
                                dsetCopy = ((FLyrRasterSE)layers.getLayer(i)).getDataSource().newDataset();
142
                                BufferFactory bufferFactory = new BufferFactory(dsetCopy);
143
                                bufferFactory.setAdjustToExtent(false);
144
                                if (!RasterBuffer.loadInMemory(dsetCopy))
145
                                        bufferFactory.setReadOnly(true);
146
                                bufferFactory.setDrawableBands(((FLyrRasterSE)layers.getLayer(i)).getRenderBands());
147
                                bufferFactory.setAreaOfInterest(minX,minY,maxX,maxY,fullExtend.getNX(),fullExtend.getNY());
148
                                buffers[i]= (RasterBuffer) bufferFactory.getRasterBuf();
149
                                percent=(int)i*100/layers.getLayersCount();
150
                        }
151
                }catch (RasterDriverException e) {
152
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer"), this, e);        
153
                } catch (InvalidSetViewException e) {
154
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_extension"), this, e);        
155
                } catch (InterruptedException e) {
156
                        Thread.currentThread().interrupt();
157
                }
158
                
159
            
160
//                 Construccion del mosaico: Operaci?n M?ximo
161
                if(codOp==0){
162
                        for(int col=0; col<mosaicGrid.getLayerNY(); col++){
163
                                for(int row=0; row<mosaicGrid.getLayerNX();row++){
164
                                        setValueMax(row,col);
165
                                        percent= col*100/mosaicGrid.getLayerNY();
166
                                }
167
                        }
168
                }
169
                
170
//                 Construccion del mosaico: Operaci?n M?nimo
171
                if(codOp==1){
172
                        for(int col=0; col<mosaicGrid.getLayerNY(); col++){
173
                                for(int row=0; row<mosaicGrid.getLayerNX();row++){
174
                                        setValueMin(row,col);
175
                                        percent= col*100/mosaicGrid.getLayerNY();
176
                                }
177
                        }
178
                }
179
                
180
//                 Construccion del mosaico: Operaci?n Media
181
                if(codOp==2){
182
                        for(int col=0; col<mosaicGrid.getLayerNY(); col++){
183
                                for(int row=0; row<mosaicGrid.getLayerNX();row++){
184
                                        setValueMax(row,col);
185
                                        percent= col*100/mosaicGrid.getLayerNY();
186
                                }
187
                        }
188
                }
189
                
190
//                 Construccion del mosaico: Operaci?n Superior
191
                if(codOp==3){
192
                        for(int col=0; col<mosaicGrid.getLayerNY(); col++){
193
                                for(int row=0; row<mosaicGrid.getLayerNX();row++){
194
                                        setValueMax(row,col);
195
                                        percent= col*100/mosaicGrid.getLayerNY();
196
                                }
197
                        }
198
                }
199
                
200
                // Escritura en fichero
201
                writeToFile();
202
        }
203

    
204
        
205
        /**
206
         *  M?todo que establece para la coordenada x,y el valor m?ximo 
207
         *  de todos los valores para ese p?xel en cualquiera de las imagenes.
208
         *  Si el valor en cualquiera de las imagenes es noData no es tenido en cuenta 
209
         *  @param cordenada x 
210
         *  @param coordenada y  
211
         * */
212
        public void setValueMax(int x, int y){
213
                byte result[]= new byte[3];
214
                result[0]=(byte) -128;
215
                result[1]=(byte) -128;
216
                result[2]=(byte) -128;
217
                for(int band=0; band<3;band++){
218
                        for(int buf=0;buf<buffers.length;buf++){
219
                                byte data = (byte)(buffers[buf].getElemByte(y,x,band));
220
//                                 TO DO: TENER EN CUENTA NO DATA REAL DEL BUFER
221
                                if(data==97)
222
                                        data=-128;
223
                                result[band]=(byte) Math.max(result[band],data);                
224
                        }
225
                        try {
226
                                mosaicGrid.setBandToOperate(band);
227
                                mosaicGrid.setCellValue(x,y,(byte)result[band]);
228
                        } catch (OutOfGridException e) {
229
                                // TODO Auto-generated catch block
230
                                e.printStackTrace();
231
                        }
232
                }
233
        }
234
        
235
        
236
        /**
237
         *  M?todo que establece para la coordenada x,y el valor m?ximo 
238
         *  de todos los valores para ese p?xel en cualquiera de las imagenes.
239
         *  Si el valor en cualquiera de las imagenes es noData no es tenido en cuenta 
240
         *  @param cordenada x 
241
         *  @param coordenada y  
242
         * */
243
        public void setValueMin(int x, int y){
244
                byte result[]= new byte[3];
245
                result[0]=(byte) 127;
246
                result[1]=(byte) 127;
247
                result[2]=(byte) 127;
248
                for(int band=0; band<3;band++){
249
                        for(int buf=0;buf<buffers.length;buf++){
250
                                byte data = (byte)(buffers[buf].getElemByte(y,x,band));
251
                                // TO DO: TENER EN CUENTA NO DATA
252
                                if(data==97)
253
                                        data=127;
254
                                result[band]=(byte) Math.min(result[band],data);        
255
                                
256
                                        
257
                        }
258
                        try {
259
                                mosaicGrid.setBandToOperate(band);
260
                                mosaicGrid.setCellValue(x,y,(byte)result[band]);
261
                        } catch (OutOfGridException e) {
262
                                // TODO Auto-generated catch block
263
                                e.printStackTrace();
264
                        }
265
                }
266
        }
267
        
268
        
269
        
270
        /**
271
         * M?todo que calcula el extend resultante para la operaci?n de mosaico
272
         * 
273
         * @param layers que intervienen en la operacion.
274
         * @return GridExtend del mosaico
275
         * */
276
        
277
        private GridExtent calculateExtend (FLayers layers){
278
                GridExtent result= null;
279
                
280
                double minX=0,maxX=0,minY=0,maxY=0, cellSize=25;
281
                try {
282
                        
283
                        minX = layers.getLayer(0).getFullExtent().getMinX();
284
                        minY = layers.getLayer(0).getFullExtent().getMinY();
285
                        maxX = layers.getLayer(0).getFullExtent().getMaxX();
286
                        maxY = layers.getLayer(0).getFullExtent().getMaxY();
287
                        
288
                        for(int i=1; i<layers.getLayersCount();i++){
289
                                minX= Math.min(minX,layers.getLayer(i).getFullExtent().getMinX());
290
                                minY= Math.min(minY,layers.getLayer(i).getFullExtent().getMinY());
291
                                maxX= Math.max(maxX,layers.getLayer(i).getFullExtent().getMaxX());
292
                                maxY= Math.max(maxY,layers.getLayer(i).getFullExtent().getMaxY());
293
                        }
294
                        
295
                } catch (ExpansionFileReadException e) {
296
                        e.printStackTrace();
297
                } catch (ReadDriverException e) {
298
                        e.printStackTrace();
299
                }
300
                
301
                result = new GridExtent(minX,minY,maxX,maxY,25);
302
                return result;
303
        }
304
        
305
        /**
306
         *  M?todo que escribe en fichero el grid resultante de la operaci?n de mosaico.
307
         *  
308
         * */
309
        public void writeToFile(){
310
                try{
311
                        
312
                        String filename= "mosaico"+codOp+".tif";
313
                        GeoRasterWriter grw = null;
314
                        writerBufferServer = new WriterBufferServer(mosaicGrid.getRasterBuf());
315
                        AffineTransform aTransform = new AffineTransform(fullExtend.getCellSize(),0.0,0.0,-fullExtend.getCellSize(),fullExtend.getMin().getX(),fullExtend.getMax().getY());
316
                        grw = GeoRasterWriter.getWriter(writerBufferServer, filename, mosaicGrid.getBandCount(),aTransform, mosaicGrid.getRasterBuf().getWidth(), mosaicGrid.getRasterBuf().getHeight(), mosaicGrid.getRasterBuf().getDataType(), GeoRasterWriter.getWriter(filename).getParams(), null);
317
                        grw.dataWrite();
318
                        grw.setWkt((String)((FLyrRasterSE)layers.getLayer(0)).getWktProjection());
319
                        grw.writeClose();
320
                        
321
                        //mapContext.beginAtomicEvent();
322
                        FLayer lyr = null;
323
                        int endIndex = filename.lastIndexOf(".");
324
                        if (endIndex < 0)
325
                                endIndex = filename.length();
326
                
327
                        lyr = FLyrRasterSE.createLayer(
328
                                        filename.substring(filename.lastIndexOf(File.separator) + 1, endIndex),
329
                                        filename,
330
                                        ((FLyrRasterSE)layers.getLayer(0)).getProjection()
331
                                        );
332

    
333
                /*        mapContext.getLayers().addLayer(lyr);
334
                        //mapContext.endAtomicEvent();
335
                        mapContext.invalidate();*/
336
                
337
                } catch (NotSupportedExtensionException e) {
338
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer_notsupportedextension"), this, e);
339
                } catch (RasterDriverException e) {
340
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer"), this, e);        
341
                } catch (IOException e) {
342
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer"), this, e);
343
                }catch (LoadLayerException e) {
344
                        RasterToolsUtil.messageBoxError("error_cargar_capa", this, e);
345
                }catch (InterruptedException e) {
346
                        Thread.currentThread().interrupt();
347
                }         
348
        }
349
        
350
        
351
        /**
352
         * @return descripcion
353
         * */
354
        public String getTitle() {
355
                return PluginServices.getText(this,"mosaic_process");
356
        }
357

    
358
        
359
        /**
360
         * @return  indicador de progreso
361
         * */
362
        public int getPercent() {
363
                if(writerBufferServer==null)
364
                        return percent;
365
                else 
366
                        return writerBufferServer.getPercent();
367
        }
368

    
369

    
370
        /*
371
        // Identificaci?n de zonas de solapamiento
372
        public boolean getSolapes(FLyrRasterSE raster1, FLyrRasterSE raster2){
373
                
374
                Grid grid1=null, grid2=null, aux=null;;
375
                IRasterDataSource dsetCopy = null; 
376
                dsetCopy =raster1.getDataSource().newDataset();
377
                BufferFactory bufferFactory = new BufferFactory(dsetCopy);
378
                
379
                IRasterDataSource dsetCopy2 = null; 
380
                dsetCopy2 =raster2.getDataSource().newDataset();
381
                BufferFactory bufferFactory2 = new BufferFactory(dsetCopy2);
382
                
383
                
384
                if (!RasterBuffer.loadInMemory(dsetCopy))
385
                        bufferFactory.setReadOnly(true);        
386
                
387
                try {
388
                        grid1 = new Grid(bufferFactory,raster1.getRenderBands());
389
                        grid2= new Grid(bufferFactory2,raster2.getRenderBands());
390
                } catch (RasterBufferInvalidException e) {
391
                        e.printStackTrace();
392
                }        
393
                
394
                // En grid1 la imagen con la cordenada x menor.
395
                if(grid2.getGridExtent().getMin().getX()< grid1.getGridExtent().getMin().getX())
396
                        {
397
                                try {
398
                                        grid1 = new Grid(bufferFactory2,raster2.getRenderBands());
399
                                        grid2= new Grid(bufferFactory,raster1.getRenderBands());
400
                                } catch (RasterBufferInvalidException e) {
401
                                        e.printStackTrace();
402
                                }        
403
                                
404
                        }
405
                
406
                double xmin= grid1.getGridExtent().getMin().getX();
407
                double xmax= grid1.getGridExtent().getMax().getX();
408
                double ymin= grid1.getGridExtent().getMin().getY();
409
                double ymax= grid1.getGridExtent().getMax().getY();
410
                
411
                double xmin2= grid2.getGridExtent().getMin().getX();
412
                double ymin2= grid2.getGridExtent().getMin().getY();
413
                
414
                if(!(xmin2>xmin && xmin2<xmax)){
415
                        System.out.print("Las imagenes no se solapan en las X");
416
                        return false;
417
                }
418
        
419
                if(!(ymin2>ymin && ymin2<ymax)){
420
                        System.out.print("Las imagenes no se solapan en las Y");
421
                        return false;
422
                }
423
                
424
                // Detectado el solapamiento
425
                System.out.print("Rango x["+ xmin2 + ","+ Math.min(xmax,grid2.getGridExtent().getMax().getX())+"].");
426
                System.out.print("Rango y["+ ymin2 + ","+ Math.min(ymax,grid2.getGridExtent().getMax().getY())+"].");
427
                
428
                return true;
429
        }*/
430

    
431

    
432

    
433
}