Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extRemoteSensing / src / org / gvsig / remotesensing / mosaic / process / HistogramMatchingProcess.java @ 20685

History | View | Annotate | Download (8.71 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.io.File;
44
import java.io.IOException;
45

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

    
63
import com.iver.andami.PluginServices;
64
import com.iver.cit.gvsig.exceptions.layers.LoadLayerException;
65
import com.iver.cit.gvsig.fmap.layers.FLayer;
66

    
67

    
68
/** 
69
 * Clase que implementa el proceso de Histogram Matching para una imagen.
70
 * Para el proceso son necesarios dos raster, el raster fuente, que se pretende hacer corresponder
71
 * con el histograma del raster de referencia y el raster maestro o de referencia.
72
 * 
73
 * @author aMu?oz (alejandro.mu?oz@uclm.es)
74
 * @version 30/4/2008
75
 * */
76

    
77
public class HistogramMatchingProcess extends RasterProcess {
78

    
79
        private FLyrRasterSE rasterSource                         = null;
80
        private FLyrRasterSE rasterReference                = null;
81
        private Grid sourceGrid                                                = null;
82
        private Grid gridResult                                                = null;
83
        
84
        // PROVISIONAL -para cargar capa en vista-
85
        //protected MapContext mapContext                         = null;
86
        
87
        private Histogram histogramSource                        = null;
88
        private Histogram histogramReference                = null;
89
        private double [][] acumulateR                                = null;
90
        private double [][] acumulateS                                 = null;
91

    
92
//        Indicador de progreso
93
        private int                     percent            = 0;
94
        
95
        protected WriterBufferServer         writerBufferServer        = null;
96
        
97
        /**
98
         *  Se inicializan los par?metros. 
99
         *  
100
         *  rasterSource raster al que se aplica el proceso de Histogram Matching
101
         *  rasterReference raster que se toma como maestro para hacer la correspondencia
102
         * */
103
        public void init() {
104
                
105
                try {
106
                        rasterSource = (FLyrRasterSE) ((FLyrRasterSE)getParam("rasterSource")).cloneLayer();
107
                        rasterReference = (FLyrRasterSE) ((FLyrRasterSE)getParam("rasterReference")).cloneLayer();
108
                } catch (Exception e1) {
109
                        e1.printStackTrace();
110
                }
111
                
112
                // PROVISIONAL
113
        //        mapContext = (MapContext)getParam("contexto");
114
                try {
115
                
116
                        histogramSource= rasterSource.getBufferFactory().getDataSource().getHistogram();
117
                        histogramReference= rasterReference.getBufferFactory().getDataSource().getHistogram();
118
                
119
                        IRasterDataSource dsetCopy = null; 
120
                        dsetCopy = rasterSource.getDataSource().newDataset();
121
                        BufferFactory bufferFactory = new BufferFactory(dsetCopy);
122

    
123
                        // Inicializacion del grid de datos y el grid resultante
124
                        if (!RasterBuffer.loadInMemory(dsetCopy))
125
                                bufferFactory.setReadOnly(true);        
126
                        
127
                        sourceGrid = new Grid(bufferFactory,rasterSource.getRenderBands());                
128
                        gridResult = new Grid(sourceGrid.getGridExtent(), sourceGrid.getGridExtent(),sourceGrid.getDataType(), new int[]{0,1,2});
129
                        
130
                        acumulateR= Histogram.convertTableToNormalizeAccumulate(histogramReference.getTable());
131
                        acumulateS= Histogram.convertTableToNormalizeAccumulate(histogramSource.getTable());
132
                        
133
                }catch (RasterBufferInvalidException e) {
134
                        RasterToolsUtil.messageBoxError("buffer_incorrecto", this, e);
135
                } catch (HistogramException e) {
136
                        return;
137
                } catch (InterruptedException e) {
138
                        Thread.currentThread().interrupt();        
139
                }
140
        }
141
        
142
        
143
        /** 
144
         * Proceso de correspondecia de Histogramas 
145
         * */
146
        public void process() throws InterruptedException {
147

    
148
                byte tableAsign[][]= new byte[3][256];
149
                int progress=0;
150
                int index=0;
151
                double inValue=0;
152
                
153
                
154
                // C?lculo de la tabla de asignaciones entre los histogramas
155
                for (int band=0; band < rasterSource.getRenderBands().length; band++){
156
                        for(int i= 0; i< tableAsign[0].length; i++){
157
                                inValue = acumulateS[band][i];
158
                                byte value=(byte) (searchInHistogramReference(inValue,band)-128);
159
                                tableAsign[band][i]= value;
160
                        }
161
                }
162
                
163
                try {
164
                // Construccion de la nueva imagen en base a la tabla estimada
165
                        for (int band=0; band < rasterSource.getRenderBands().length; band++){
166
                                gridResult.setBandToOperate(band);
167
                                sourceGrid.setBandToOperate(band);
168
                                for(int i=0; i< sourceGrid.getNY(); i++){
169
                                        progress++;
170
                                        for(int j=0;j<sourceGrid.getNX();j++){                                                                                
171
                                                byte data= (byte) ((sourceGrid.getCellValueAsByte(j,i)));
172
                                                index=data+128;
173
                                                gridResult.setCellValue(j,i,(byte)((tableAsign[band][index])));
174
                                                percent=(int)( progress*100/(gridResult.getLayerNY()*rasterSource.getRenderBands().length));        
175
                                        }        
176
                                }        
177
                        }
178
                } catch (GridException e) {
179
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "grid_error"), this, e);
180
                } catch (OutOfGridException e) {
181
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "bad_access_grid"), this, e);
182
                }        
