Statistics
| Revision:

gvsig-raster / org.gvsig.raster.georeferencing / trunk / org.gvsig.raster.georeferencing / org.gvsig.raster.georeferencing.lib / org.gvsig.raster.georeferencing.lib.impl / src / main / java / org / gvsig / raster / georeferencing / lib / impl / GeoreferencingProcess.java @ 1740

History | View | Annotate | Download (11.8 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.raster.georeferencing.lib.impl;
42

    
43
import java.awt.geom.AffineTransform;
44
import java.util.HashMap;
45

    
46
import javax.swing.SwingUtilities;
47

    
48
import org.gvsig.fmap.dal.coverage.RasterLocator;
49
import org.gvsig.fmap.dal.coverage.RasterManager;
50
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
51
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
52
import org.gvsig.fmap.dal.coverage.datastruct.GeoPointList;
53
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
54
import org.gvsig.fmap.dal.coverage.datastruct.Params;
55
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
56
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
57
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
58
import org.gvsig.fmap.dal.coverage.store.DataServerWriter;
59
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
60
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
61
import org.gvsig.fmap.dal.coverage.store.RasterWriter;
62
import org.gvsig.i18n.Messages;
63
import org.gvsig.raster.impl.grid.GridInterpolated;
64
import org.gvsig.raster.tools.algorithm.base.RasterBaseAlgorithmLibrary;
65
import org.gvsig.raster.tools.algorithm.base.process.IProcessActions;
66
import org.gvsig.raster.tools.algorithm.base.process.ProcessException;
67
import org.gvsig.raster.tools.algorithm.base.process.RasterProcess;
68
import org.gvsig.raster.tools.algorithm.base.util.Interpolation;
69

    
70
/**
71
 *  Resamples a image with the georeferencing parameters
72
 *  @author Nacho Brodin (nachobrodin@gmail.com)
73
 **/
74
public class GeoreferencingProcess extends RasterProcess implements IProcessActions {
75
        public static String             RASTER_STORE       = "RasterStore";
76
        public static String             GCPS               = "gcps";
77
        public static String             ORDER              = "Order";
78
        public static String             TIME               = "Time";
79
        public static String             RESULT             = "RESULT";
80
        public static String             FILENAME           = "FileName";
81
        public static String             METHOD             = "method";
82
        public static String             XCELLSIZE          = "xCellSize";
83
        public static String             YCELLSIZE          = "yCellSize";
84
        public static String             INTERPOLATION      = "Interpolation";
85
            
86
        //Capa a georreferenciar
87
        private RasterDataStore          store                          = null;
88
        
89
        //Fichero de salida
90
        private String                   filename           = null;
91
        
92
        // Lista puntos de control
93
        private GeoPointList             gcps               = null;
94
        
95
        // Metodo de resampleado utilizado
96
        private int                      rMethod            = 0;
97
        
98
        //Indicador de progreso
99
        private int                      percent            = 0;
100
        
101
        private int                      orden              = 0;
102
        
103
        private int[]                    bands              = null;
104
        
105
        //Tama?o de celda en X si es pasada por el usuario
106
        private double                   xCellSize           = 0;
107
        //Tama?o de celda en Y si es pasada por el usuario
108
        private double                   yCellSize           = 0;
109
        
110
        private final DataServerWriter   writerBufferServer  = null;
111
        private long                     milis               = 0;
112
        
113
        public static void registerParameters() {
114
                RASTER_STORE = RasterBaseAlgorithmLibrary.registerInputParameter(RASTER_STORE, RasterDataStore.class);
115
                INTERPOLATION = RasterBaseAlgorithmLibrary.registerInputParameter(INTERPOLATION, Integer.class); 
116
                GCPS = RasterBaseAlgorithmLibrary.registerInputParameter(GCPS, GeoPointList.class);
117
                ORDER = RasterBaseAlgorithmLibrary.registerInputParameter(ORDER, Integer.class);
118
                TIME = RasterBaseAlgorithmLibrary.registerOutputParameter(TIME, Long.class);
119
        }
120
        
121
        /** Metodo que recoge los parametros del proceso georreferenciacion de un raster
122
        * <LI>rasterSE: capa a georeferenciar</LI>
123
        * <LI>filename: path con el fichero de salida</LI>
124
        * <LI>method: metodo de resampleo </LI>
125
        */
126
        public void init() {
127
                store = getParam(RASTER_STORE) != null ? (RasterDataStore)getParam(RASTER_STORE) : null;
128
                gcps = getParam(GCPS) != null ? (GeoPointList) getParam(GCPS) : null;
129
                filename = (String)getParam(FILENAME);
130
                rMethod = (int)getIntParam(METHOD);
131
                orden = (int)getIntParam(ORDER);
132
                bands = new int[store.getBandCount()];
133
                xCellSize = (double)getDoubleParam("xCellSize");
134
                yCellSize = (double)getDoubleParam("yCellSize");
135
                
136
                for(int i = 0; i < store.getBandCount(); i++)
137
                        bands[i]= i;
138
        }
139
        
140

    
141
        public void process() throws ProcessInterruptedException, ProcessException {
142
                long t1 = new java.util.Date().getTime();
143
                
144
                RasterQuery query = RasterLocator.getManager().createQuery();
145
                query.setAllDrawableBands();
146
                query.setAreaOfInterest();
147
                query.setReadOnly(true);
148
                Buffer bufInput;
149
                try {
150
                        bufInput = store.query(query);
151
                } catch (RasterDriverException e1) {
152
                        throw new ProcessException("Error getting the input buffer", e1);
153
                } catch (InvalidSetViewException e1) {
154
                        throw new ProcessException("Error getting the input buffer", e1);
155
                }
156
                
157
                GeoTransformProcess transform = new GeoTransformProcess();
158
                transform.setActions(this);
159
                transform.addParam(GCPS, gcps);
160
                transform.addParam(ORDER, new Integer(orden));
161
                transform.execute();                
162
                
163
                // Obtenida la transformacion la aplicamos a los puntos extremos de la imagen
164
                double p1[] = transform.getCoordMap(0, 0);                
165
                double p2[] = transform.getCoordMap(store.getWidth(), 0);                
166
                double p3[] = transform.getCoordMap(0, store.getHeight());
167
                double p4[] = transform.getCoordMap(store.getWidth(), store.getHeight());        
168
                                
169
                double xmin = Math.min(p1[0], p3[0]);
170
                double ymin = Math.min(p3[1], p4[1]);
171
                double xmax = Math.max(p2[0], p4[0]);        
172
                double ymax = Math.max(p1[1], p2[1]);
173
                
174
                Extent bbox = store.getExtent();
175
                Extent newBbox = RasterLocator.getManager().getDataStructFactory().createExtent(xmin, ymax, xmax, ymin);
176
                int w = 0;
177
                int h = 0;
178
                if(xCellSize >= 0 && yCellSize >= 0) {
179
                        w = (int)(bbox.width() * xCellSize);
180
                        h = (int)(bbox.height() * yCellSize);
181
                } else {
182
                        double[] size = getSize(bbox, newBbox);
183
                        w = (int)size[0];
184
                        h = (int)size[1];
185
                        xCellSize = yCellSize = size[2];
186
                }
187
                        
188
                int dataType = store.getDataType()[0];
189
                
190
                Buffer bufResult = RasterLocator.getManager().createBuffer(
191
                                dataType, 
192
                                w, 
193
                                h, 
194
                                store.getBandCount(), 
195
                                true);
196
                
197
                NoData nd = RasterLocator.getManager().getDataStructFactory().createDefaultNoData(
198
                                store.getBandCount(), dataType);
199
                
200
                Interpolation interpolation = new Interpolation(bufInput);
201

    
202
                double coord[] = null;
203
                double values[] = new double[bands.length];
204
                int progress = 0;
205
                for(int row = 0; row < bufResult.getHeight(); row++) {
206
                        for(int col = 0; col < bufResult.getWidth(); col++) {
207
                                coord = transform.getCoordPixel(col * xCellSize + xmin, ymax - row * yCellSize);
208
                                if(coord[0] < 0)
209
                                        coord[0] = 0;
210
                                if(coord[1] < 0)
211
                                        coord[1] = 0;
212
                                if(coord[0] > bufInput.getWidth() - 1)
213
                                        coord[0] = bufInput.getWidth() - 1;
214
                                if(coord[1] > bufInput.getHeight() - 1)
215
                                        coord[1] = bufInput.getHeight() - 1;
216
                                
217
                                for (int iBand = 0; iBand < store.getBandCount(); iBand++) {
218
                                        
219
                                        
220
                                        if(rMethod == GridInterpolated.INTERPOLATION_Bilinear)
221
                                                values[iBand] = interpolation.getBilinearValue(coord[0], coord[1], iBand);
222
                                        if(rMethod == GridInterpolated.INTERPOLATION_InverseDistance)
223
                                                values[iBand] = interpolation.getInverseDistance(coord[0], coord[1], iBand);
224
                                        else
225
                                                values[iBand] = interpolation.getBilinearValue(coord[0], coord[1], iBand);
226
                                        
227
                                                
228
                                        if(dataType == Buffer.TYPE_BYTE) 
229
                                                bufResult.setElem(row, col, iBand, (byte)values[iBand]);
230
                                        else if(dataType == Buffer.TYPE_DOUBLE)
231
                                                bufResult.setElem(row, col, iBand, (double)values[iBand]);
232
                                        else if(dataType == Buffer.TYPE_FLOAT)
233
                                                bufResult.setElem(row, col, iBand, (float)values[iBand]);
234
                                        else if(dataType == Buffer.TYPE_SHORT)
235
                                                bufResult.setElem(row, col, iBand, (short)values[iBand]);
236
                                        else if(dataType == Buffer.TYPE_INT)
237
                                                bufResult.setElem(row, col, iBand, (int)values[iBand]);
238
                                }
239
                        }
240
                        percent = (int)(progress * 100 / (bufResult.getHeight() * bands.length));
241
                }
242

    
243
                export(filename, bufResult, xCellSize, xmin, ymin);
244
                
245
                long t2 = new java.util.Date().getTime();
246
                milis = t2 - t1;
247
                
248
                SwingUtilities.invokeLater(new Runnable() {
249
                        public void run() {
250
                                if (externalActions != null) {
251
                                        externalActions.end(getResult());
252
                                }
253
                        }
254
                });
255
                
256
                if(externalActions!=null)
257
                        externalActions.end(filename);
258
        }
259
        
260
        /**
261
         * Gets the size of the new image
262
         * @param bbox
263
         * @param newBbox
264
         * @return
265
         */
266
        private double[] getSize(Extent bbox, Extent newBbox) {
267
                double sumSideOldBBox = bbox.width() + bbox.height();
268
                double sumSideNewBBox = newBbox.width() + newBbox.height();
269
                double d1x = (bbox.width() * 100) / sumSideOldBBox; 
270
                double d1y = (bbox.height() * 100) / sumSideOldBBox;
271
                double d2x = (newBbox.width() * 100) / sumSideNewBBox;
272
                double d2y = (newBbox.height() * 100) / sumSideNewBBox;
273
                double p2y = (store.getHeight() * d2y) / d1y;
274
                double p2x = (store.getWidth() * d2x) / d1x;
275
                double newCellSize = newBbox.width() / p2x;
276
                return new double[]{Math.round(p2x), Math.round(p2y), newCellSize};
277
        }
278
        
279
        public Object getResult() {
280
                HashMap<String, Object> map = new HashMap<String, Object>();
281
                map.put(FILENAME, filename);
282
                map.put(TIME, new Long(milis));
283
                return map;
284
        }
285

    
286
        public boolean export(final String sFilename, Buffer buf, double cellsize, double minX, double minY) {
287

    
288
        try {
289
            RasterManager manager = RasterLocator.getManager();
290
            final DataServerWriter writerBufferServer =
291
                manager.createDataServerWriter();
292
            writerBufferServer.setBuffer(buf, -1);
293
            final Params params = manager.createWriterParams(sFilename);
294
            final AffineTransform affineTransform =
295
                new AffineTransform(cellsize, 0, 0,
296
                    -cellsize, minX, minY);
297

    
298
            final RasterWriter writer =
299
                manager.createWriter(writerBufferServer, sFilename,
300
                    buf.getBandCount(), affineTransform, buf.getWidth(),
301
                    buf.getHeight(), buf.getDataType(), params, null);
302
            writer.dataWrite();
303
            writer.writeClose();
304

    
305
        } catch (final Exception e) {
306
                e.printStackTrace();
307
            return false;
308
        }
309

    
310
        return true;
311

    
312
    }
313

    
314
        public String getTitle() {
315
                return Messages.getText("georreferenciacion_process");
316
        }
317
        
318
        public int getPercent() {
319
                if(writerBufferServer == null)
320
                        return percent;
321
                else
322
                        return writerBufferServer.getPercent();
323
        }
324
        
325
        public String getLog() {
326
                return Messages.getText("georreferencing_log_message");
327
        }
328
        
329
        public void interrupted() {
330
        }
331

    
332
        public void end(Object param) {        
333
        }
334
}