universidad de extremadura
Transcripción
universidad de extremadura
UNIVERSIDAD DE EXTREMADURA Escuela Politécnica Máster en Ingeniería Informática Trabajo Final de Máster Desarrollo de un Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Ángel María Ferrán Frías Marzo 2012 2 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web TMF MII, UEX 2012 Ángel Ferrán Frías 3 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web UNIVERSIDAD DE EXTREMADURA Escuela Politécnica Máster en Ingeniería Informática Trabajo Final de Máster Desarrollo de un Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Autor: Ángel María Ferrán Frías Fdo: TRIBUNAL CALIFICADOR Presidente: Fdo: Directores: Pablo García Rodríguez Fdo Secretario: Fdo Vocal: Fdo: Antonio Plaza Miguel Fdo: CALIFICACIÓN: FECHA: TMF MII, UEX 2012 Ángel Ferrán Frías 4 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web TMF MII, UEX 2012 Ángel Ferrán Frías 5 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Dedicado a mi mujer, Marta, por darme las fuerzas necesarias cada día para poder realizar este Máster, por confiar en mí más que yo mismo y por permitirme haberle robado tanto tiempo. A mis padres y hermanos, por el poco tiempo prestado y por su generosidad. A mis sobrinas, Carla, Mara y Lucía por darme tantas risas, alegrías y energías. Ángel Ferrán Marzo, 2012 TMF MII, UEX 2012 Ángel Ferrán Frías 6 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web TMF MII, UEX 2012 Ángel Ferrán Frías 7 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Agradecimientos A Pablo García, por el continuo apoyo prestado, la generosidad demostrada, por transmitirme siempre la motivación necesaria para finalizar este Máster y por confiar en mí para realizar este trabajo. Sin su apoyo hubiera resultado mucho más difícil. A Antonio Plaza, por estar siempre ahí, por colaborar tanto y tan bien en este proyecto y por darme la oportunidad de aprender algo tan interesante de su trabajo. A Sergio Bernabé, por su inestimable ayuda en este proyecto, por tanta colaboración prestada y por enseñarme mucho de algoritmos de procesamiento. A Abel Paz, por su aportación en materia de Servidores y Sistemas y por todo el apoyo y el buen hacer. A mis compañeros del Máster en Ingeniería Informática, Sergio, Jose, Samuel, Roberto, Manuel, Juan Luis, Noelia y Ricardo por ser tan buenos compañeros, dejarme aprender algo de ellos y pasar muy buenos ratos juntos. A todo el profesorado del MII de la Universidad de Extremadura, por el trabajo realizado con tan poco tiempo disponible y las ganas demostradas por conseguir una buena Universidad para Extremadura. A todos, un fuerte abrazo y muchas gracias. Ángel Ferrán Marzo, 2012 TMF MII, UEX 2012 Ángel Ferrán Frías 8 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web TMF MII, UEX 2012 Ángel Ferrán Frías 9 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Table of Contents Abstract ................................................................................................................. 13 1. Introduction ....................................................................................................... 14 2 System architecture ............................................................................................. 17 2.1 Maps layer ......................................................................................................................... 19 2.2 Server layer ....................................................................................................................... 20 2.3 Client layer ........................................................................................................................ 21 3. Methodology ...................................................................................................... 23 3.1 Image acquisition .............................................................................................................. 24 3.2. Graphical user interface (GUI).......................................................................................... 26 3.3. Image processing.............................................................................................................. 29 3.3.1. Handling image processing requests......................................................................... 29 3.3.2. Performing the actual image processing task ........................................................... 30 3.3.3. Saving the final obtained results ............................................................................... 32 4. Experimental results ........................................................................................... 33 4.1. Experiment 1: Validation of the k-means unsupervised classification algorithm ............ 34 4.2. Experiment 2: Validation of the ISODATA algorithm with spatial post-processing ......... 37 4.3. Experiment 3: Performance of the client-server architecture ......................................... 40 5. Conclusions and future research lines ................................................................. 48 Annexes ................................................................................................................. 51 A) User Manual ...................................................................................................... 51 A.1. Introducción ..................................................................................................................... 51 A.1.1 ¿Qué es WMPS? ......................................................................................................... 51 A.2. Acceso a la Aplicación ...................................................................................................... 51 A.3. Configuración ................................................................................................................... 52 A.4. Barra de Herramientas ..................................................................................................... 52 A.4.1. Creación de Mapas.................................................................................................... 53 A.4.2. Obtención de Capturas ............................................................................................. 54 A.4.3. Actualizar Capturas ................................................................................................... 54 TMF MII, UEX 2012 Ángel Ferrán Frías 10 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web A.4.4. Manejo de Nivel de Zoom ......................................................................................... 54 A.4.5 Procesado K-Means ................................................................................................... 55 A.4.6. Procesado Isodata ..................................................................................................... 56 A.4.7. Gestión de Clases ...................................................................................................... 56 A.4.8. Centrado del Mapa ................................................................................................... 57 A.4.9. Guardar Capturas ...................................................................................................... 58 B) Programmer Manual .......................................................................................... 59 B.1. Introducción ..................................................................................................................... 59 B.2. Arquitectura ..................................................................................................................... 59 B.3. Tecnología ........................................................................................................................ 60 B.4. Estructura de Ficheros ..................................................................................................... 61 B.5. Requisitos del Sistema ..................................................................................................... 61 B.6. Instrucciones de Despliegue ............................................................................................ 62 B.7. Módulos y código Fuente ................................................................................................. 62 B.7.1. Capa: SERVIDOR ........................................................................................................ 62 B.7.2. Capa REPOSITORIO DE IMÁGENES ............................................................................ 70 B.7.3. Capa CLIENTE ............................................................................................................ 70 C) Project Charter ................................................................................................... 79 C.1. Información general ......................................................................................................... 79 C.2. Resumen del proyecto ..................................................................................................... 79 C.3. Objetivos del proyecto ..................................................................................................... 80 C.4. Alcance del proyecto ........................................................................................................ 80 C.5. Descripción del producto / servicio ................................................................................. 80 C.6. Participantes del proyecto ............................................................................................... 80 C.7. Hitos importantes del proyecto ....................................................................................... 81 C.8. Restricciones del proyecto ............................................................................................... 81 C.9. Criterios de aceptación del proyecto ............................................................................... 81 C.10. Sponsor que autoriza el proyecto .................................................................................. 81 D) Planning and System Construction ..................................................................... 83 D.1. Introducción ..................................................................................................................... 83 D.2. Planificación Inicial........................................................................................................... 83 D.3. Planificación Final ............................................................................................................ 84 D.4. Análisis Requisitos............................................................................................................ 86 D.5. Análisis del Proyecto ........................................................................................................ 87 TMF MII, UEX 2012 Ángel Ferrán Frías 11 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web D.6. Construcción del Proyecto ............................................................................................... 89 D.7. Pruebas del Proyecto ....................................................................................................... 90 D.8. Plan de Mantenimiento ................................................................................................... 91 D.8.1. Introducción .............................................................................................................. 91 D.8.2. Nuevas Funcionalidades ........................................................................................... 91 D.8.3. Módulos revisables y mejorables ............................................................................. 92 E) Glossary of Terms ............................................................................................... 93 E.1. Introducción ..................................................................................................................... 93 E.2. Glosario de Términos. ...................................................................................................... 93 References ............................................................................................................. 99 TMF MII, UEX 2012 Ángel Ferrán Frías 12 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web TMF MII, UEX 2012 Ángel Ferrán Frías 13 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web New Web-Based System for Unsupervised Classification of Satellite Imagery Angel Ferrán1, Sergio Bernabé2, Pablo García-Rodríguez1 and Antonio Plaza2 1 Grupo de Ingeniería de Medios, Dept. of Systems Engineering and Telematics University of Extremadura, Avda. de la Universidad s/n, 10003 Cáceres, SPAIN E-mail: [email protected], [email protected] 2 Hyperspectral Computing Laboratory, Dept. of Technology of Computers and Communications University of Extremadura, Avda. de la Universidad s/n, 10003 Cáceres, SPAIN E-mail: {sergiobernabe,aplaza}@unex.es Abstract The availability of satellite images has significantly increased in recent years, and the possibility to perform fast processing of massive databases comprising this kind of imagery data has opened ground-breaking perspectives in many different fields. In this regard, the widespread use and availability of web-based tools such as Google Maps has quickly introduced new processing challenges. In this paper, we develop a new webbased system for unsupervised classification of remotely sensed images which is available for public use1. The system has been developed using the Google Maps applications programming interface (API), and incorporates a complete unsupervised classification chain for satellite image data. It is made up of the well-known ISODATA and k-means algorithms, followed by spatial post-processing based on majority voting. The system makes use of a remote server to speed-up the processing of large satellite images, using a cluster of commodity graphics processing units (GPUs) to perform the calculations in computationally efficient fashion. The system has been experimentally 1 http://login-hpc.ceta-ciemat.es/hypercomp/Wmps/Wmps.html TMF MII, UEX 2012 Ángel Ferrán Frías 14 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web validated using different satellite images obtained from the Google Maps tool, and the classification accuracy has been validated with regards to techniques available in the well-known Environment for Visualizing Images (ENVI) commercial software package. Our experimental results indicate that the proposed system can perform computationally efficient and accurate web-based classification of satellite images available from Google Maps engine. Keywords: Web-based system, satellite image classification, Google Maps. 1. Introduction Remote sensing image analysis and interpretation has become an important tool, particularly thanks to the wide availability of web mapping services and programs which have increased the community of users of satellite images that not long ago were available mainly to government intelligence agencies [1, 2]. Specifically, the wealth of satellite imagery available from Google Maps, which now provides high-resolution satellite images from many locations around the Earth2, has opened the appealing perspective of performing classification and retrieval tasks via the Google Maps application programming interface (API). In fact, the introduction of Google's mapping engine prompted a worldwide interest in satellite imagery exploitation. The combination of an easily searchable mapping and satellite imagery tool such as Google Maps with advanced image classification and retrieval features [3]. has the potential to significantly expand the functionalities of the tool and also to allow end-users to extract relevant information from a massive and widely available database of satellite images (the Google Maps service is free for non-commercial use). By using the Google Maps Javascript API, it is now possible to embed the full Google Maps site into an external website application. Other similar services currently available comprise Yahoo Maps3 and OpenStreetMap4. The characteristics of Yahoo Maps are similar to those available in Google Maps 2 http://code.google.com/apis/maps/index.html 3 http://maps.yahoo.com TMF MII, UEX 2012 Ángel Ferrán Frías 15 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web (although the spatial resolution of the satellite imagery available in Yahoo Maps is generally lower than the resolution of the image data available from Google Maps). On the other hand, the OpenStreetMap follows a different approach. It is a collaborative project aimed at creating a free editable map of the world. Its design was inspired by sites such as Wikipedia5. As shown by Fig. 1, the Google Maps service offers important competitive advantages, such as the availability of high resolution satellite imagery, the smoothness in the navigation and interaction with the system, the availability of a hybrid satellite view which can be integrated with other views (e.g. maps view), and adaptivity for general-purpose desktop applications. Despite its competitive advantages, the possibility to perform unsupervised or supervised classification of satellite images at different zoom levels [4, 5] is not available in Google Maps, despite image classification is widely recognized as one of the most powerful approaches in order to extract information from satellite imagery [6, 7]. The incorporation of such functionality to Google Maps would allow us to extract relevant information from a massive and widely available database of satellite images and the possibility to perform contentbased image retrieval (CBIR) tasks [8] which are of great interest for the exploitation of this and other satellite image databases. 4 http://www.openstreetmap.org 5 http://www.wikipedia.org TMF MII, UEX 2012 Ángel Ferrán Frías 16 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Figure 1. A comparison of the main functionalities offered by web mapping services: Google MapsTM, Yahoo Maps and OpenStreetMap. In this paper, we describe a new web-based system (which represents a follow-up to our previous work in [9]) which allows an unexperienced user to perform unsupervised classification of satellite images obtained via Google Maps through a web-based system that incorporates a fully unsupervised processing chain based on two well-known clustering techniques: ISODATA [10] and k-means [11], followed by spatial postprocessing based on majority voting [12]. The processing chain has been implemented in the C++ language and integrated into our proposed tool, developed using HTML5, JavaScript, Php, Ajax and other web programming languages. A very important functionality of our newly developed tool is the fact that it exploits a remote server to speed-up the processing of large satellite images, using a cluster of commodity graphics processing units (GPUs) [13] to perform the calculations in computationally efficient fashion. Recent literature has focused on the development of high-performance computing implementations for remotely sensed satellite imagery [14-18], and particularly GPUs [19-25] have been used as a source of computational power that can be obtained at low cost in order to accelerate processing chains in satellite image TMF MII, UEX 2012 Ángel Ferrán Frías 17 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web interpretation. In this regard, our proposed contribution represents an innovative way to process the satellite imagery available from Google Maps engine by resorting to a centralized GPU cluster with the capacity to perform the processing of large amounts of satellite data in computationally efficient fashion. The remainder of the paper is organized as follows. Section 2 describes the system architecture, including relevant aspects such as the map, server and client layers. Section 3 describes the processing chain implemented by the proposed methodology, including aspects such as the image acquisition process, the graphical user interface (GUI) that allows end-users to interact with the proposed system, the image processing algorithms implemented and their efficient implementation in the GPU cluster, and the procedure adopted for data saving and end product distribution to the users. Section 4 performs an experimental validation of the classification results obtained by the proposed system by comparing the classification accuracy of the proposed chain with regards to techniques available in the well-known Environment for Visualizing Images (ENVI) software package6. Finally, section 5 concludes the paper with some remarks and hints at plausible future research. 2 System architecture In this section we describe the architecture of the proposed system, whose general architecture is described in Fig. 2. The system is a web application made up of several layers or modules. Each module serves a different purpose, and the technology adopted for the development of the system is based on open standards and free software. Specifically, we have used a blend of different tools for the development of the system, including Apache web server7, PHP8 (a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into the hypertext 6 http://www.exelisvis.com/language/en-us/productsservices/envi.aspx 7 http://httpd.apache.org/ 8 http://www.php.net/ TMF MII, UEX 2012 Ángel Ferrán Frías 18 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web markup language such as the version HTML59 used in our development), JavaScript libraries10, Asynchronous JavaScript and extensive markup language (AJAX)11, Jquery12 and its user interface (UI)13, cascading style sheets (CSS)14 and, last but not least, the C++ programming language and NVidia’s compute device unified architecture (CUDA)15 for carrying out the image processing tasks. As shown by the architecture model described in Fig. 2, the proposed system can be described from a high level viewpoint using three different layers, which are completely independent from each other. Due to the adopted modular design, any of the layers can be replaced. Also, the system is fully scalable, allowing for the incorporation of additional layers. The communication betweetn two layers is carried out throught the Internet, using the hypertext transfer protocol (HTTP)16. As a result, the system performance will depend largely (as expected) on the available bandwidth. Therefore, both the map layer (currently provided by Google Maps) and the server layer (developed by ourselves) are available from any location in the world. In the following, we describe each of the layers adopted in the system in detail. 9 http://www.w3.org/TR/html5/ 10 http://javascriptlibraries.com/ 11 http://www.asp.net/ajax 12 http://jquery.com/ 13 http://jqueryui.com/ 14 http://www.w3schools.com/css/ 15 http://www.nvidia.com/object/cuda_home_new.html 16 http://www.w3.org/Protocols/ TMF MII, UEX 2012 Ángel Ferrán Frías 19 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Figure 2: Architecture of the proposed system expressed in the form of different modular layers. 2.1 Maps layer This layer contains the source imagery data to be used by the system, i.e. the image repository. Google Maps is used in the current version by means of the Google Maps API V3 as a programming interface intended for accessing the provided maps. Taking this into account, it is important to emphasize that the current framework is limited to the types of maps provided by Google Maps. Therefore, all types of maps provided by the API V3 can be used, including roadmaps (2D mosaics), satellite images, hybrid view (mixed satellite images and roadmap, superimposed), or terrain (physical relief). Also, all the potentials and functionalities provided by the Google Maps API V3 are included (this comprises management of zoom levels, image centering, location by geospatial coordinates, etc.) Although Google Maps is now used by our system as a repository of images, the system is open and could support other possible alternative repositories such as Yahoo Maps or OpenStreetMap. These systems are all accessible TMF MII, UEX 2012 Ángel Ferrán Frías 20 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web for free and easy to include in our proposed platform. In this work, Google Maps was mainly chosen due to the advantages summarized in Fig. 1. In fact, the image repository can be used to capture any satellite image displayed by the Google Maps engine, and most importantly the images can be captured at different zoom levels. Even a single image can be extracted at different zoom levels, which is obtained by different image sizes and resolutions. This offers significant advantages in terms of analyzing perfectly geo-registered satellite imagery at different resolutions [26]. 2.2 Server layer The server layer is one of the main components of the system. It is formed by two submodules: web server and compute server. The former is the part of the system in charge of hosting the source code of the application (developed using HTML5, PHP, JavaScript and CSS) and deal with the incoming traffic and requests from client browsers. In our system we have used the Apache web server due to its wide acceptance and performance, and also due to the fact that its software license is free. Further, PHP is used both in the server layer and also for managing the communications between the clients and the web server (mainly dominated by the transmission of satellite imagery to be processed) and between the web server and the compute server (intended for the processing of satellite images). In fact, the compute server is mainly in charge of the actual image processing tasks which comprise clustering using k-means [10] and ISODATA [11] algorithms, and spatial post-processing [12]. In this regard, the compute server receives the processing requests from end-users, manages them effectively by resorting to a local GPU cluster made up of 44 NVidia Tesla C1060 GPUs17 (in the future, further acceleration by means of efficient NVidia CUDA implementations will be pursued), and then provides the obtained result to the end-user. Currently the web server and the computer server are hosted in the same machine, but the system also allows to have different machines for this purpose. It is also worth noting that the system is modular, thus allowing for the incorproation of additional processing modules other than ISODATA, k-means and spatial postprocessing. At this point, we also emphasize that the current system has been 17 http://www.nvidia.com/object/personal-supercomputing.html TMF MII, UEX 2012 Ángel Ferrán Frías 21 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web shown to be able to handle the processing of large image data sets. This is because, in the current implementation, both the web server and the compute server are implemented in a cluster of GPUs, thus reducing the communication time which is limited to the transfer of the image to be processed from the client to the server and the return of the obtained processing result after it is locally obtained in the cluster. 2.3 Client layer The client layer defines the interactions between the user (through an internet browser) and our system. Only one web page is needed as user interface thanks to the adopted AJAX and JavaScript technologies, which allow updating the web interface without the need for interactions with the web server. The design of the web interface has been done using Jquery UI, which provides built-in JavaScript modules which are attractive, easy to use and freely available. The interaction betwen the user and the client web interface is captured by the event handlers of the Jquery libraries, and executed at the local browser as JavaScript is only executed in the browser in our implementation. Hence, the only actions from the user which are transmitted to the server layer are those related with the processing of satellite images. In this context, the images to be processed are transmitted to the server using AJAX-based requests, and the web server provides such requests to the compute server (in our implementation, implemented in the same machine) so that the compute server can process the images very efficiently and produce a result that is then transmitted back to the client layer. This process is illustrated in Fig. 3, which also shows how the client layer perform requests to the maps layer in order to update the maps which are being handled by the end-user. This comprises operations such as zoom in-out, changing of location in the map, creation of maps, selection of the specific view in which the processing will be accomplished (satellite, roadmap, hybrid, etc.) In this regard, Fig. 3 provides an illustrative view of the communications taking place between the main layers in our system. In order to better interpret the interactions between the different layers of our system, graphically illustrated in Fig. 3, in the following we provide an example of the flow of a processing request started by the client in the system and the different steps needed until a processing result is received by the end-user. The following steps are identified in Fig. 3: TMF MII, UEX 2012 Ángel Ferrán Frías 22 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Figure 3: Interactions between the three main layers (map, client and server) of our system. 1. First, the client starts the use of the system by requesting a web page from the local internet browser. This results in an HTTP request to the web server. 2. The web server receives this request and provides the client with an HTML web page and all necessary references (JavaScript libraries, CSS, etc.) 3. At this point, the client requests from the map server the information needed to perform the map modification locally (i.e., zooming in-out, etc.) This operation is transparent to the system, and the requests are performed via messages from the client to the maps server. 4. The maps layer returns the information requested by the client in the form of updated maps that will be locally managed by the end-user. 5. Once the end-user has decided the image and view to be processed, a capture of the image information is performed in order to delimit the image that will be processed by the compute server. This process is locally managed at the client by means of JavaScript functions. We emphasize that the end-used can decide the zoom level and the image view (street, satellite, hybrid, etc.) in which the image to be processed is captured. TMF MII, UEX 2012 Ángel Ferrán Frías 23 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web 6. Now the captured image is sent to the web server by means of AJAX functions and asynchronous requests. In this way, the interaction with the application at the client layer can continue while the captured image is being transferred to the server. 7. The web server provides the satellite image to be processed to the compute server. In this regard, we emphasize that our system delegates the processing task to an independent high-performance system (GPU cluster) that takes care of the processing task independently from other layers in the system. 8. Once the satellite image has been procesed, the compute server returns the obtained result to the web server. We reiterate that in our current implementation both the web server and the compute server are implemented in the same computing machine, hence in this case the communications are minimized. 9. Finally, the processing result is returned to the client so that it can be saved to disk as the final outcome of the adopted processing chain. 3. Methodology In this section we describe the methodology adopted for the development of the proposed system. Several main tasks have been identified: image acquisition, graphical user interface (GUI), web server, image processing and image saving. These tasks, which are summarized in the flowchart given in Fig. 4, will be described in detail in the present section. TMF MII, UEX 2012 Ángel Ferrán Frías 24 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web . Figure 4: Flowchart describing the methodology adopted for the development of the system. 3.1 Image acquisition Image acquisition is the starting point of the system operation. The images to be processed are considered from two different viewpoints. On the one hand, the images are parts of a map and, on the other hand, the images can also be considered as a specific capture or snapshot of a larger map. The maps are dynamic entities which can be dragged, zoomed (i.e. displayed in more or less detail), but the captures can be seen as static parts of a map which are selected by the end-user through the interface. These captures or snapshots can then be sent to the server and processed in spite of the components of the map layer, in our case supported by the Google Maps engine. TMF MII, UEX 2012 Ángel Ferrán Frías 25 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Figure 5: Flowchart describing the strategies adopted for managing image captures. The methodology implemented in our system for obtaining the image captures from the maps layer has been developed using JavaScript libraries. These processes have access to the collection or “puzzle” of images that compose a certain map, thus taking advantage of the browser cache memory to optimize such operation. The query is directed to the map layer in case that the image is not already present in the cache memory (a situation which happens quite rarely). This allows some advantages, most notably the high speed achieved by the system in the task of obtaining image captures regardless of the latency of communications with the server. This reduces the communication traffic and increases the performance in the local management of image captures. In order to achieve this functionality, several layers of images from the server are considered once the image captures have been processed, thereby obtaining a stack of images in which each layer represents a class (as determined by the considered processing algorithms, i.e. k-means and ISODATA). The layers are completely TMF MII, UEX 2012 Ángel Ferrán Frías 26 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web independent, thus allowing visualization as individual entities or as a combination between layers, providing a lot of flexibility in the analysis of the obtained results and a specific management of layers. Finally, the system also allows for the rapid acquisition of multiple captures from the same map, along with the simultaneous operation of multiple maps at the same time. For illustrative purposes, Fig. 5 shows the strategy adopted by our system for managing image captures. 3.2. Graphical user interface (GUI) GUI is a very important component as it is the visible part of our system and it allows the user to perform all operations available in the application. An HTML page and JavaScript libraries have been used for development. These libraries are the Jquery framework (version 1.6.2) and Jquery-UI (version 1.8.16). Other own developments using JavaScript libraries have been accomplished in order to add new functionalities to the created widgets. As the whole GUI runs on the client layer, usability and speed of response is guaranteed and the adopted design is very flexible. The GUI has been developed in the form of a single HTML page, avoiding repeated requests and responses back to the server while. Several features within the HTML5 standard have been used in order to design the GUI for our system applciation. The most important object used is the canvas object, which allows for an efficient management of the images to be processed. Pixel-level accesses to the content of a canvas object is possible, thus largely simplifying the implementation of image processing operations. Therefore, the container is adequate to carry out map captures (snapshots), to access information of each pixel of the capture, to transfer all such information to the server layer, and to save the obtained information (processed images). As noted above, a stack of images is obtained as an outcome with as many layers as the classes identified by the processing algorithms k-means and ISODATA. The obtained layers can be merged in order to simplify the interpretation of the obtained results. To achieve the aforementioned functionality, the only requirement at the client layer is the use of browsers that support HTML5. Some browsers currently support some (but not all) of the features in HTML5. One of the key features that client browsers must TMF MII, UEX 2012 Ángel Ferrán Frías 27 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web support in the context of our application is the so-called attribute crossOrigin of the image object in HTML18. Essentially, if this feature is not supported then the application will display a security error and will not work correctly. On the other hand, it is worth noting that our application is fully accessible from mobile devices: although the application is developed to be accessed primarily from the browser of a personal computer, it is also operational on mobile devices such as cell phones or tablets, as far as these devices use browsers that support HTML 5. For illustrative purposes, Fig. 6 shows an example of the designed GUI application. As shown by Fig. 6, the GUI of our application has been designed to be quite simple. It consists of a single web page with a working panel, a container of maps, and a capture container. The work panel allows creating maps, updating the captures of a given map, changing the zoom level, and select processing parameters for the k-means, ISODATA and spatial postprocessing algorithms implemented for image analysis tasks in the current version of the application. The map container can hold multiple maps of individual sizes, while the capture container allows several captures of the same map. Different captures of the same map always have the same size as the original map size. 18 http://www.w3.org/TR/cors TMF MII, UEX 2012 Ángel Ferrán Frías 28 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Figure 6: Graphical user interface of our designed application. To conclude this subsection, Fig. 7 shows a view of our application in which the management of different layers is illustrated. In the considered example, we show how an image has been processed and several classes have been identified by one of the considered processing algorithms. The system allows showing, hiding and merging of the different classes identified by such processing algorithms. The colors associated to these classes can also be edited and completely personalized. The layers can be superimposed on the original image (capture) to be processed, thus generating a final product which comprises an unsupervised classification of a certain area whose location, size, dimensionality, zoom level, etc. are defined by the end-user. TMF MII, UEX 2012 Ángel Ferrán Frías 29 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Figure 7: An example illustrating the management of different layers in the considered application. 3.3. Image processing Two different modules are devoted to image processing tasks within our system. On the one hand, the web server is responsible for receiving the image, processing it in accordance with the methodologies implemented in the system, and then forwarding the obtained result to the client layer. On the other hand, the compute server is in charge of the actual processing of the image (e.g. applying the considered clustering and spatial post-processing algorithms) in efficient fashion. In the following we describe in more detail the image processing tasks at bot layers with particular attention to describing how image processing requests are handled. 3.3.1. Handling image processing requests The main task of the web server is to receive requests from the clients. Such requests are handled as follows. First, the client selects the image capture to be processed and an access to a canvas object in HTML5 is performed. From this access the image content is TMF MII, UEX 2012 Ángel Ferrán Frías 30 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web extracted using a method called toDataURL of the canvas object. In this way the image content can be then encapsulated into an Ajax request together with all processing options, and sent to the compute server in asynchronous fashion using the HTTP protocol, and specifically a function called post. Once the web server has received the full request, a PHP funcion is used for receiving the image to be processed and the parameters needed for such task (number of classes, number of iterations, etc.) Then the compute server assigns a timestamp to the image in order to have it uniquely identified. Then the image is stored into a temporary folder. Finally the web server calls the compute server indicating the location and unique identification of the image. so that the data can be efficiently processed by the compute server (both the web server and the compute server can access the image structure and its particular location). Finally the compute server generates a final product (in our case, the processed image) from the information received, and stores the output in another temporary location. After the processing task has been completed, the web server takes again the control. It collects the final product generated by the compute server and sends it to the client in response to the original Ajax request originated at the client layer, thus closing the communication cycle with the client that originated the request. 3.3.2. Performing the actual image processing task In this subsection we describe in more details how the actual image processing task is performed at the compute server. In our system we use a high-level programming language such as C++ to perform the analysis of the input image, thus producing a final product (processed image) which is stored in a different location. As described in the previous subsection, the communication between the system layers is performed using system calls from the web server to the compute server, passing the information related with the timestamp identification and location of the original image as additional parameters. The compute server sends a signal to the web server indicating that the processing has been completed when the image has been analyzed, and also provides the identification and location of the resulting final product. A very important aspect of the layering structure adopted by our proposed system is that it is highly modular and scalable, since the system calls (in our case confined within the same machine as the web and compute server are implemented as a unique computing resource in our architecture) can be adapted to more complex and parallel processing environments, TMF MII, UEX 2012 Ángel Ferrán Frías 31 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web such as the adopted multi-GPU system which will be fully exploited in future developments of the proposed system. For illustrative purposes, Fig. 8 graphically summarizes the whole image processing strategy adopted by our proposed system, from the generation of the initial request and its placement into a canvas object that contains the image to be processed, to the generation of an Ajax request in order to start the processing cycle at the web server, and ultimately to the execution of the request and the compute server and the provision of the final product (processed image) back to the client that initiated the request. An important final step of the process is to overlay the final product with the original image to be processed. As indicated by Fig. 8 this is done at the client, once the processing cycle has been finalized. The method used to perform this task is the one called putImageData which is also a method of the canvas object. Fig. 8 reveals a highly modular design with clearly defined interactions between the different layers of the system. Finally, Fig. 9 shows a processing example of an image captured from Google Maps corresponding to the Iberian Peninsula. As indicated by Fig. 8 many classes could be identified in the considered test case, including different classes in the water areas. Visually, it can be seen that the combination of classes (a functionality that is also included in the proposed system) can lead to improved results by joining different classes (such as those belonging to water). Figure 8: A summary of the whole image processing strategy adopted by our proposed system. TMF MII, UEX 2012 Ángel Ferrán Frías 32 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Figure 9: Processing example, using the proposed system, of a Google Maps image of the Iberian Peninsula. The example shows that the classification can be refined by merging classes. 3.3.3. Saving the final obtained results We devote this section to the saving of the final results as it required a special treatment in the proposed system implementation. Specifically, the generated product is not stored in any server when the processing is completed, and it is only located in the local memory of the browser of at the client. In addition, the obtained results can be expressed in different forms, e.g. as a processed image, as a collection of layers that can be superimposed with the original data set, or as a combination of both. In order to handle the treatment of the obtained results, two specific actions have been implemented in the proposed system: 1. A JavaScript library (called canvas2image) has been used to save the contents of the canvas object in the local devide using different image formats, such as JPEG, PNG or Bitmap. 2. In order to save the combined result after putting together different layers of the obtained results into the canvas object, we have used another canvas container which integrates all the data layers to be displayed. Once the image is saved the initial container is not retained. This process is transparent to the user and it is also optimized from the viewpoint of computational performance. For TMF MII, UEX 2012 Ángel Ferrán Frías 33 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web illustrative purposes, Fig. 10 shows a graphical illustration of the content of a canvas object, which is the container of both the original image capture and also of the processed image, which can be decomposed in the form of different layers after the processing is completed. Figure 10: Structure of the canvas object that contains the initial image to be processed and the outcome of the processing. 4. Experimental results In this section, we perform an experimental validation of our developed system using satellite images obtained from Google Maps engine across different locations. The validation is conducted by means of the following experiments: 1. In the first experiment, we conduct an experimental validation of the k-means unsupervised classification algorithm by selecting a satellite image over an urban area (Pavia city, Italy) which represents a challenging classification TMF MII, UEX 2012 Ángel Ferrán Frías 34 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web scenario due to the presence of complex urban features. The validation has been conducted by evaluating the agreement between the classification results provided by our implemented versions of k-means with regards to those available in the well-known ENVI commercial software package. In our tests, we adopt exactly the same parameters when running our implementations and those available in the ENVI package. 2. In a second experiment, we conduct a similar analysis using a satellite image collected over the city of Mérida, Spain. This area contains archeological remains from ancient Rome and has been used in order to evaluate the possibility of using the proposed web-based tool in the context of archeologicaloriented remote sensing applications. In this experiment, we also evaluate the impact of using the ISODATA algorithm and a spatial post-processing over the considered processing chain. This experiment is based on visual assessment of the classification results obtained for the satellite images considered in previous experiments. 3. While in the previous two experiments the analyses were conducted using Google Maps images obtained at the highest level of zoom available, in a third experiment we process a satellite image obtained over the Amazon river in South-America, using a higher zoom level in order to evaluate the feasibility of using the proposed web-based tool to process much larger areas covering a wide extension of the surface of the Earth. In this experiment we also evaluate the computational performance of the server-client architecture developed for fast processing of massive data sets. 4.1. Experiment 1: Validation of the k-means unsupervised classification algorithm For this experiment, we have selected a satellite image over an urban area collected over the city of Pavia, Italy [see Fig. 11(a)]. This area represents a challenging classification scenario due to the presence of complex urban features. The spatial resolution of the image is approximately 1.2 meters per pixel. Fig. 11(b) shows the unsupervised classification result obtained by the proposed processing chain, using the well-known kmeans algorithm, implemented to search for a total of c=6 clusters [11]. No spatial postTMF MII, UEX 2012 Ángel Ferrán Frías 35 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web processing is performed in this experiment in order to evaluate the spectral clustering performance of the algorithm without including any spatial information. (a) (b) (c) Figure 11. (a) Satellite image collected over the city of Pavia, Italy. (b) Classification using our processing chain implemented with k-means and c=6 classes. (c) Classification using ENVI’s k-means implemented with the same parameters. TMF MII, UEX 2012 Ángel Ferrán Frías 36 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Table 1. Percentage of agreement (in terms of individual classes and also from a global point of view) after comparing the classification map in Fig. 11(b), produced by our tool (with the k-means algorithm) with the classification map in Fig. 11(c), produced by ENVI. Water Arid soil Grove Urban areas Semiarid soil Urban areas Overall (Cyan) (Grey) (Red) #1 (Orange) (Yellow) #2 (Green) agreement 100.00 78.64 90.40 75.65 81.79 75.01 83.58 Table 2. Confusion matrix obtained after comparing the classification map in Fig. 11(b), produced by our system (with the k-means algorithm) with the classification map in Fig. 11(c) produced by ENVI. Class Water Water Arid soil Grove Urban areas Semiarid Urban areas (red) (Magenta) (Green) #1 (Yellow) soil (Blue) #2 (Cyan) 99,927 0 5,562 0 0 0 0 12,970 0 0 0 0 0 0 52,368 0 11,933 0 0 0 0 49,938 0 13,520 0 0 0 16,073 53,607 0 0 3,523 0 0 0 40,579 (Cyan) Arid soil (Grey) Grove (Red) Urban areas #1 (Orange) Semiarid soil (Yellow) Urban areas #2 (Green) TMF MII, UEX 2012 Ángel Ferrán Frías 37 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Finally, Fig. 11(c) shows the classification result obtained by the k-means algorithm implemented by Research Systems ENVI software19, using also c=6 classes. As shown by comparing Figs. 11(b) and 11(c), the color labels obtained in the different classification results are different, but the classification maps provided by our processing chain applied to the original satellite image in Fig. 11(b) and by ENVI’s implementation of k-means in Fig. 11(c) are very similar. Table 1 reports the classification agreement (in percentage) [3] measured after comparing our processing chain result, based on k-means classification, with the one obtained by ENVI (assuming the latter as the reference). As shown by Table 1, the agreement between the obtained classification maps is always very high regardless of the labeling of the classes. This is also confirmed by the confusion matrix [27] displayed in Table 2. This experiment reveals that our k-means classifier is very similar to the one available in the commercial (ENVI) software. 4.2. Experiment 2: Validation of the ISODATA algorithm with spatial post-processing In this second experiment, we use a satellite image collected over the city of Mérida, Spain [see Fig. 12(a)]. The spatial resolution of the image is quite high, with approximately 1.2 meters per pixel. Specifically, the image in Fig. 12(a) was collected over the Roman Theater of Mérida, a construction which dates from the years 16 and 15 BC and which has undergone several renovations. The theatre is located in the archaeological ensemble of Mérida, one of the largest and most extensive archaeological sites in Spain. It was declared a World Heritage Site by UNESCO in 1993. The theatre was located on the edge of the Roman city by the walls. The grandstand consists essentially of a semicircular seating area (cavea), with capacity for 6,000 spectators eventually divided into three zones: the lowest tier called the ima cavea (22 rows), the medium tier called the media (5 rows) and a top tier called the summa, the latter in very poor state at present. Besides being the most visited monument in the city, since 1933 it is home to the development of a Festival of Classical Theatre, thus returning to its original function and transcending the mere ornament. In this experiment, we have selected this historical monument as an example of remotely sensed archeology, and have decided to adopt an improved view offered by Google 19 http://www.exelisvis.com/language/en-us/productsservices/envi.aspx TMF MII, UEX 2012 Ángel Ferrán Frías 38 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Maps in order to better visualize the structure and scale of this highly relevant monument for the city of Extremadura, Spain. (a) (b) (c) (d) (e) Figure 12. (a) Satellite image collected over the Roman city of Mérida, Spain. (b) Classification using our processing chain with ISODATA. (c) Classification using ENVI’s ISODATA. (d) Classification using our processing chain with ISODATA with spatial post-processing. (e) Classification using ENVI’s ISODATA with spatial postprocessing. TMF MII, UEX 2012 Ángel Ferrán Frías 39 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Table 3. Percentage of agreement after comparing the classification map in Fig. 12(b), produced by our tool (with ISODATA), with the classification map in Fig. 11(c), produced by ENVI, and after comparing the map in Fig. 12(d) produced by our tool (with spatial post-processing) with the classification map in Fig. 12(e) produced by ENVI (also with spatial post-processing). Clustering Sand Structure Trees algorithm (red) ISODATA Shadow Rocks Pavement Overall (cyan) (grey) (yellow) (green) (orange) agreement 87.90 89.23 93.64 100.00 84.56 91.33 91.11 ISODATA with 79.48 91.09 87.02 98.42 79.32 89.36 87.45 spatial postprocessing Table 4. Confusion matrix obtained after comparing the classification map in Fig. 12(b), produced by our system (with ISODATA) with the map in Fig. 12(c), produced by ENVI. Class Shadow Structure Trees Shadows Rocks Pavement (yellow) (magenta) (grey) (red) (blue) (orange) 35,986 0 0 0 0 5,248 0 17,298 0 0 0 0 0 0 40,335 0 5,187 0 Shadows (yellow) 0 0 2,739 45,373 0 0 Rocks 4,951 0 0 0 25,947 0 0 2,088 0 0 0 55,298 Sand (red) Structure (cyan) Trees (grey) (green) Pavement (orange) TMF MII, UEX 2012 Ángel Ferrán Frías 40 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Table 5. Confusion matrix obtained after comparing the classification map in Fig. 12(d), produced by our system (with ISODATA plus spatial post-processing), with the classification map in Fig. 12(e), produced by ENVI. Class Sand Shadow Structure Trees Shadows Rocks Pavement (yellow) (magenta) (grey) (red) (blue) (orange) 32,503 77 336 137 494 4,935 515 17,547 122 30 246 924 186 20 37,425 198 4,524 51 60 12 3,703 46,062 199 26 6,189 57 1,261 287 21,590 751 1,440 1,550 158 88 165 56,132 (red) Structure (cyan) Trees (grey) Shadow (yellow) Rocks (green) Pavement (orange) 4.3. Experiment 3: Performance of the client-server architecture In this experiment we evaluate the performance of the system in terms of computational cost and processing time. The experiment consists of two main parts. First, we evaluate the performance of the proposed application using a web/compute server and three different client configurations (medium, high and very high quality of access to the Internet). Then, we discuss the impact of using a local compute server or a remote server in experiments. In all cases we use a satellite image collected by the Amazon river in South-America, using different zoom levels to illustrate the impact of this parameters which was fixed in the two previous experiments when performing the TMF MII, UEX 2012 Ángel Ferrán Frías 41 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web image capture (snapshot) in the Google Maps engine. For illustrative purposes, Fig. 13(a) shows the image to be processed at a given zoom level. Fig. 13(b) shows the obtained processing result, using the k-means algorithm with c=6 classes and without spatial post-processing. Table 6 summarizes the different zoom levels that will be considered in our experiments with this scene. The table indicates the spatial resolution of each image (depending on the considered zoom level) and the size in MB of the captured image at each zoom level. Before describing the obtained timing results, we summarize in Table 7 the client-server configurations adopted in our experimental evaluation. Specifically, Table 7 describes four different scenarios given by different processing speeds, where the “PC home” scenario can be considered of medium quality, the “PC work” scenario can be considered of high quality, and the “UEX LAN” and “Server UEX LAN” scenarios can be considered of extremely high quality (in terms of bandwidth transmission). (a) (b) Figure 13. (a) Satellite image collected over the Amazon river in South-America. (b) Classification using our processing chain with k-means. TMF MII, UEX 2012 Ángel Ferrán Frías 42 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Table 6. Different zoom levels considered in the experiments with a satellite image over the Amazon river in South-America and available in Google Maps. Considered zoom level Image size (MB) Dimensions (pixels) Zoom 1 0,20 600 x 150 Zoom 2 0,50 1200 x 300 Zoom 3 2,59 2400 x 600 Zoom 4 10,00 4800 x 1200 Table 7. Different scenarios used in the computational performance evaluation of our system. Settings CPU External LAN External LAN UEX LAN Server UEX (PC home) (PC work) Intel Core 2 Intel Core 2 Intel Core 2 Duo, 2 x QuadCore Duo, 3 GHz Duo, 3 GHz 2.53 GHz Intel Xeon LAN 2.26GHz Main 6 GB 4 GB 4 GB 12 GB Google Chrome Google Chrome CentOS 6.2 memory Client Google Chrome Google Chrome browser Operating Windows Vista Windows Vista Windows 7 system Business 32 Business 32 Professional 64 Bits Bits bits 36000 Kbps 36000 Kbps 13258 kbps 100 Mbps 1100 Kbps 1100 Kbps 10593 Hbps 100 Mbps Internet down Internet up TMF MII, UEX 2012 Ángel Ferrán Frías 43 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Table 8 shows the timing results obtained for the “PC home” (medium quality) scenario after processing the satellite image in Fig. 13 (with different zoom levels) using kmeans with and without spatial post-processing. The measured times are subdivided into three stages: 1) the time for sending the image from the client to the server for processing; 2) the waiting time since the image is sent from the client till the client receives a response after the image has been processed; and 3) the time needed to receive the image. Similarly, Table 9 shows the timing results obtained for the “PC work” (high quality) scenario after processing the same image. Finally, Table 10 shows the timing results obtained for the “UEX LAN” (extremely high quality) scenario after processing the same image. In all cases, we can observe how the processing complexity increases with the image size (i.e. with the considered zoom level). It is also remarkable that the spatial post-processing does not significantly increase the computational complexity (despite the relatively large size of the spatial window adopted in experiments, with 7x7 pixels). Another important observation is that, as the quality of the used configuration is increased, the processing times can be significantly reduced although the proposed system performs adequately in all cases. This indicates the portability of the proposed system to different quality configurations. Table 8. Timing results obtained for the “PC home” scenario. Without spatial post-processing Spatial post-processing (7x7 window) Event Send Waiting Image Zoom Image Total Receive Send Waiting Image Image Total Receive 2 2,6 0,125 4,725 2 2,64 0,132 4,772 7,74 9,29 0,225 17,255 7,69 9,61 0,222 17,522 30,14 33,59 1,012 64,742 30,17 34,86 0,735 65,765 114 156 3,2 273,2 114 156 3,1 273,1 1 Zoom 2 Zoom 3 Zoom 4 TMF MII, UEX 2012 Ángel Ferrán Frías 44 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Table 9. Timing results obtained for the “PC work” scenario. Without spatial post-processing Spatial post-processing (7x7 window) Event Send Waiting Image Image Total Receive Send Waiting Image Image Total Receive Zoom 1 0,295 2,28 0,107 2,682 0,354 1,43 0,103 1,887 Zoom 2 0,793 8,76 0,198 9,751 0,81 9,06 1,91 11,78 Zoom 3 2,39 33,03 0,337 35,757 2,45 34,29 0,335 37,075 Zoom 4 8,75 90 0,7 99,45 8,73 96 0,72 105,45 Table 10. Timing results obtained for the “UEX LAN” scenario. Without spatial post-processing Spatial post-processing (7x7 window) Event Send Waiting Image Image Total Receive Send Waiting Image Image Total Receive Zoom 1 0,062 1,93 0,014 2,006 0,062 1,93 0,014 2,006 Zoom 2 0,125 3,33 0,032 3,487 0,125 3,33 0,032 3,487 Zoom 3 0,247 20,01 0,062 20,319 0,247 20,01 0,062 20,319 Zoom 4 0,734 84 0,126 84,86 84 0,126 84,86 TMF MII, UEX 2012 0,734 Ángel Ferrán Frías Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web For illustrative purposes, Fig. 14 shows a comparison between the timing results obtained in the three considered scenarios (reported on Tables 8-10) with and without spatial post-processing. From Fig. 14, several important conclusions can be derived. First and foremost, it is clear that the processing time of the application depends on the type of internet connection. Second, the processing time depends largely on the size of the image to be processed. As indicated in Fig. 14, this time will grow significantly as the zoom level becomes more detailed, in particular for the medium-quality scenario. Finally, it is also clear from Fig. 14 that the spatial post-processing increases the execution time but not significantly, regardless of the quality of the connection available. Seconds No Post-Processing 300 250 200 150 100 50 0 Zoom 1 Zoom 2 Zoom 3 Zoom 4 Pc-Home 4,725 17,255 64,742 273,2 Work 2,682 9,751 35,757 99,45 Lan - Uex 2,006 3,487 20,319 84,86 Post-Processing 7x7 Seconds 45 300 250 200 150 100 50 0 Zoom 1 Zoom 2 Zoom 3 Zoom 4 Pc-Home 4,772 17,522 65,765 273,1 Work 1,887 11,78 37,075 105,45 Lan - Uex 2,006 3,487 20,319 84,86 Figure 14. Comparison of the timing results obtained in the three considered scenarios (reported on Tables 8-10) with and without spatial post-processing. TMF MII, UEX 2012 Ángel Ferrán Frías 46 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Table 11. Timing results obtained when the compute server is implemented in the local machine. Without spatial post-processing Spatial post-processing (7x7 window) Zoom 1 0,023 5,20 0,013 5,236 0,048 4,01 0,021 4,079 Zoom 2 0,032 22,22 0,035 22,287 0,045 23,60 0,030 23,675 Zoom 3 0,190 102,37 0,075 102,635 0,224 102,9 0,061 103,19 Zoom 4 0,931 318,3 0,129 319,360 0,982 452,1 0,188 453,27 Table 12. Timing results obtained when the compute server is implemented as a (remote) cluster. Without spatial post-processing Spatial post-processing (7x7 window) Zoom 1 0,062 1,93 0,014 2,006 0,062 1,93 0,014 2,006 Zoom 2 0,125 3,33 0,032 3,487 0,125 3,33 0,032 3,487 Zoom 3 0,247 20,01 0,062 20,319 0,247 20,01 0,062 20,319 Zoom 4 0,734 84 0,126 84,86 0,734 84 0,126 84,86 To conclude this section, we perform a comparison between the processing time invested by the proposed system to perform the same image processing task described in this subsection if the compute server is implemented in a local machine with regards to the actual implementation, in which the compute server is implemented in a remote machine. Table 11 shows the processing times measured for the considered image processing scenario when the compute server is implemented in the local machine, while Table 12 reports the timing results for processing the same scene when the compute server is a remote (cluster) system. After comparing Tables 11 and 12, we can observe the significant improvements achieved by implementing the compute server as TMF MII, UEX 2012 Ángel Ferrán Frías Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web a remote (cluster), which offers the possibility to reduce the processing times very significantly. These improvements are graphically illustrated in Fig. 15, which reveals that the following main observations: 1) when the compute server is implemented as a local machine, the processing times are always much higher than using a remote server, even if the local processing removes communication times over the network since all work is performed on the same machine; and 2) the larger the image size, the higher the times measured for the local processing while the remote processing times do not increase so significantly. This reveals that the use of a dedicated, high-performance compute server (cluster) offers important advantages from the viewpoint of the computational efficiency of the considered application. In this case, an internet LAN connection is recommended in order to keep the communication times within reasonable levels. Seconds No Post-Processing 350 300 250 200 150 100 50 0 Zoo m1 Zoo m2 Zoo m3 Zoo m4 Local Server 5,236 22,287 102,635319,360 Remote Server 2,006 3,487 20,319 84,86 Post-Processing 7x7 Seconds 47 500 400 300 200 100 0 Zoo m1 Zoo m2 Zoo m3 Zoo m4 Local Server 4,079 23,675 103,185 453,27 Remote Server 2,006 3,487 20,319 84,86 Figure 15. Comparison of the timing results obtained by the proposed system when the compute server is implemented as a local machine or as a (remote) cluster. TMF MII, UEX 2012 Ángel Ferrán Frías 48 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web 5. Conclusions and future research lines This paper has described a new web-based system for computationally efficient processing of satellite images from Google Maps engine. The system has been developed using the Google Maps applications programming interface (API), and incorporates functionalities such as unsupervised classification of image portions selected by the user (at the desired zoom level) using the k-means and ISODATA clustering algorithms, followed by spatial post-processing. Most importantly, the processing of satellite images is conducted by means of a centralized server which receives the image to be processed, performs the analysis in computationally efficient fashion in a cluster of commodity graphics processing units (GPUs), and returns the classification result to the end-user. This represents an improvement over a previously development desktop application presented in [9]. Our experimental results, conducted by comparing the obtained classification results with those provided by commercial products such as the popular ENVI software package, reveal that the proposed webbased tool provides classification maps of high similarity with regards to those provided by ENVI for the same satellite imagery, but with the possibility to perform classification of any image portion available in Google Maps engine. This work will be first presented to the community in the form of a conference publication [28]. A peer-reviewed journal contribution describing the system in detail is already in process [29]. In the future, we plan to incorporate other advanced classifiers to the proposed webbased system, such as random forests and support vector machines (SVMs). Also, we would like to extend the developed tool with the incorporation of content-based image retrieval (CBIR) functionalities. For that purpose, the strategy will be based on a query system linked to feature extraction from an image repository (such as Google Maps). The retrieved features (which will comprise shape descriptors, texture features, etc.) will be stored in a database of features and used to compare the feature vector of the input query with those recorded in the database by means of a similarity function, which will provide a result to the end-user in the form of image portions (across different locations) with sufficient similarity with regards to the features in the input query. This strategy is TMF MII, UEX 2012 Ángel Ferrán Frías 49 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web illustrated in Fig. 16, which suggests an overall architecture for a future CBIR system based on remote queries to an image repository which performs feature extraction tasks in order to catalog the remotely sensed images through a vector of features, which can then be used to peform the search in a database of feature vectors by means of a carefully selected similarity function. Incorporating such CBIR architecture to our proposed system will be the focus of our future research developments. Figure 16: An overview of the different modules that we plan to develop in order to include the functionality of content-based image retrieval (CBIR) in future developments of our proposed web-based application. TMF MII, UEX 2012 Ángel Ferrán Frías 50 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web TMF MII, UEX 2012 Ángel Ferrán Frías 51 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Annexes A) User Manual A.1. Introducción Este Manual de usuario explica el manejo y funcionamiento de la Aplicación WPMS. Inicialmente se explicará qué es y para qué sirve la Aplicación WMPS para, posteriormente, realizar un recorrido por las funcionalidades de la Aplicación detallando su funcionamiento, configuración y opciones de procesamiento. A.1.1 ¿Qué es WMPS? WMPS es una aplicación WEB para el procesamiento de imágenes obtenidas desde repositorios de imágenes satélites disponibles de forma gratuita en Internet. Esta aplicación utiliza, así, el repositorio facilitado por Google Maps TM. La Aplicación proporciona acceso a cualquier imagen disponible desde Google Maps y permite, posteriormente, que estas puedan ser procesadas y clasificadas según ciertos algoritmos de clasificación. Actualmente están disponibles los algoritmos o procesos Kmeans e Isodata. El sistema está abierto a futuras líneas de desarrollo para la incorporación de nuevos procesos de clasificación y funcionalidades. A.2. Acceso a la Aplicación La aplicación está alojada actualmente en un servidor perteneciente al centro de investigación CETA-CIEMAT. Se ha contado con la colaboración, muy activa, por parte de este centro lo que ha permitido utilizar los servidores existentes en sus instalaciones y que son de gran potencia de cálculo, lo que facilita el uso del sistema por la celeridad de las operaciones de procesamiento que se utilizan en dichos servidores. El acceso a la aplicación está actualmente permitido únicamente al personal de Investigación de la Universidad de Extremadura, no obstante, en un futuro se plantea el acceso a la misma para el público en general. La dirección actual de la aplicación es la siguiente: http://login-hpc.ceta-ciemat.es/hypercomp/Wmps/Wmps.html TMF MII, UEX 2012 Ángel Ferrán Frías 52 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web A.3. Configuración Existen algunos valores de configuración en el sistema. Estos valores son, esencialmente, características predeterminadas para la carga de mapas y para el procesamiento de las capturas realizadas. A continuación se indican la configuración de las variables que pueden configurarse en el sistema mediante esta configuración con sus correspondientes valores. configuration.defaultWidhImage='200' configuration.defaultHeightImage='300' configuration.defaultLongitud='39.30993' configuration.defaultLatitud='-4.5820' configuration.defaultMapZoom=5 configuration.defaultNumberClasses=7 configuration.defaultIterMax=15; configuration.defaultKmeansPP='5x5' configuration.defaultIsodataPP='OFF' configuration.defaultIsodataOptions={ max_pares_union:5, min_porc_muestra:2, max_desv_estandar:1, min_distancia_clases:3 } //Valor Por defecto del Ancho de Mapa //Valor Por defecto del Alto de Mapa //Valor Por defecto de Longitud del Mapa //Valor Por defecto del Latitud del Mapa //Valor Por defecto del Zoom de Mapa //Valor Por defecto del Nº Clases para //Procesamientos Kmeans e Isodata //Valor Por defecto de Iteraciones Máximas //para procesamiento Kmeans e Isodata //Valor Por defecto de Post-Procesado Kmeans //Valor Por defecto del Post-Procesado Isodata //Otros valores por defecto del procesado // Isodata Actualmente la configuración de estos valores es común para todos los usuarios y es administrada, por tanto, por el administrador del sistema. En un futuro se prevé que sea única por usuario y gestionada, así, por el mismo. A.4. Barra de Herramientas La barra de herramientas de la aplicación es el contenedor de las funcionalidades que provee el sistema. De ella es de donde se pueden crear mapas, capturas, controlar el nº de clases de procesamiento, etc. A continuación se detalla cada función que puede realizarse mediante la barra de herramientas. Estas funciones están habilitadas mediante iconos activos que interaccionan con las pulsaciones del usuario. TMF MII, UEX 2012 Ángel Ferrán Frías 53 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web A.4.1. Creación de Mapas Mediante este icono, al pulsarlo, se crear un nuevo mapa interactivo con el usuario. Este mapa es proporcionado por Google Maps. La creación de mapas permite, así mismo, otras opciones, como las que se muestra a continuación: Alto del mapa (se carga con el valor por defecto) Ancho del mapa (se carga con el valor por defecto) Nombre del Mapa Latitud del Mapa (se carga con el valor por defecto) Longitud del Mapa (se carga con el valor por defecto) Nivel de Zoom del Mapa (se carga con el valor por defecto) Descripción Al pulsar el botón de Aceptar se crea un nuevo mapa en el contenedor de mapas del sistema con los valores introducidos. El contenedor de mapas es la parte superior de la pantalla que contiene una pestaña por cada mapa creado en el sistema, como se presenta en la imagen siguiente. TMF MII, UEX 2012 Ángel Ferrán Frías 54 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web A.4.2. Obtención de Capturas Las capturas son “fotos” estáticas de los mapas. Estas capturas permiten obtener una imagen fija del mapa visible y posteriormente ser procesadas mediante alguna función de clasificación de las existentes en el sistema (actualmente Kmeans e Isodata). Para cada Mapa pueden realizarse tantas capturas como se desee. Por tanto existirá otro contenedor de capturas para cada contenedor de mapas. Icono creador de Capturas Contenedor de Capturas A.4.3. Actualizar Capturas Mediante esta acción se actualiza la captura actualmente seleccionada (si existe alguna) con el contenido del mapa seleccionado en ese momento. Es como un “refresco” de la captura original. A.4.4. Manejo de Nivel de Zoom El nivel de Zoom controla el zoom del mapa activo. Éste se controlar mediante dos eventos, por una lado el propio botón de “+” y “-” y mediante el ratón sobre el propio mapa, funcionamiento estándar de los mapas de Google Maps. La etiqueta de Zoom nos indica en todo momento el zoom en el que se encuentra el mapa, ya se actualice éste tanto por los propios botones de incremento y decremento como por el evento del ratón sobre el propio mapa TMF MII, UEX 2012 Ángel Ferrán Frías 55 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web A.4.5 Procesado K-Means El procesado Kmeans es uno de los dos algoritmos de clasificación no supervisados que actualmente ejecuta el sistema. Consiste en obtener, dada una imagen, otra nueva imagen cuyos pixeles son agrupados dependiendo del color de los mismos. Se realiza una agrupación de pixeles y se asigna un color concreto a cada grupo de pixeles de colores parecidos. La imagen que se obtiene es una representación de la original que puede utilizarse posteriormente para realizar búsquedas por contenidos. Estas búsquedas se permitirán en una futura versión del sistema. Este proceso se ejecuta en un servidor externo y el tiempo de procesamiento dependerán tanto de las características de este servidor como del tamaño de la imagen a clasificar. Para imágenes no muy grandes (de hasta 1200 x 600) el tiempo estimado de procesamiento son algunos segundos. Este procesado tiene algunos parámetros que se indican en la barra de herramientas: Nº de Iteraciones Máximas: valor técnico del algoritmo de procesado Nº de Clases: número de grupos de pixeles resultantes (en el sistema se identificarán con colores) Opción de Post-Procesado: valor técnico para el algoritmo. Se selecciona del desplegable existente junto al botón de procesamiento Kmeans Botón de procesado y opción de post-procesado A continuación se muestra un ejemplo de procesamiento del mapa de España y la imagen correspondiente: Figura A.1: Ejemplo de procesamiento de imagen TMF MII, UEX 2012 Ángel Ferrán Frías 56 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web A.4.6. Procesado Isodata El procesado Isodata es otro algoritmo de clasificación de imágenes. Es muy semejante al Kmeans señalado anteriormente. La forma de obtener las imágenes que devuelve este procesado es mediante el botón Isodata, que en este caso conlleva algunos otros parámetros, aparte de los parámetros indicados anteriormente para el procesamiento Kmeans y que son comunes (Nº clases, Iteraciones Máximas) . Son parámetros técnicos de entrada al algoritmo y se indican a continuación: Figura A.2: Opciones de Procesamiento de Algoritmo Isodata A.4.7. Gestión de Clases El botón de Clases permite aumentar o disminuir el nº de clases de agrupamiento que indicábamos anteriormente. Eso por una parte, pero por otra, al pulsar sobre la etiqueta propia de clases se abrirá una ventana que muestra las clases existentes, el olor asignado a cada clase y si esa clase está o no visible. Una clase visible mostrará su propio color e invisible no mostrará ninguno, pudiendo verse la imagen original en los pixeles que conforman la clase. También es posible modificar los colores(R, G, B) de cada clase eligiendo el usuario el valor de cada componente. A continuación se muestra una imagen como ejemplo de gestión de clases y otra donde se muestra únicamente 3 clases visibles de la imagen procesada anteriormente de España. TMF MII, UEX 2012 Ángel Ferrán Frías 57 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Figura A.3: Configuración de Capas Figura A.4: Configuración de Capas A.4.8. Centrado del Mapa Centrar un mapa significa posicionar el centro del mapa en unas determinadas coordenadas. Estas coordenadas son la que se indican en los 2 cuadros de texto separados por una coma: TMF MII, UEX 2012 Ángel Ferrán Frías 58 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Control que permite Centrar el Mapa y Obtener las coordenadas del centro del Mapa Actual. Estos cuadros de texto permiten indicar cualquier coordenada y al pulsar sobre el icono de aspas cruzadas se cargarán con las coordenadas del centro del mapa. Como ayuda para obtener coordenadas existen otros dos cuadros de texto e icono que indica en todo momento las coordenadas del mapa conforme el ratón pasa por encima del mismo. El icono de aspas realiza, por otra parte, el centrado del mismo, es decir, centrar el mapa en las posiciones anteriormente indicadas. Control de coordenadas de navegación del ratón y Centrar el Mapa. Estos dos controles, en conjunto, conforman una buena manera de localizar y ubicar cualquier posición de coordenadas del globo terrestre. A.4.9. Guardar Capturas Guardar las capturas es algo fundamental en el sistema. Permite, en todo momento, guardar la captura visible del contenedor de capturas en cualquiera de los siguientes formatos: Bmp, Jpeg, Png. Es necesario indicar que únicamente se guarda una captura o imagen de procesamiento a la vez, no siendo posible guardar todas las imágenes de una sola vez. Es importante señalar, asimismo, que es posible guardar una captura original, una imagen procesada de la misma e, incluso, una mezcla de las mismas (seleccionado algunas clases como no visibles, como en el ejemplo anterior). Icono y botón de guardar imagen y opciones de formato de imagen a guardar. TMF MII, UEX 2012 Ángel Ferrán Frías 59 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web B) Programmer Manual B.1. Introducción Este Manual está orientado principalmente a programadores. Contiene información acerca de la arquitectura, tecnologías y módulos empleados en el desarrollo del sistema WMPS (Web Map Processing Saver). Esta aplicación constituye el TFM del autor en el Máster de Ingeniería en Informática de la Universidad de Extremadura. La aplicación es un desarrollo web que interactúa con mapas disponibles a través de la API V3 de Google Maps, realiza capturas sobre el mismo y procesa esas capturas realizando funciones de procesamiento mediante algoritmos de clasificación. El objetivo del documento es dar una visión global a posibles futuros desarrolladores que puedan realizar tareas tanto de modificación del proyecto inicial como desarrollo de nuevas funcionalidades del mismo. El nivel de detalle del código fuente es medio, de manera que se identifican los módulos del sistema así como las principales funciones y procedimientos del mismo, dejando el nivel de detalla bajo en los comentarios del propio código fuente disponible. Se indica la arquitectura establecida, la tecnología utilizada y los principales módulos de la aplicación. B.2. Arquitectura La arquitectura del sistema se realiza en tres capas, como puede verse en la figura 1. Por un lado está la capa de repositorio de imágenes, Google Maps, por otro la capa cliente, formada por la interfaz de usuario y por último la capa de servidor, formada a su vez por el servidor web y el servidor de cómputo o servidor de procesos. Figura B.1: Arquitectura de capas del Sistema TMF MII, UEX 2012 Ángel Ferrán Frías 60 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web La capa de repositorio de imágenes es la encargada de proporcionar las imágenes que componen un mapa a la capa cliente. Este repositorio puede ser cualquiera de los que están disponibles en internet. En este proyecto se ha decidido utilizar Google Maps, por la sencillez de programación de su API, su potencia y su uso libre y gratuíto. La capa servidor está formada por dos módulos a su vez, el servidor Web y el servidor de cómputo. Actualmente están hospedados en la misma máquina física, un servidor facilitado por el centro de investigación CETA-CIEMAT, colaborador de este proyecto. El servidor Web es Apache 2.2 elegido por su amplia aceptación, facilidad y sencillez de utilización y potencia en la respuesta a peticiones web. En este servidor se aloja la aplicación Web WMPS, corazón del proyecto. El servidor de cómputo está formado por programas de línea de comandos que son ejecutados por páginas alojadas en el servidor Web. Estos programas son los encargados de realizar las funciones de procesamiento de las imágenes. B.3. Tecnología Se ha utilizado en todo el proyecto software libre. La tecnología empleada en el desarrollo del proyecto ha sido la siguiente: JavaScript: lenguaje de programación utilizado en la capa cliente del proyecto debido a su velocidad, amplio uso en desarrollos, de uso libre y gratuito. Facilita mucho el uso de la aplicación al usuario porque responde a los eventos de éste y no requiere llamadas continuas al servidor web, evitando el tráfico de comunicación y acelerando la velocidad de los procesos. Jquery: librería JavaScript que permite manejar de forma más rápida los objetos del DOM e las páginas HTML. Jquery-UI: librería JavaScript que permite crear “widget”, objetos Html con estilo y funcionalidad propia. Se utiliza para crear la interfaz de usuario. Ajax: lenguaje de programación para comunicación asíncrona entre cliente y servidor Web. Se utiliza mediante los objetos XML Http Request y en este proyecto se utiliza para enviar las imágenes a procesar y recibir las correspondientes imágenes procesadas. Php: lenguaje de programación en la parte servidor. Se ha utilizado para programar las páginas alojadas en la aplicación Web que reciben las peticiones del cliente y contentas a las mismas tras realizar llamadas al servidor de cómputo (call a programas de líneas de comandos) TMF MII, UEX 2012 Ángel Ferrán Frías 61 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Html 5: nuevo estándar para visualizar páginas web en internet. Están aún en fase de desarrollo por lo que en algún momento algún componente o desarrollo de la aplicación requeriría ser revisado. Se utiliza Html 5 porque permite, principalmente el uso de objetos Canvas. Estos nuevos objetos nos permiten almacenar imágenes de los mapas de google map. Son contenedores y es la parte fundamental de las páginas Html de este proyecto. Sin estos objetos la aplicación no podría haberse desarrollado. C++: es el lenguaje de programación utilizado en la parte de servidor de cómputo. Concretamente se han desarrollado los programas que analizan y clasifican las imágenes que son enviadas al cliente tras su procesamiento. B.4. Estructura de Ficheros La estructura de ficheros del programa, por capas es la siguiente: Capa Servidor: o Servidor Apache: /htdocs: Carpeta WMPS que contiene: Css Images Js jsGMS ui work Wmps.html Capa Repositorio de Imágenes o Proporcionado por Google Maps. Capa Cliente o En esta capa sólo es necesario acceder a la url de la aplicación Web mediante un navegador que soporte Html 5 (ver requisitos en el punto siguiente). B.5. Requisitos del Sistema Servidor: el sistema se ha desarrollado para poder ser implantado tanto en servidores web de open source, como Apache, como en servidores IIS de Microsoft. En este último caso los programas del servidor de cómputo (Kmeans e Isodata deberían adaptarse al S.O. Windows, puesto que sólo son actualmente operativos en sistemas Linux) TMF MII, UEX 2012 Ángel Ferrán Frías 62 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Cliente: el único requisito para acceder y utilizar la aplicación es utilizar navegadores que soporten HTML 5 desde los dispositivos de accesos, que pueden ser PC, Mac, Tablet o Móvil. Actualmente únicamente soportan las características del sistema los navegadores Moziila Firefox, versión 9.0 o superior y Google Chrome, versión 14.0 o superior. B.6. Instrucciones de Despliegue Para instalar la aplicación los pasos son los siguientes (sistemas Unix/Linux): Instalar servidor Apache Httpd, versión 2.2 o superior Instalar Módulo Php 5.2 o superior Copiar carpeta de aplicación, Wmps, en carpeta de publicación del servidor Web htdocs. Compilar los programas del servidor de cómputo y probarlos en el servidor asignado para procesar las imágenes. Asignar ruta del servidor de cómputo en la página de tratamiento de peticiones del cliente: saveimage.php en carpeta /GMS/work Para instalar la aplicación los pasos son los siguientes (sistemas Windows): Son los mismos pasos que en sistemas Linux/Unix, únicamente es necesario disponer de ficheros ejecutables Kmenas e Isodata compatibles con la plataforma Windows. B.7. Módulos y código Fuente A continuación se indican los módulos de los que está compuesto el proyecto y de cada uno de ellos se destacan las principales funciones y funcionalidades del mismo. En el propio código fuente, disponible, existen comentarios aclaratorios de cada función. En este documento no se incluye, pues, todo el código fuente debido a la gran extensión del mismo. Los principales desarrollos realizados se han programado en JavaScript aparte de la página Html inicial y de la página Php en la parte servidor. Estos lenguajes de programación no soportan la programación a objetos (exceptuando Php), por lo que la implementación se ha realizado mediante programación estructurada, con funciones y llamadas a las mismas. B.7.1. Capa: SERVIDOR Fichero: saveimage.php Descripción: página que recibe la imagen desde el cliente, llama a las funciones de procesados, recibe y devuelve la imagen procesada tras su finalización. TMF MII, UEX 2012 Ángel Ferrán Frías 63 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Funciones Principales: en este caso no existe ninguna función principal. La página únicamente ejecuta una u otra llamada dependiendo de los parámetros pasados: opción Kmeasn o Isodata. Código fuente: if (isset($_POST["op"]) && isset($_POST["id"]) && isset($_POST["imagen"])) { $op=$_POST["op"]; $numclusters=$_POST["numclusters"]; $numiter=$_POST["numiter"]; $colores= json_decode($_POST["colores"]); $id=$_POST["id"]; $image=$_POST["imagen"]; //PASOS COMUNES //1º: obtener image y guardarla en disco $image=substr($image, strpos($image, ",")+1); //2º decode it from base 64 and into image data only $decode=base64_decode($image); $idImgin='inprocess/'.$id.'.png'; $p3x3=$_POST["p3x3"]; $p5x5=$_POST["p5x5"]; $p7x7=$_POST["p7x7"]; $idImgout='outprocess/'.$id.'_out.png'; $fopen = fopen($idImgin, 'wb' ); fwrite( $fopen, $decode); fclose( $fopen ); switch ($op) { case 1: //Operacion KMEANS //3º: Process image //$return=shell_exec('./Kmeans '.$idImgin.' '.$idImgout.' '.$numclusters.' '.$numiter.' '.$p3x3.' '.$p5x5.' '.$p7x7); //$return=shell_exec('./Kmeans '.$idImgin.' '.$idImgout.' 5 15 0 0 1'); //4º: reenvío de id de imagen procesada ob_start(); //Productivo //echo $idImgout; //PreProductivo echo 'outprocess/p.png'; ob_flush(); break; case 2: //Operacion ISODATA //3º: procesamiento de imagen //Parameters for Isodata $max_pu=$_POST["max_pu"]; $min_pmc=$_POST["min_pmc"]; $max_de=$_POST["max_de"]; $min_dc=$_POST["min_dc"]; //$return=shell_exec('./Isodata '.$idImgin.' '.$idImgout.' '.$numclusters.' '.$numiter.' '.$max_pu.' '.$min_pmc.' '.$max_de.' '.$min_dc.' '.$p3x3.' '.$p5x5.' '.$p7x7); $return=shell_exec('./Isodata '.$idImgin.' '.$idImgout.' 5 100 1 5 1 1 0 0 0'); TMF MII, UEX 2012 Ángel Ferrán Frías 64 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web //4º: reenvío de id de imagen procesada ob_start(); //Productivo //echo $idImgout; //PreProductivo echo 'outprocess/p.png'; ob_flush(); break; default: $return=('Error: operacion no definida'); echo $return; break; } } else{ echo ('Error en parametros'); } La funcionalidad de la página radica en los parámetros que debe recibir. En caso de no ser correctos se envía mensaje de error. GMS/work: carpeta de trabajo: o Isodata: fichero de procesamiento de imágenes para el algoritmo Isodata. Facilitado por el Grupo de Investigación de Hypercomp de la Universidad de Extremadura. o Kmeans: fichero de procesamiento de imágenes para el algoritmo Kmeans. Facilitado por el Grupo de Investigación de Hypercomp de la Universidad de Extremadura. GMS/Wmps.html: página web de la aplicación. El sistema de ha desarrollado en una sola página web que interactúa de forma dinámica con el usuario mediante el interface de Jquery y JavaScript. Consta de, principalmente, divs que contiene los objetos del contenedor de mapas y contenedor de capturas, además de código que genera las ventanas de diálogo de la aplicación, para las clases y las opciones deprocesamiento. Código de la página: <!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <title> Web Maps Processing Saver </title> <link type="text/css" rel="stylesheet" href="css/smoothness/jquery-ui1.8.16.custom.css" /> <link type="text/css" rel="stylesheet" href="css/gms.css"> <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script> <script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script> <script type="text/javascript" src="js/canvas2image.js"></script> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> TMF MII, UEX 2012 Ángel Ferrán Frías 65 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web <script type="text/javascript" <script type="text/javascript" <!--<script type="text/javascript" <script type="text/javascript" <script type="text/javascript" src="jsGMS/config.js"></script> src="jsGMS/sources.js"></script> src="jsGMS/kmeans.js"></script>--> src="jsGMS/utils.js"></script> src="jsGMS/jsGM.js"></script> <style> #dialog label, #dialog input { display:block; } #dialog label { margin-top: 0.5em; } #dialog input, #dialog textarea { width: 95%; } #tabs { margin-top: 5px; overflow:auto;} #tabs li .ui-icon-close { float: left; margin: 0.4em 0.2em 0 0; cursor: pointer; } #tabs div { padding: 3px;} #add_tab { cursor: pointer; } .tabs-bottom { position: relative; } .tabs-bottom .ui-tabs-panel { height: 310px; width:1210px; overflow: auto; } .tabs-bottom .ui-tabs-panel { overflow: auto; } .tabs-bottom .ui-tabs-nav { position: absolute !important; left: 0; bottom: 0; right:0; padding: 0 0.2em 0.2em 0; } .tabs-bottom .ui-tabs-nav li { margin-top: -2px !important; margin-bottom: 1px !important; border-top: none; border-bottom-width: 1px; } .ui-tabs-selected { margin-top: -3px !important; } </style> </head> <body> <header> <div id="header1"></div> </header> <div id="all"> <div class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" style="margin-top:5px; margin-left:2px; margin-right:2px; padding:2px"> <!--<input class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" type="button" id="nuevoMapa" value="Map +" /> --> <button id="nuevoMapa">Nuevo Mapa</button> <!--<input class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" type="button" id="nuevaCaptura" value="Capture +" onclick="nuevaCaptura()" /> --> <button id="nuevaCaptura">Nueva Captura</button> <!--<input class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" type="button" id="actualizaCaptura" value="Refresh" onclick="actualizaCaptura()" /> --> <button id="actualizaCaptura">Actualiza Captura</button> <!--<input class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" type="button" id="server" value="Server" onclick="sendImageToServer()" /> --> <span> <button id="saveImage">Salvar</button> <button id="formatImageSave" style="margin-left:-1px">Png</button> </span> <div id="mnu_save" style="padding: 1px; position: absolute; text-align: center;display:none; zindex: 10;"> <ul id="listformatSave" style="padding: 3px;font-size: 1.0em;"> <li class="format_save_li"><input type="radio" id="png" value="Png" name="optionsave" checked="checked"/><label for="png">Png</label></li> <li class="format_save_li"><input type="radio" id="bmp" value="Bmp" name="optionsave"/><label for="png">Bmp</label></li> <li class="format_save_li"><input type="radio" id="jpeg" value="Jpeg" name="optionsave"/><label for="png">Jpeg</label></li> </ul> TMF MII, UEX 2012 Ángel Ferrán Frías 66 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web </div> <!-<input class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" type="button" id="inverseImage" value="Invertir" onclick="inverseImagen()" /> <input class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" type="button" id="BinariceImage" value="Binarizar" onclick="binariceImagen()" /> --> <span> <button id="zoom" class="button-no-mouse-over">Zoom: </button> <button id="zoom-more" style="border-left:none">Más</button> <button id="zoom-less" style="border-left:none">Menos</button> </span> <span> <button id="clases">Clases: </button> <button id="clases-more" style="border-left:none">Más</button> <button id="clases-less" style="border-left:none">Menos</button> </span> <input class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" style="padding-left: 3px; padding-right: 3px;" type="button" id="Iter" value="Iter-Max:" /> <input type="text" name="num_iter_max" id="num_iter_max" value="50" class="ui-widget" maxlength="3" style="width:25px" /> <span> <button id="Kmeans">Kmeans PP-OFF</button> <button id="Kmeans-Options" style="border-left: none">Opciones Post-Procesado Kmeans</button> </span> <span> <button id="Isodata">Isodata</button> <button id="Isodata-Options" style="border-left: none">Opciones Procesado Isodata</button> </span> <div id="mnu_opc_kmeans" style="padding: 1px; position: absolute; text-align: center;display:none; z-index: 10;"> <ul id="listKmeansPP" style="padding: 5px;font-size: 1.0em;"> <li class="kmeans-opt-li"><input type="radio" id="no-pp" data-codPP='0' value="OFF" name="kmeans-options" checked="checked" /><label for="no-pp">Post OFF</label></li> <li class="kmeans-opt-li"><input type="radio" id="pp-3x3" data-codPP='1' value="3x3" name="kmeans-options" /><label for="pp-3x3">Post 3x3</label></li> <li class="kmeans-opt-li"><input type="radio" id="pp-5x5" data-codPP='2' value="5x5" name="kmeans-options" /><label for="pp-5x5">Post 5x5</label></li> <li class="kmeans-opt-li"><input type="radio" id="pp-7x7" data-codPP='3' value="7x7" name="kmeans-options" /><label for="pp-7x7">Post 7x7</label></li> </ul> </div> <button id="buttonGetCenterMap">Obtener Centro del Mapa</button> <input type="text" name="map-lat" id="map-lat" value="" class="ui-widget" maxlength="18" style="width:75px" />, <input type="text" name="map-lon" id="map-lon" value="" class="ui-widget" maxlength="18" style="width:75px; margin-left:-3px;"/> <button id="buttonSetCenterMap">Centrar Mapa</button> <input type="text" name="map-lat-lock" id="map-lat-lock" value="" class="ui-widget" maxlength="18" style="width:75px; background:transparent;" readonly />, <input type="text" name="map-lon-lock" id="map-lon-lock" value="" class="ui-widget" maxlength="18" style="width:75px; margin-left:-3px; background:transparent;" readonly /> <!--<button id="buttonConfiguration" style="position:absolute; right:10px;">Configuración</button> --> </div> <div class="gms"> <div id="tabs" class="tabSup"> TMF MII, UEX 2012 Ángel Ferrán Frías 67 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web <ul> <li><a href="#tabs-1">Mapa España</a> <span class="ui-icon ui-iconclose">Borrar Mapa</span></li> </ul> <div id="tabs-1" class="tabs-h"> <div class="contenedorSup"> <div id="map_canvas1" class="nuevoMapa" style="padding:0px"></div> </div> <div id="tabs-1B" class="tabs-h2 tabs-bottom"> <ul> </ul> </div> </div> </div> </div> </div> <!-- Diálogos--> <div id="dialog-confirm-layer_assign" title="Confirme Acción.-"> <p><span class="ui-icon ui-icon-alert" style="float:left; 0;"></span>¿Desea reasignar la clase?</p> </div> margin:0 7px 20px <!-- Nuevo Mapa --> <div id="dialog" title="Nuevo Mapa"> <form id='form-nuevo-mapa'> <fieldset class="ui-helper-reset"> <input type="hidden" name="tab_idmapa" id="tab_idmapa" value="" class="ui-widget-content ui-corner-all" /> <label for="tab_width">Alto</label> <input type="text" name="tab_width" id="tab_width" value="" class="ui-widget-content ui-corner-all" /> <label for="tab_height">Ancho</label> <input type="text" name="tab_height" id="tab_height" value="" class="ui-widget-content ui-corner-all"/> <label for="tab_title">Nombre</label> <input type="text" name="tab_title" id="tab_title" value="" class="ui-widget-content ui-corner-all" /> <label for="tab_latitud">Latitud</label> <input type="text" name="tab_latitud" id="tab_latitud" value="32.0" maxlength="20" class="ui-widget-content ui-corner-all" /> <label for="tab_longitud">Longitud</label> <input type="text" name="tab_longitud" id="tab_longitud" value="-3.0" maxlength="20" class="ui-widget-content ui-corner-all" /> <label for="tab_zoom">Zoom</label> <input type="text" name="tab_zoom" id="tab_zoom" value="5" maxlength="2" class="ui-widget-content ui-corner-all" /> <label for="tab_content">Descripción</label> <textarea name="tab_content" id="tab_content" class="ui-widgetcontent ui-corner-all"></textarea> </fieldset> </form> </div> <!-- Configuración de Capas --> <div id="dialog-Colors" title="Configuración de Capas"> <div id='form-colors'> TMF MII, UEX 2012 Ángel Ferrán Frías 68 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web <fieldset class="ui-helper-reset"> <legend class="legend">Gestión de visualización y control de capas</legend> <div class="div-colors-container"> <div id="colorsConf"> <div id="colorsConf2_buttom"> <button id="buttonselectclases_all">Todas</button> <button id="buttonselectclases_none">Ninguna</button> </div> </div> <div id="colorsConf2" class="cConf2"> <div class=".ui-widget" style="font-size: 1.75em; height: 35px; margin-left: 15px; margin-top: 10px;"> <legend id="layerToEdit">Capa Seleccionada: Ninguna</legend> <div id="layerSelected" data-color="0" style="background-color: blue; width:20px; height:20px; margin-top:-210px; margin-left: 200px; margintop: -20px;border: 1px solid #C3C3C3;"></div> </div> <div> <div id="layer_edit_remove" class="cConf2" style="margin-top: 10px; width:86%;"> <div id="red"></div> <input id="t_red" type="text" maxlength="3" style="float: left; font-size: 1em; height: 10px; margin-left: 10px; margintop:2px;width:25px;"></input> <div id="blue"></div> <input id="t_blue" type="text" maxlength="3" style="float: left; font-size: 1em; height: 10px; margin-left: 10px; margintop:2px;width:25px;"></input> <div id="green"></div> maxlength="3" style="float: left; top:2px;width:25px;"></input> font-size: 1em; height: <input id="t_green" type="text" 10px; margin-left: 10px; margin<div id="swatch" class="ui-widget- content ui-corner-all"></div> </div> </div> <div style="float:left;margin:5px;padding:10px;text- align:center;width:90%;"> <button id="configureclases_cancel" style="margin-left:20px;">Cancelar</button> <button id="configureclases_ok" style="marginleft:20px;">Actualizar</button> </div> </div> </div> </fieldset> </div> </div> <!-- Opciones de ISODATA --> <div id="dialog-isodata-options" title="ISODATA.-"> <form id='form-isodata-options'> <fieldset class="ui-helper-reset"> <legend class="legend">Opciones de procesamiento.</legend> <div class="div-isodata-options-container" style="height: 50px; line-height: 2.5;"> <label for="post-isodata">Post-Procesado: </label> <select id="post-isodata"> TMF MII, UEX 2012 Ángel Ferrán Frías 69 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web <option id="pp-OFF" data-codPP='0' value="OFF">Post OFF</option> <option id="pp-3x3" data-codPP='1' value="3x3">Post 3x3</option> <option id="pp-5x5" data-codPP='2' value="5x5">Post 5x5</option> <option id="pp-7x7" data-codPP='3' value="7x7">Post 7x7</option> </select> <br> <label for="max_pares_union">Máximo pares por unión:</label> <input type="text" name="max_pares_union" id="max_pares_union" value="1" class="ui-widget-content ui-corner-all" style="width:25px; marginleft:5px"/> <br> <label for="min_porc_muestra_clase">Mínimo porcentaje Muestra/Clase:</label> <input type="text" name="min_porc_muestra_clase" id="min_porc_muestra_clase" value="1" class="ui-widget-content ui-corner-all" style="width:25px; margin-left:5px"/> <br> <label for="max_desv_estandar">Máxima desviación estandar:</label> <input type="text" name="max_desv_estandar" id="max_desv_estandar" value="1" class="ui-widget-content ui-corner-all" style="width:25px; marginleft:5px"/> <br> <label for="min_dist_clases">Mínima distancia clases:</label> <input type="text" name="min_dist_clases" id="min_dist_clases" value="1" class="ui-widget-content ui-corner-all" style="width:25px; margin-left:5px"/> </div> </fieldset> </form> </div> <!-- Fin Diálogos--> </body> <!-- Fin Body--> <footer id="fter-12"> <div> @WMPS - 2012, by Ángel Ferrán. TFM: Master of Computer Engineering. UEX, University of Extremadura, Spain. </div> <div> <div> <a href="http://gim.unex.es/" target="_blanck">Gim, Grupo de Investigación de Medios</a> </div> <div> <a href="http://www.unex.es/" target="_blanck">Universidad de Extremadura</a> </div> <div> <a href="http://www.unex.es/investigacion/grupos/hypercomp/" target="_blanck">Hypercomp, Computación Hiperspectral</a> </div> </div> </footer> </html> TMF MII, UEX 2012 Ángel Ferrán Frías 70 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web B.7.2. Capa REPOSITORIO DE IMÁGENES En esta capa no existe ningún desarrollo. Se utiliza, como se menciona anteriormente, la Api V3 de Google Maps. Las funciones que utilizan este Api están implementadas en la Capa Cliente. La Api V3 de Google Maps es de uso libre https://developers.google.com/maps/documentation/javascript/?hl=es y gratuíto: B.7.3. Capa CLIENTE En esta capa se encuentra el grueso de los desarrollos realizados. Se detallan los distintos ficheros y principales funciones. Estos ficheros se encuentra en la aplicación en el servidor WEB, pero el navegador se los descarga automáticamente la primera vez que a la aplicación para su ejecución en local, en el lado cliente GMS/css/gms.css: hoja de estilos aplicada a la aplicación web GMS/css/”resto archivos”: hojas de estilos de Jquery-UI GMS/images: archivos de imágenes utilizados en la aplicación web GMS/js: librerías JavaScript de terceros necesarias para la correcta ejecución de la aplicación (guardar imágenes, jquery y jquery-ui) GMS/jsGMS: librerías de desarrollo propias: o Config.js: valores predeterminados de la aplicación Código fuente: var configuration = {} configuration.defaultWidhImage='200', configuration.defaultHeightImage='300' configuration.defaultLongitud='39.30993', configuration.defaultLatitud='-4.5820', configuration.defaultMapZoom=5; configuration.defaultNumberClasses=7; configuration.defaultIterMax=15; //'OFF', '3x3', '5x5', '7x7' configuration.defaultKmeansPP='5x5'; configuration.defaultIsodataPP='OFF'; configuration.defaultIsodataOptions={ max_pares_union:5, min_porc_muestra:2, max_desv_estandar:1, min_distancia_clases:3} o jsGM.js: librería de inicializaciones de objetos. Variables globales del sistema: //Variables de Tabs var tabSuperior, tabInferior, tab_inferior_counter=new Array(), arrColores=new Array(); TMF MII, UEX 2012 Ángel Ferrán Frías 71 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web var Hlen=configuration.defaultWidhImage, Vlen=configuration.defaultHeightImage; var controlLoadCapture=new Array(); var flatShowOpcKmenas=false; var flatShowOpcSave=false; var kmeans_pp_value=0; //0= no PP, 1=3x3, 2=6x6, 3=9x9 var actualClassesNumber; var actualZoom; var mapHash = []; var bound = new google.maps.LatLngBounds(); var layer_to_delete; var layer_to_asign; Principales funciones: function nuevaCaptura(): crea una nueva captura del mapa actualmente seleccionado en el contenedor de mapas function nuevaCaptura(){ tabInferior=tabSuperior + "B"; i=tab_inferior_counter[tabSuperior]; tab_inferior_counter[tabSuperior]++; $(tabInferior).tabs("add", tabInferior + i, "Imagen-"+i); componImagen(); } function actualizaCaptura(): función que actualiza el contenido de una captura con el contenido de un mapa function actualizaCaptura(){ removeLayers($(tabInferior + " div canvas").attr("id")); componImagen(); } function componImagen(): Obtiene la imagen del mapa Actual function componImagen(){ var idMapa=$(tabSuperior + " div div").attr("id"); var idImagen=$(tabInferior + " div canvas").attr("id"); putImagen(idMapa,idImagen); } function putImagen: función principal del modulo que obtiene las imágenes de un mapa de pasado por parámetro y las “pega” en el objeto Canvas pasado por parámetro. function putImagen(idMapa, idContenedor){ //var imgs=document.getElementById(idMapa).getElementsByTagName('img'); //var divs=document.getElementById(idMapa).getElementsByTagName('div') var imgs=$("#"+idMapa+" img"); var divs=$("#"+idMapa+" div"); var canvas = document.getElementById(idContenedor); var context = canvas.getContext("2d"); var p=Array(); var i=0; var indiceAux=0; var aux; var aux2=0; var valor; var contador=0; TMF MII, UEX 2012 Ángel Ferrán Frías 72 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web var offSetLeft=0; var offSetTop=0; var imgArr=new Array(); var typeOffset; typeOffset=browserTypeOffset(); //Localización del OffSet de OpenHand de GoogleMaps for( i=0; i<divs.length; i++) { aux=divs[i].style.cssText; indiceAux=aux.indexOf("openhand"); if (indiceAux>-1) { switch (typeOffset){ case 1: if (aux.indexOf("-webkit-transform: matrix")>-1) { indiceAux=aux.indexOf("-webkit-transform: matrix"); indiceAux=aux.indexOf(",",indiceAux+1); //firs vector position matrix indiceAux=aux.indexOf(",",indiceAux+1); //second vector position matrix indiceAux=aux.indexOf(",",indiceAux+1); //third vector position matrix indiceAux=aux.indexOf(",",indiceAux+1)+1; //four vector position matrix aux2=aux.indexOf(",",indiceAux+1); offSetLeft=parseInt(aux.substring(indiceAux,aux2)); //Value of Left Transformaton indiceAux=aux.indexOf(")",aux2); offSetTop=parseInt(aux.substring(aux2+1,indiceAux)); } break; case 2: if (aux.indexOf("position: absolute;")==0) { indiceAux=aux.indexOf("left:")+5; aux2=aux.indexOf("px;",indiceAux+1); offSetLeft=parseInt(aux.substring(indiceAux,aux2)) indiceAux=aux.indexOf("top:")+4; TMF MII, UEX 2012 Ángel Ferrán Frías 73 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web aux2=aux.indexOf("px;",indiceAux+1); offSetTop=parseInt(aux.substring(indiceAux,aux2)) } break; case 3: if (aux.indexOf("-ms-transform: matrix")>-1) { indiceAux=aux.indexOf("-ms-transform: matrix"); indiceAux=aux.indexOf(",",indiceAux+1); //firs vector position matrix indiceAux=aux.indexOf(",",indiceAux+1); //second vector position matrix indiceAux=aux.indexOf(",",indiceAux+1); //third vector position matrix indiceAux=aux.indexOf(",",indiceAux+1)+1; //four vector position matrix aux2=aux.indexOf(",",indiceAux+1); offSetLeft=parseInt(aux.substring(indiceAux,aux2)); //Value of Left Transformaton indiceAux=aux.indexOf(")",aux2); offSetTop=parseInt(aux.substring(aux2+1,indiceAux)); } }; } } //Obtención de Imágenes de Google Maps for( i=0; i<imgs.length; i++) { //src //if((parseInt($(imgs[i]).parent().css('left'))) (parseInt($(imgs[i]).parent().css('top'))) ){ imgArr.push(imgs[i].src); //console.info(imgs[i].src) //left imgArr.push(parseInt($(imgs[i]).parent().css('left'))); && //top imgArr.push(parseInt($(imgs[i]).parent().css('top'))); //} if (imgs[i].src.search("&x=")>0) { p[contador]=new Array(); p[contador].push(imgs[i].src); //LEFT aux=imgs[i].parentNode.style.cssText indiceAux=aux.indexOf("left:")+5; TMF MII, UEX 2012 Ángel Ferrán Frías 74 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web aux2=aux.indexOf("px;",indiceAux+1); valor=parseInt(aux.substring(indiceAux,aux2)) + p[contador].push(valor); //TOP indiceAux=aux.indexOf("top:")+4; aux2=aux.indexOf("px;",indiceAux+1); valor=parseInt(aux.substring(indiceAux,aux2)) + offSetLeft; offSetTop; p[contador].push(valor); contador++; } } //Creación de imagen contentWorking($(canvas).attr("id"),"Capturando mapa..."); controlLoadCapture[$(canvas).attr("id")]=new Array() controlLoadCapture[$(canvas).attr("id")]=0; for( i=0; i<p.length; i++) { newImage(context,p[i][0],p[i][1],p[i][2],$(canvas).attr("id"),p.length ); } //for( i=0; i<imgArr.length; newImage(context,imgArr[i],imgArr[i+1],imgArr[i+2]); i=i+3) } function saveCanvasToImage: función que guarda el contenido de un objeto Canvas en el format seleccionado. Se pasa por parámetro el identificado de la imagen captura concreta a guardar. function saveCanvasToImage(idContent) { //Save image from Canvas //Generate new canvas from layers with z-index>=0 cvWidth=$(idContent+' canvas').width(); cvHeight=$(idContent+' canvas').height(); $(idContent).append('<canvas id='+idContent+'_layer_to_save width="'+cvWidth+'" height="'+cvHeight+'" class="nuevaCaptura"></canvas>'); var oCanvasTmp = document.getElementById(idContent+"_layer_to_save"); $(oCanvasTmp).css('z-index',-100); $(oCanvasTmp).css('position','absolute'); $(oCanvasTmp).css('left','800px'); contextPut=oCanvasTmp.getContext("2d"); var context, arrayImage, oLayer; var oCanvasTmpGetImage; var $canvasStack=$('#'+$(idContent).attr('id')+' canvas'); var newPixels = contextPut.createImageData(cvWidth, cvHeight); var tama=newPixels.height * newPixels.width; $.each($canvasStack, function(index, value) { if (($(this).css('zIndex'))>-1){ oLayer = document.getElementById($(this).attr('id')); context = oLayer.getContext("2d"); arrayImage = context.getImageData(0, 0, cvWidth, cvHeight); for( i=0; i<tama; i++){ j=i*4; TMF MII, UEX 2012 Ángel Ferrán Frías 75 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web if ( (arrayImage.data[j]!=0) || (arrayImage.data[j+1]!=0) (arrayImage.data[j+2]!=0) ){ newPixels.data[j]=arrayImage.data[j]; newPixels.data[j+1]=arrayImage.data[j+1]; newPixels.data[j+2]=arrayImage.data[j+2]; newPixels.data[j+3]=255; } } } }); //Context Final, todos los pixeles actualizados¡¡ contextPut.putImageData(newPixels, 0,0); || //force download image to client switch ($("#listformatSave :checked").attr('value')){ case 'Png': Canvas2Image.saveAsPNG(oCanvasTmp) break; case 'Bmp': Canvas2Image.saveAsBMP(oCanvasTmp) break; case 'Jpeg': Canvas2Image.saveAsJPEG(oCanvasTmp) break; } //remove canvas temp from DOM $(oCanvasTmp).remove(); } function sendToServer(obCanvas, urlDest, type, objPost): función que envía, vía objeto Ajax, el contenido de una imagen al servidor para ser procesada. Se pasa por parámetro la captura a procesar, la url del servidor de cómputo y los parámetros de procesamiento de la imagen. function sendToServer(obCanvas, urlDest, objPost){ var ret=''; var idCanvas=$(obCanvas).attr("id"); var request=$.ajax({ type: 'post', cache: false, url: urlDest, data: objPost }); ret=request.done(function( msg ) { }); ret=request.success(function( msg ) { if (ret.status==200) { loadImageServer(ret.responseText, obCanvas, 'imgPr-'+idCanvas); } else alert("Error en el envío: " + ret.responseText); }); ret=request.fail(function(jqXHR, textStatus) { TMF MII, UEX 2012 Ángel Ferrán Frías 76 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web alert ('Error en la petición:' + textStatus + ' ' + status) }); ret=request.always(function() { contentWorkingRemove($(obCanvas).attr("id")); }); } o sources.js: librería de código general de la aplicación Principales Funciones: $(document).ready(function(): esta función es el 99% de este archivo y básicamente lo que realiza es inicializar las variables definidas mediante Jquery de los objetos de la página Html que posteriormente se utilizan, como son los tabs de mapas y capturas y las ventanas de diálogo de la aplicación Fragmento de Código: $(document).ready(function() { //Inicializaciones jQuery /////////////////// $("#tabs-1B").tabs(); $(".tabs-bottom .ui-tabs-nav, .tabs-bottom .ui-tabs-nav > *" ) .removeClass( "ui-corner-all ui-corner-top" ) .addClass( "ui-corner-bottom" ); //Variables para cada Mapa var $tab_content_idmapa = $( "#tab_idmapa"), $tab_title_input = $( "#tab_title"), $tab_content_input = $( "#tab_content" ), $tab_content_latitud = $( "#tab_latitud" ), $tab_content_longitud = $( "#tab_longitud" ), $tab_content_zoom = $( "#tab_zoom" ); var tab_counter = 2; tabSuperior ="#tabs-1"; tab_inferior_counter[tabSuperior]=1; //Otras Variables //BOTONES ////////////////////////////// $("#nuevoMapa").button({ icons: { primary: "ui-icon-circle-plus" }, text: false }) .click(function() { $dialog.dialog( "open" ); }); $("#nuevaCaptura").button({ icons: { primary: "ui-icon-image" }, text: false }) .click(function() { nuevaCaptura(); }); $("#actualizaCaptura").button({ TMF MII, UEX 2012 Ángel Ferrán Frías 77 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web icons: { primary: "ui-icon-refresh" }, text: false }) .click(function() { actualizaCaptura(); }); $("#saveImage").button({ icons: { primary: "ui-icon-disk" }, text: false }) .click(function() { //saveCanvasToImage(); saveCanvasToImage(tabInferior); }) .next() .button( { text: true, icons: { primary: "ui-icon-triangle-1-s" } }) .click(function() { }) .parent() .buttonset(); function crearNuevoMapa: function que crea un Nuevo mapa en el contenedor de mapas. function crearNuevoMapa() { var tab_title = $tab_title_input.val() || "Mapa-" + tab_counter; Hlen=$Hlen.val() || configuration.defaultWidhImage; Vlen=$Vlen.val() || configuration.defaultHeightImage ; $tabs.tabs( "add", "#tabs-" + tab_counter, tab_title ); nuevaTabInf('#tabs-' + tab_counter + 'B'); tab_counter++; } function Init(): función que inicializa otras variables de la aplicación, como los colores utilizados en las clases de agrupamiento y características por defecto el primer mapa que se crea automáticamente. o utils.js: librería de utilidades. Principal función: browserTypeOffset: devuelve un valor para cada tipo de navegador Código Fuente: function browserTypeOffset(){ //navigator.userAgent.toLowerCase().indexOf('chrome') > -1; var ret=0; if (navigator.userAgent.toLowerCase().indexOf('chrome')> -1) ret=1; TMF MII, UEX 2012 Ángel Ferrán Frías 78 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web else if (navigator.userAgent.toLowerCase().indexOf('firefox')> -1) ret=2; else if (navigator.userAgent.toLowerCase().indexOf('msie')> -1) ret=3; return ret; } TMF MII, UEX 2012 Ángel Ferrán Frías 79 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web C) Project Charter C.1. Información general Nombre del proyecto: ‘Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Proyecto destinado a ser el TFM (trabajo Fin de Máster) del Alumno Ángel María Ferrán Frías, como finalización del MII (Máster en Ingeniería Infomrática) de la Universidad de Extremadura. Cliente: Pablo García, Grupo de Investigación Gim, Antonio Plaza, Grupo de Investigación Hypercomp. Universidad de Extremadura Grupo de Trabajo: Ángel María Ferrán Frías Fecha de preparación: 15/09/2011 Fecha límite de finalización del proyecto: Marzo de 2012 C.2. Resumen del proyecto Se desea realizar un sistema de información que, cogiendo las ideas fundamentales de un sistema ya existente, CBIR, desarrollado por Sergio Bernabé García, mejore el mismo en cuanto a funcionalidades y flexibilidad. Principalmente se desea crear el sistema de información basado en tecnologías Web, ya que el sistema CBIR es un sistema de escritorio. Esto mejorará la eficiencia, escalabilidad, flexibilidad y utilidad de cara a futuras ampliaciones de funcionalidades. El sistema debe ser una aplicación Web y debe ser capaz de realizar capturas de mapas proporcionados por algún repositorio gratuito existente. Se desea que las capturas puedan ser procesadas, posteriormente por algún mecanismo o proceso y proporcionar las imágenes clasificadas mediante algoritmos de procesamiento tanto no supervisado como supervisado. Dependiendo del avance del proyecto y disponibilidad del tiempo se abarcará más o menos en los tipos de algoritmos que procesan las imágenes. TMF MII, UEX 2012 Ángel Ferrán Frías 80 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web C.3. Objetivos del proyecto Obtener aplicación Web accesible desde varios dispositivos y desde cualquier ubicación Disponer de mapas de imágenes satélites en la aplicación y operar con ellos Poder realizar capturas de imágenes de estos mapas Realizar, de algún modo, el procesamiento de estas capturas Poder guardar los resultados obtenidos Poder realizar búsquedas por contenidos de los resultados almacenados C.4. Alcance del proyecto El alcance del proyecto se plantea como abierto. Esto se plantea así puesto que el desarrollo del mismo dependerá en gran medida del tiempo disponible del alumno. Así mismo dado el alto contenido del desarrollo se priorizará en los objetivos a desarrollar conforme el proyecto vaya avanzando en su desarrollo. C.5. Descripción del producto / servicio El producto resultante estará compuesto por los siguientes módulos: Módulo de Servidor Web: encargado de alojar la aplicación web Módulo de mapas: proveerá los mapas que deben cargase en la aplicación Modulo de Procesamiento: deberá procesar las imágenes capturadas por la aplicación Módulo de almacén de datos: almacenará los procesamientos para posteriores búsquedas por contenido C.6. Participantes del proyecto El equipo del proyecto será el siguiente: Directores del Proyecto: Pablo García y Antonio Plaza, UEX: realizarán las labores de director del proyecto ( siendo tutores del TFM del alumno) y coordinación del mismo. Desarrollo del proyecto: Ángel María Ferrán Frías, Alumno del MII Colaboraciones: o Sergio Bernabé García: podrá realizar tareas de asesoramiento y colaboraciones puntuales en la parte de los procesamientos de imágenes. TMF MII, UEX 2012 Ángel Ferrán Frías 81 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web C.7. Hitos importantes del proyecto Reunión con directores para análisis de necesidades Recopilar información sobre herramienta existente CBIR Elaboración del Planificación Inicial del Proyecto Selección repositorio de imágenes de las posibilidades existentes Presentación del borrador del proyecto Aceptación por parte de la dirección el proyecto Desarrollo del proyecto: análisis, diseño, construcción y pruebas Implantación del Proyecto Propuesta de Plan de Mantenimiento C.8. Restricciones del proyecto Utilización de tecnologías de software libre Utilización de estándares El proyecto debe conllevar coste de 0 euros Limitación de posibles objetivos a la disponibilidad del tiempo Sistema utilizable desde navegadores Web Plataforma escalable y reutilizable C.9. Criterios de aceptación del proyecto Dado que el proyecto constituye el TFM los criterios de aceptación del mismo están indicados por los directores del proyecto y están abierto al continua avance y supervisión del mismo. No obstante, se indican los criterios mínimos de aceptación: Existencia de Aplicación Web con posibilidad de visualización de Mapas Posibilidad de Realizar capturas sobre estos mapas Guardar resultados de estas capturas Facilidades de ampliación para futuras funcionalidades nuevas C.10. Sponsor que autoriza el proyecto Universidad de Extremadura. Gim, Grupo de Investigación de Medios Hypercomp, Grupo de Investigación de Computación Hyperespectral Fecha: 16/09/2011 TMF MII, UEX 2012 Ángel Ferrán Frías 82 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web TMF MII, UEX 2012 Ángel Ferrán Frías 83 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web D) Planning and System Construction D.1. Introducción La planificación de este proyecto se realizará en dos fases. Dada la gran importancia que tiene el factor del tiempo disponible se realizará una primera planificación que abracará todos los objetivos iniciales indicados en el Project Charter, objetivos deseables para el funcionamiento global y completo del proyecto propuesto. Posteriormente se realizará un planificación real acorde a los tiempos empleados en cada fase del proyecto lo que mostrará los objetivos finales alcanzados. D.2. Planificación Inicial En esta planificación inicial se establecen las principales actividades a realizar para la completa ejecución del proyecto propuesto. A continuación se muestra la lista de tareas del proyecto, indicando una fecha inicial, duración y fecha final aproximada. Inicio Proyecto Fin Proyecto 15/09/2011 20/03/2012 Fecha Inicio Duracion Reuniones Iniciales Actividad 15/09/2011 3 18/09/2011 Toma de Requisitos 19/09/2011 3 22/09/2011 Fase de Análisis Análisis Herramienta CBIR Fecha Fin 23/09/2011 5 28/09/2011 Creación Project Charter 29/09/2011 3 02/10/2011 Análisis de Repositorios Imágenes Existentes 03/10/2011 10 13/10/2011 Creación Interfaz Usuario 14/10/2011 15 29/10/2011 Creación Página General Html 30/10/2011 10 09/11/2011 Creación Librerías JavaScript en Cliente 10/11/2011 40 20/12/2011 Creación Hojas de Estilo 21/12/2011 5 26/12/2011 Implementación Programas de procesado 27/12/2011 15 11/01/2012 Instalación Servidor Web Apache Entorno local 12/01/2012 2 14/01/2012 Creación App Web en Local 15/01/2012 2 17/01/2012 Instalación BD MySql Funcionalidades de aplicación con BD (consultas por contenido) Pruebas en entorno local 18/01/2012 3 21/01/2012 22/01/2012 25 16/02/2012 17/02/2012 5 22/02/2012 Implantación en entorno real Pruebas en entorno real 23/02/2012 01/03/2012 6 5 29/02/2012 06/03/2012 Documentación Documentación del Proyecto Desarrollo del Sistema Pruebas Despliegue Mantenimiento 07/03/2012 8 15/03/2012 Reunión Planificación de Mantenimiento 16/03/2012 1 17/03/2012 Creación de plan de Mantenimiento 18/03/2012 2 20/03/2012 TMF MII, UEX 2012 Ángel Ferrán Frías 84 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web La gráfica de Gant de las tareas anteriores es la siguiente: 15-sep 25-oct 4-dic 13-ene 22-feb Reuniones Iniciales Toma de Requisitos Análisis Herramienta CBIR Creación Project Charter Análisis de Repositorios Imágenes Existentes Creación Interfaz Usuario Creación Página General Html Creación Librerías JavaScript en Cliente Creación Hojas de Estilo Implementación Programas de procesado Instalación Servidor Web Apache Entorno… Creación App Web en Local Instalación BD MySql Funcionalidades de aplicación con BD… Pruebas en entorno local Implantación en entorno real Pruebas en entorno real Documentación del Proyecto Reunión Planificación de Mantenimiento Creación de plan de Mantenimiento Obviamente las tareas se realizan de forma secuencial puesto que los recursos disponibles para todas las tareas es una única persona. D.3. Planificación Final La planificación final del proyecto indica, por un lado, los objetivos reales alcanzados en el proyecto, así como las tareas efectuadas y el tiempo estimado en cada una de ellas. Debido al tiempo limitado disponible y a un cambio de criterio que a continuación se explica, la planificación inicial cambia en algunas fases. TMF MII, UEX 2012 Ángel Ferrán Frías 85 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Concretamente se han eliminado los desarrollos referentes a la implementación en el sistema de la BD en MySQL y su correspondiente módulo de consultas por contenido. Esto se ha hecho por dos razones. Primera, resultaba absolutamente imposible abarcar estos objetivos en el tiempo disponible y, segunda, se replantea el TFM y el grupo completo el Proyecto decide realizar un PAPER para publicación de este mismo trabajo, dado lo interesante del mismo desde el punto de vista de la investigación. Así pues, por un lado se eliminan las funcionalidades del módulo de almacenamiento y consultas por contenidos de las imágenes procesadas y se realiza, en cambio, un PAPER para enviar a revistas científicas este trabajo final de Máster. Las tareas referentes a la elaboración del PAPER se han realizado de forma conjunta con el resto de colaboradores indicados en el Project Charter y se indican en la lista de tareas y diagrama correspondiente dentro del apartado de “Documentación”. Lista definitiva de tareas principales efectuadas: Inicio Proyecto Fin Proyecto 15/09/2011 23/03/2012 Fecha Inicio Duración Reuniones Iniciales Actividad 15/09/2011 5 20/09/2011 Toma de Requisitos 21/09/2011 3 24/09/2011 Fase de Análisis Análisis Herramienta CBIR Desarrollo del Sistema Pruebas Despliegue 25/09/2011 6 01/10/2011 Creación Project Charter 02/10/2011 3 05/10/2011 Análisis de Repositorios Imágenes Existentes 06/10/2011 10 16/10/2011 Creación Interfaz Usuario 17/10/2011 20 06/11/2011 Creación Página General Html 07/11/2011 12 19/11/2011 Creación Librerías JavaScript en Cliente 20/11/2011 40 30/12/2011 Creación Hojas de Estilo 31/12/2011 6 06/01/2012 Implementación Programas de procesado 07/01/2012 15 22/01/2012 Instalación Servidor Web Apache Entorno local 23/01/2012 2 25/01/2012 Creación App Web en Local 26/01/2012 2 28/01/2012 Instalación BD MySql 29/01/2012 0 29/01/2012 Funcionalidades de aplicación con BD (consultas por contenido) 30/01/2012 0 30/01/2012 Pruebas en entorno local 31/01/2012 5 05/02/2012 Implantación en entorno real 06/02/2012 5 11/02/2012 Pruebas en entorno real 12/02/2012 5 17/02/2012 18/02/2012 30 19/03/2012 Reunión Planificación de Mantenimiento 20/03/2012 1 21/03/2012 Creación de plan de Mantenimiento 22/03/2012 1 23/03/2012 Documentación Documentación del Proyecto Mantenimiento Fecha Fin TMF MII, UEX 2012 Ángel Ferrán Frías 86 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Gráfica correspondiente: 15-9 25-10 4-12 13-1 22-2 Reuniones Iniciales Toma de Requisitos Análisis Herramienta CBIR Creación Project Charter Análisis de Repositorios Imágenes Existentes Creación Interfaz Usuario Creación Página General Html Creación Librerías JavaScript en Cliente Creación Hojas de Estilo Implementación Programas de procesado Instalación Servidor Web Apache Entorno local Creación App Web en Local Pruebas en entorno local Implantación en entorno real Pruebas en entorno real Documentación del Proyecto Reunión Planificación de Mantenimiento Creación de plan de Mantenimiento D.4. Análisis Requisitos Tras varias reuniones con el promotor el Proyecto (Grupo Gim y Grupo Hypercomp de la UEX), se expone la siguiente lista de requisitos deseables de cumplir por el proyecto. Como se indicó en el documento Project Charter, estos requisitos serán satisfechos en la medida de los posible teniendo en cuenta el tiempo disponible. Aplicación en entorno Web Se desea que la aplicación sea accesible desde cualquier ubicación. Será necesario, por tanto, disponer de un servidor público Coste 0. El proyecto no deberá generar coste alguno. Por tanto las tecnologías y software a utilizar deberán ser de uso libre y gratuito, así como del hardware necesario para alojar la aplicación El sistema debe ser fácil de ampliar. Esto es importante puesto que es factible que no todos los objetivos del proyecto sean cumplidos en su totalidad TMF MII, UEX 2012 Ángel Ferrán Frías 87 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Posibilidad de realizar capturas de mapas de imágenes satélite El sistema debe permitir realizar el procesamiento de las capturas de mapas Posibilidad de almacenar estas imágenes. Esto significa la necesidad de disponer de un SGBD Posibilidad de realizar consultas a posteriori sobre los documentos existentes en el repositorio La aplicación debe ser de uso rápido y sencillo, sin demasiadas opciones, menús ni diálogos D.5. Análisis del Proyecto Teniendo en cuenta los requisitos indicados se presenta la propuesta de construcción del sistema de acuerdo a los siguientes términos: Arquitectura de tres capas: o Cliente Web o Repositorio de Imágenes o Capa de Servidor Servidor Web Servidor de cómputo La siguiente imagen ilustra la arquitectura del sistema: Figura D.1: Arquitectura del Sistema TMF MII, UEX 2012 Ángel Ferrán Frías 88 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Desde el punto de vista de desarrollo se opta por utilizar la siguiente tecnología: Html 5 + JavaScript en la capa cliente: no requiere comunicaciones continuas con el servidor web y rápido desde el punto de vista del usuario Php en la parte de servidor: open source y ampliamente utilizado Servidor de cómputo: programas de líneas de comandos en servidor accesible desde el servidor web Ajax: como programación para comunicaciones entre cliente servidor y de forma asíncrona Se utilizará Google Maps como repositorio de imágenes. Es el repositorio de uso más extendido por disponer de su propio API de programación de aplicaciones Un punto muy importante en este análisis es el proceso de comunicaciones entre el cliente y el servidor. Estas comunicaciones se establecerán únicamente en el caso de envío y recepción de imágenes desde el navegador del cliente hacia el servidor y viceversa, tras el procesamiento de la imagen. En la siguiente figura se ilustra el flujo de comunicaciones del sistema. Figura D.2: Flujo de Comunicaciones Cliente-Servidor TMF MII, UEX 2012 Ángel Ferrán Frías 89 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Metodología de desarrollo: se realizará mediante metodologías Ágiles, esto es, se establecerán reuniones periódicas con la dirección del proyecto, se presentará el estado actual del mismo y se encauzarán las siguientes fases de desarrollos según las prioridades de la dirección del proyecto, del tiempo disponible y del resultado de estas reuniones periódicas. D.6. Construcción del Proyecto La construcción del proyecto se ha dividido en varias módulos. La figura siguiente muestra la división de módulos de desarrollo. Figura D.3: División en módulos de desarrollo del sistema TMF MII, UEX 2012 Ángel Ferrán Frías 90 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web A continuación se indican, para cada fase de desarrollo las principales tareas realizadas: Fase de Análisis Reuniones Iniciales Toma de Requisitos Análisis Herramienta CBIR Creación Project Charter Análisis de Repositorios Imágenes Existentes Desarrollo del Sistema Creación Interfaz Usuario Creación Página General Html Creación Librerías JavaScript en Cliente Creación Hojas de Estilo Implementación Programas de procesado Instalación Servidor Web Apache Entorno local Creación App Web en Local Pruebas Despliegue Pruebas en entorno local Implantación en entorno real Pruebas en entorno real Documentación Documentación del Proyecto Mantenimiento Reunión Planificación de Mantenimiento Creación de plan de Mantenimiento En la planificación final del proyecto se han detallado para cada actividad el tiempo estimado empleado en cada una de ellas. D.7. Pruebas del Proyecto Las pruebas del proyecto consisten en realizar tres pasos fundamentales: 1. Realizar capturas desde mapas provistos por el repositorio de mapas 2. Realizar el procesamiento de estas capturas y obtener las imágenes correspondientes de todos los algoritmos de procesamiento 3. Comparar las imágenes del punto 2 con herramientas del mercado para validar esos algoritmos de clasificación. Las pruebas se han realizado tanto en fase de desarrollo (servidor local y aplicación en entorno de desarrollo) como en fase de producción (aplicación en entorno de funcionamiento real). En ambos casos las pruebas han resultado satisfactorias puestos que los valores comparativos son muy aceptables. Se ha comparado con la herramienta ENVI y los resultados pueden verse en el Experimento 1 y 2 de este trabajo. TMF MII, UEX 2012 Ángel Ferrán Frías 91 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web D.8. Plan de Mantenimiento D.8.1. Introducción Este plan de mantenimiento tiene por objetivo indicar, por un lado, aquéllas funcionalidades que se desean ampliar en un futuro en el sistema y, por otro, señalar los posibles módulos del sistema que deben ser susceptibles a mejoras o solución a posibles errores. D.8.2. Nuevas Funcionalidades Las principales funcionalidades a añadir a este proyecto serían las que se indican en el Project Charter y que no se han efectuado en el mismo, por los motivos y argumentos indicados en el correspondiente documento de Planificación Final del Proyecto. Por tanto, sería deseable que en un futuro el sistema: Contara con un SGBD Relacional para el posible almacenaje de las capturas de los mapas y el procesado de estas capturas. Sobre estos archivos documentales podrían, posteriormente, realizarse múltiples búsquedas por contenido, según los criterios del usuario. Posibilidad de realizar capturas sobre una parte concreta del mapa y no capturas completas del mismo. Esto es interesante porque permite al usuario seleccionar el territorio concreto de la imagen satélite a procesar, sin tener que solicitar el procesado de la captura completa del mapa. Utilización de lenguajes de programación paralela. Con esto se aceleraría bastante el tiempo de ejecución de los programas del servidor de cómputo, ya que aprovecharían mucho más los recursos del servidor multiprocesador Utilización de Servidores MultiGPU. Esta mejora significaría un salto cualitativo en la forma de tratar las imágenes satélite al utilizar métodos novedosos en cuanto a la arquitectura multigpu. La implementación de esta mejora podrían considerarse suficiente para la elaboración de un nuevo PAPER de investigación. TMF MII, UEX 2012 Ángel Ferrán Frías 92 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web D.8.3. Módulos revisables y mejorables Las posibles mejoras y posibles errores del sistema podrían ser las siguientes: Utilización de navegadores. Existen navegadores que actualmente no pueden utilizarse para acceder al sistema. El problema es que al día de hoy no son compatibles con algunas de las características de HTML 5 necesarias para el correcto funcionamiento del sistema. Uno de los principales problemas de compatibilidad de los navegadores es que no soportan las características de los objetos “Canvas” de HTML 5. Sería conveniente revisar en un futuro cercano la compatibilidad de estos navegadores para poder adaptar la aplicación y su uso. Como muestra decir que el navegador IE no es compatible actualmente. Actualmente los navegadores que sí garantizan el correcto funcionamiento del sistema son Mozilla Firefox y Google Chrome. Otras mejoras de la aplicación podrían ser revisar el interfaz de usuario y controlar de forma más eficiente el tamaño de las ventanas tanto del contenedor de mapas como del contenedor de capturas, para permitir que cualquiera de ellos pudiera ocupar todo el alto de la pantalla del navegador. Mensajes de error personalizados. Actualmente se envían mensajes de error generales al usuario indicando que no se ha podido realizar un proceso concreto. Estos errores solamente están visibles si se utilizan herramientas de “debug” de JavaScript. Es deseable poder personalizar y mejorar la forma de enviar los mensajes de error al usuario. Mejora en el proceso de Ajax. Actualmente el proceso de envío y recepción mediante Ajax indica que el procesa está en fase de ejecución o espera, pero no indica un tiempo aproximado para su finalización. Es deseable poder indicar este tiempo para que el usuario pueda visualizarlo por pantalla. TMF MII, UEX 2012 Ángel Ferrán Frías 93 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web E) Glossary of Terms E.1. Introducción En este documento se indican los principales términos de uso del sistema WMPS. Algunos de ellos son de uso común durante la explotación del sistema, no obstante, se añaden otros más relacionados con el desarrollo de la aplicación debido a la gran importancia de los mismos y su uso generalizado, considerándolos, por tanto, interesantes para añadirlos a este documento. E.2. Glosario de Términos. Actualizar Captura Acción por la cual se actualiza el contenido de la captura actualmente seleccionada, del contenedor de capturas, con el contenido del mapa superior actualmente seleccionado del contenedor de mapas. AJAX Es la tecnología de programación Web que permite las comunicaciones entre dos máquinas de forma asíncrona. Se realiza principalmente mediante objetos XML Http Request y se programa en el “lado cliente” Algoritmo de clasificación Es un algoritmo matemático que permite clasificar el contenido en pixeles de una imagen teniendo en cuenta los valores de cada pixel del rango RGBA, siendo estos los valores para los colores, en inglés, Red, Green, Blue y Alpha como componente de transparencia. Captura Una captura es una instantánea similar a una fotografía de un mapa en un momento dado. Son de carácter fijo y no dinámico. Es posible tanto obtenerlas, como refrescar su contenido y realizar su procesamiento. TMF MII, UEX 2012 Ángel Ferrán Frías 94 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Clase Cada uno de los grupos en los que se desea clasificar una imagen. De forma práctica puede entenderse como cada uno de los colores que se muestran en una imagen de procesamiento. Cada clase contendrá los píxeles cuyo contenido en valores RGBA sean más parecidos entre todos los pixeles que componen la imagen Contenedor de Mapas El contenedor de mapas es la parte visible superior de la pantalla de la aplicación. Contiene todos los mapas que el usuario vaya creando a lo largo del uso del sistema. El número de mapas que puede albergar es indefinido y vendrá indicado por la capacidad o límites del navegador. Contenedor de Capturas Es otro contenedor semejante al contenedor de mapas, pero que contiene las capturas realizada a un único mapa concreto. Es la parte visible inferior de la pantalla de la aplicación. Cada mapa posee, así, su propio contenedor de capturas independiente a cualquier otro contenedor de cualquier otro mapa Coordenadas Las coordenadas son los valores numéricos que indican la longitud y latitud de un mapa dentro del contexto del sistema. Cada mapa se crea con unas coordenadas concretas, ya sean por defecto o indicadas por el usuario a la hora de crear el mapa. Google Maps TM Google Maps es una marca registrada de Google TM que provee servicios de mapas de forma gratuita. Además provee de una API de programación para desarrolladores con el fin de facilitar herramientas software que utilicen estos servicios de mapas. En esta aplicación se ha utilizado esta API, concretamente la versión 3 (API V3.0) JavaScript Lenguaje de programación de aplicaciones Web en la capa cliente utilizado para manejar los objetos DOM de las páginas HTML. Facilita las operaciones del interfaz de usuario dado que no implica comunicación alguna con servidores Web. Es muy TMF MII, UEX 2012 Ángel Ferrán Frías 95 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web utilizado para desarrollar componentes e interfaces web que necesiten rápida respuesta al usuario. En este sistema se utiliza de forma muy habitual puesto que la funcionalidad del mismo radica en los eventos que el usuario provoca con la interacción del sistema. Jquery Es una librería desarrollada en JavaScript que permite la utilización del propio lenguaje JavaScript de forma más rápida y cómoda lo que facilita el desarrollo de aplicaciones que utilizan este lenguaje, Jquery-UI Otra librería JavaScript desarrollada para el manejo y creación de “widget” u objetos predefinidos de interfaz de usuario. Está orientado principalmente a objetos como botones, desplegables, listas, etc. Kmeans Es un algoritmo de clasificación de imágenes no supervisado. Esto último quiere decir que la imagen se clasifica sin ningún tipo de información previa por parte del usuario. Existen otros tipos de algoritmos, supervisados, en los que se necesita indicar algunas características de la imagen a analizar para realizar las funciones de clasificación. En esta aplicación únicamente se han implementado algoritmos no supervisados. Isodata Es otro algoritmo de clasificación no supervisado. Es muy semejante a Kmeans y los resultados obtenidos son muy semejantes. Junto a Kmeans son los únicos algoritmos implementados en la versión actual de este manual. Mapa Es, obviamente, un mapa que se muestra en la aplicación. Lo interesante es indicar que este mapa está creado de acuerdo a las indicaciones de la API V3 de Google Maps y que puede mostrar distintas visiones del territorio: terrestre, callejero (mapa de carreteras), imágenes satélites (principal uso en este sistema) e, incluso, visión de 45º de la superficie terrestre de algunas ciudades del mundo. TMF MII, UEX 2012 Ángel Ferrán Frías 96 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Php Es un lenguaje de programación ampliamente utilizado por desarrolladores para la creación de proyectos software. Es un lenguaje utilizado en la capa de servidores. En este proyecto se utiliza para implementar la parte del servidor web que recibe las imágenes a procesar y renvía al cliente la imagen procesada. Es de uso libre y gratuito. Post-Procesado El post-procesado es un conjunto de operaciones que se realizan con posterioridad al procesado de una imagen por algún algoritmo de procesamiento indicado anteriormente. Es un conjunto de funciones que operan sobre la imagen procesada que permite “afinar” aún más el procesamiento inicial. En este sistema se permite el post-procesado a tres niveles: 3x3, 5x5, 7x7. Estos valores significan el tamaño de ventana sobre el cual se aplican funciones de “afinamiento” sobre cada pixel de la imagen procesada. Servidor Web Conjunto de máquina y software que se encarga de recibir y gestionar las solicitudes de páginas WEB, por un lado, y por otro las operaciones de procesamiento de imágenes, recibiendo las capturas originales y renviando las imágenes procesadas de las mismas. En este proyecto se ha utilizado el software Apache 2.2 como software de servidor Web. Es el servidor de código abierto, de uso libre y gratuito y el más extendido en el mundo del desarrollo de software. La máquina donde está alojado “instalado” este software es un servidor del centro de investigación CETA-CIEMAT, que ha colaborado con este trabajo de forma desinteresada. Servidor de Cómputo Conjunto formado por máquina y software encargado de ejecutar los algoritmos de clasificación sobre las capturas realizadas sobre los mapas. El software es, en este caso, un desarrollo propio realizado por el grupo de investigación Hypercomp de la Universidad de Extremadura. El hardware utilizado es el mismo servidor utilizado como servidor web del centro CETA-CIEMAT. TMF MII, UEX 2012 Ángel Ferrán Frías 97 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web Zoom Nivel de altura de un mapa concreto de la aplicación. Los mapas visibles en el sistema tienen un mínimo y un máximo nivel de zoom. El mínimo corresponde a 1, donde puede visualizarse el globo terrestre completo y el máximo depende de la zona que se visualice, ay que en algunas zonas es de 19 y en otras de hasta 21. Cada nivel de zoom superior significa un mayor nivel de detalle de la imagen satélite del mapa. TMF MII, UEX 2012 Ángel Ferrán Frías 98 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web TMF MII, UEX 2012 Ángel Ferrán Frías 99 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web References [1] R. A. Schowengerdt, Remote Sensing: Models and Methods for Image Processing, 2nd ed. New York: Academic Press, 1997. [2] D. A. Landgrebe, Signal Theory Methods in Multispectral Remote Sensing. New York: Wiley, 2003. [3] J. A. Richards and X. Jia, Remote Sensing Digital Image Analysis: An Introduction. New York: Springer, 2006 [4] M. Fauvel, J. Benediktsson, J. Chanussot, and J. Sveinsson, “Spectral and spatial classification of hyperspectral data using SVMs and morphological profiles”, IEEE Trans. Geosci. Remote Sens., vol. 46, no. 11, pp. 3804–3814, Nov. 2008. [5] A. Plaza, J. A. Benediktsson, J. Boardman, J. Brazile, L. Bruzzone, G. Camps-Valls, J. Chanussot, M. Fauvel, P. Gamba, J. Gualtieri, M. Marconcini, J. C. Tilton, and G. Trianni, “Recent advances in techniques for hyperspectral image processing”, Remote Sens. Environ., vol. 113, pp. 110–122, 2009. [6] A. Cuartero, A. M. Felicísimo, M. E. Polo, A. Caro and P. G. Rodríguez, “Positional accuracy analysis of satellite imagery by circular statistics”, Photogr. Eng. & Remote Sens., vol. 76, no. 11, pp. 1275-1286, 2010. [7] D. Tuia, F. Ratle, F. Pacifici, M. F. Kanevski, and W. J. Emery, “Active learning methods for remote sensing image classification”, IEEE Trans. Geosci. Remote Sens., vol. 47, no. 7, pp. 2218–2232, Jul. 2009. [8] A. Plaza, J. Plaza and A. Plaza, “Parallel heterogeneous CBIR system for efficient hyperspectral image retrieval using spectral mixture analysis”, Concurr. & Comput. Pract. & Exper., vol. 22, no. 9, pp. 1138-1159, 2010. [9] S. Bernabé, A. Plaza, P. R. Marpu and J. A. Benediktsson, “A new parallel tool for classification of remotely sensed imagery”, Comput. & Geosci., in press, 2012 (http://dx.doi.org/10.1016/j.cageo.2011.12.009). [10] G. Ball and D. Hall, “ISODATA: A novel method of data analysis and classification”, Technical Report AD-699616, Stanford University, 1965. TMF MII, UEX 2012 Ángel Ferrán Frías 100 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web [11] J. A. Hartigan and M. A. Wong, “Algorithm as 136: a k-means clustering algorithm”, Journal of the Royal Statistical Society, Series C (Applied Statistics), vol. 28, pp. 100–108, 1979. [12] P. Gamba, F. Dell’Acqua, A. Ferrari, J. A. Palmason and J. A. Benediktsson, “Exploiting spectral and spatial information in hyperspectral urban data with high resolution”, IEEE Geoscience and Remote Sensing Letters, vol. 1, pp. 322–326, 2005. [13] J. Nickolls and W. J. Dally, “The GPU computing era”, IEEE Micro, vol. 30, pp. 56–69, 2010. [14] A. Plaza and C.-I Chang, High Performance Computing in Remote Sensing. Boca Raton, FL: Taylor & Francis, 2007. [15] A. Plaza, D. Valencia, J. Plaza, and P. Martinez, “Commodity clusterbased parallel processing of hyperspectral Imagery”, J. Parallel and Distributed Computing, vol. 66, no. 3, pp. 345–358, 2006. [16] A. Plaza, J. Plaza, A. Paz, and S. Sanchez, “Parallel hyperspectral image and signal processing”, IEEE Signal Process. Mag., vol. 28, pp. 119–126, 2011. [17] S. Kalluri, Z. Zhang, J. JaJa, S. Liang, and J. Townshend, “Characterizing land surface anisotropy from AVHRR data at a global scale using high performance computing”, Int. J. Remote Sens., vol. 22, pp. 2171–2191, 2001. [18] A. Plaza, “Special issue on architectures and techniques for real-time processing of remotely sensed images”, J. Real-Time Image Process., vol. 4, pp. 191–193, 2009. [19] T. Balz and U. Stilla, “Hybrid GPU-based single- and double-bounce SAR simulation”, IEEE Trans. Geosci. Remote Sens., vol. 47, no. 10, pp. 3519–3529, 2009. [20] J. Mielikainen, B. Huang, and A. H.-L. Huang, “GPU-accelerated multi-profile radiative transfer model for the infrared atmospheric sounding interferometer”, IEEE J. Sel. Topics Appl. Earth Observ. Remote Sens. (JSTARS), vol. 4, no. 3, pp. 691–700, Sep. 2011. [21] C. Song, Y. Li, and B. Huang, “A GPU-accelerated wavelet decompression system with SPIHT and Reed-Solomon decoding for satellite images”, IEEE J. Sel. Topics Appl. Earth Observ. Remote Sens. (JSTARS), vol. 4, no. 3, pp. 683–690, Sep. 2011. TMF MII, UEX 2012 Ángel Ferrán Frías 101 Desarrollo de Sistema de Información para realizar búsquedas por contenido en imágenes de satélite, mediante tecnologías Web [22] S.-C. Wei and B. Huang, “GPU acceleration of predictive partitioned vector quantization for ultraspectral sounder data compression”, IEEE J. Sel. Topics Appl. Earth Observ. Remote Sens. (JSTARS), vol. 4, no. 3, pp. 677–682, Sep. 2011. [23] C.-C. Chang, Y.-L. Chang, M.-Y. Huang, and B. Huang, “Accelerating regular LDPC code decoders on GPUs”, IEEE J. Sel. Topics Appl. Earth Observ. Remote Sens. (JSTARS), vol. 4, no. 3, pp. 653–659, Sep. 2011. [24] A. Plaza, Q. Du, Y.-L. Chang and R. L. King, “Foreword to the special issue on high performance computing in Earth observation and remote sensing”, IEEE J. Sel. Topics Appl. Earth Observ. Remote Sens. (JSTARS), vol. 4, no. 3, pp. 503-507, 2011. [25] C. A. Lee, S. D. Gasster, A. Plaza. C.-I Chang and B. Huang, “Recent developments in high performance computing for remote sensing: A review”, IEEE J. Sel. Topics Appl. Earth Observ. Remote Sens. (JSTARS), vol. 4, no. 3, pp. 508-527, 2011. [26] J. Le Moigne, N. S. Netanyahu and R. D. Eastman, Image Registration for Remote Sensing, Cambridge University Press: Wiley, New York, 2011. [27] H. G. Lewis and M. Brown, “A generalized confusion matrix for assessing area estimates from remotely sensed data”, International Journal of Remote Sensing, vol. 22, no. 16, pp. 3223-3235, 2001. [28] A. Ferrán, S. Bernabé, P. G. Rodríguez and A. Plaza, “A new web-based system for unsupervised classification of satellite images from the Google Maps engine”, Proceedings of SPIE Optics and Photonics, Satellite Data Compression, Communication and Processing Conference, San Diego, California, August 2012 (accepted for publication). [29] A. Ferrán, S. Bernabé, P. G. Rodríguez and A. Plaza, “A new system for classification of satellite imagery”, IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, IEEE Press, 2012 (to be submitted). TMF MII, UEX 2012 Ángel Ferrán Frías