183
        
184
                // PROVISIONAL
185
                writeToFile();
186
        }
187
        
188
        
189
        /**
190
         * M?todo que realiza la correspondencia entre las clases de los histogramas
191
         * */
192
        public int searchInHistogramReference(double value,int band){
193
                int i=0;
194
                while(value>acumulateR[band][i]){
195
                        i++;
196
                        if(i==255) 
197
                                return (int)255;
198
                }
199
                if(i==0)
200
                        return 0;
201
                if((acumulateR[band][i]-value) < (acumulateR[band][i-1]-value))
202
                        return (int)i;
203
                else 
204
                        return (int)(i-1);
205
        }
206
        
207
        
208
        /**
209
         *  Escritura en fichero y carga de la capa en la vista.
210
         *  Metodo Provisional.
211
         * 
212
         * */
213
        public void writeToFile(){
214

    
215
                try{
216
                        
217
                        String filename= "histogramMatching2.img";
218
                        GeoRasterWriter grw = null;
219
                        writerBufferServer = new WriterBufferServer(gridResult.getRasterBuf());
220
                        grw = GeoRasterWriter.getWriter(writerBufferServer, filename, gridResult.getBandCount(),rasterSource.getAffineTransform(), gridResult.getRasterBuf().getWidth(), gridResult.getRasterBuf().getHeight(), gridResult.getRasterBuf().getDataType(), GeoRasterWriter.getWriter(filename).getParams(), null);
221
                        grw.dataWrite();
222
                        grw.setWkt(rasterSource.getWktProjection());
223
                        grw.writeClose();
224
                        
225
                        //mapContext.beginAtomicEvent();
226
                        FLayer lyr = null;
227
                        int endIndex = filename.lastIndexOf(".");
228
                        if (endIndex < 0)
229
                                endIndex = filename.length();
230
                
231
                        lyr = FLyrRasterSE.createLayer(
232
                                        filename.substring(filename.lastIndexOf(File.separator) + 1, endIndex),
233
                                        filename,
234
                                        rasterSource.getProjection()
235
                                        );
236

    
237
                /*        mapContext.getLayers().addLayer(lyr);
238
                        //mapContext.endAtomicEvent();
239
                        mapContext.invalidate();*/
240
                
241
                } catch (NotSupportedExtensionException e) {
242
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer_notsupportedextension"), this, e);
243
                } catch (RasterDriverException e) {
244
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer"), this, e);        
245
                } catch (IOException e) {
246
                        RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer"), this, e);
247
                }catch (LoadLayerException e) {
248
                        RasterToolsUtil.messageBoxError("error_cargar_capa", this, e);
249
                }catch (InterruptedException e) {
250
                        Thread.currentThread().interrupt();
251
                }         
252
        }
253
        
254
        /**
255
         * @return title
256
         * */
257
        public String getTitle() {
258
                return PluginServices.getText(this,"histogram_matching");
259
        }
260
        
261
        /**
262
         * @return indicador de progreso 
263
         * */
264
        public int getPercent() {
265
                if(writerBufferServer==null)
266
                        return percent;
267
                else
268
                        return writerBufferServer.getPercent();
269
        }
270
        
271
}