ie.geologyidea.com
More

Using QgsRasterCalculator

Using QgsRasterCalculator


We are searching data for your request:

Forums and discussions:
Manuals and reference books:
Data from registers:
Wait the end of the search in all databases.
Upon completion, a link will appear to access the found materials.


I'm trying to make a sum of n rasters and create a new one using QgsRasterClaculator. The problem is, every time the code reachesprocessCalculation, it makes QGIS close and create a dump file. I don't know if I'm doing it wrong, but I'd like to ask you for some help in how I can do it.

That's how I'm trying to do:

entries = [] rasters = os.listdir("C://test/Rasters/") for i in range(0, len(rasters)): raster = "C://test/Rasters/"+rasters[i] resp = QgsRasterLayer(raster) rast1 = QgsRasterCalculatorEntry() rast1.raster = resp rast1.ref = "rast"+str(i+1) print(rast1.ref) rast1.bandNumber = 1 entries.append(rast1) if(i == len(rasters)-1): var = var + 'rast'+str(i+1) else: var = var + 'rast'+str(i+1)+' + ' calc = QgsRasterCalculator( var, 'C://test/Rasters/raster_somado.tif', 'GTiff', resp.extent(), resp.width(), resp.height(), entries ) print(calc.processCalculation())

I think the error might be happening because I'm using a variable (var), that contains the rasters alias. The base code I found and that works is

calc = QgsRasterCalculator( 'rast1 + rast2', 'C://test/Rasters/raster_somado.tif', 'GTiff', resp.extent(), resp.width(), resp.height(), entries ) print(calc.processCalculation())

Can anybody help me? I already tried some things but it's still not working, QGIS keeps creating the dump and closes.


thanks for the answers. The problem was that I had to set both 'resp' and 'rast1' variables to None after each iteration in the for loop, so my code end up like this

entries = [] rasters = os.listdir("C://test/Rasters/") for i in range(0, len(rasters)): raster = "C://test/Rasters/"+rasters[i] resp = QgsRasterLayer(raster) rast1 = QgsRasterCalculatorEntry() rast1.raster = resp rast1.ref = "rast"+str(i+1) print(rast1.ref) rast1.bandNumber = 1 entries.append(rast1) rast1 = None resp = None if(i == len(rasters)-1): var = var + 'rast'+str(i+1) else: var = var + 'rast'+str(i+1)+' + ' calc = QgsRasterCalculator( var, 'C://test/Rasters/raster_somado.tif', 'GTiff', resp.extent(), resp.width(), resp.height(), entries ) print(calc.processCalculation())

And it worked


The issue is likely that 'resp' goes out of scope and is deleted when the for loop ends. Then when you try to use it in the calc = QgsRasterCalculator… line QGIS crashes. Try initializing 'resp' outside of your loop first. Something like:

… resp = None for i in range(0, len(rasters)):…

should do it.


QGIS keeps crashing while using the raster calculator

So I'm working on a project that needs extensive use of the raster calculator, but I can't seem to use it now without it crashing. So what's going on and how can I fix it?

QgisApp::showRasterCalculator : QMetaObject::activate : QAction::activate : QMenu::actionGeometry : QMenu::actionGeometry : QMenu::mouseReleaseEvent : QWidget::event : QMenu::event : QApplicationPrivate::notify_helper : QApplication::notify : QgsApplication::notify : QCoreApplication::notifyInternal2 : QApplicationPrivate::sendMouseEvent : QSizePolicy::QSizePolicy : QSizePolicy::QSizePolicy : QApplicationPrivate::notify_helper : QApplication::notify : QgsApplication::notify : QCoreApplication::notifyInternal2 : QGuiApplicationPrivate::processMouseEvent : QWindowSystemInterface::sendWindowSystemEvents : QEventDispatcherWin32::processEvents : UserCallWinProcCheckWow : DispatchMessageWorker : QEventDispatcherWin32::processEvents : qt_plugin_query_metadata : QEventLoop::exec : QCoreApplication::exec : main : BaseThreadInitThunk : RtlUserThreadStart :

QGIS Version: 3.14.16-Pi QGIS code revision: df27394552 Compiled against Qt: 5.11.2 Running against Qt: 5.11.2 Compiled against GDAL: 3.0.4 Running against GDAL: 3.0.4


Class: QgsCoordinateReferenceSystem¶

It supports the following formats: - “EPSG:<code>” - handled with createFromOgcWms() - “POSTGIS:<srid>” - handled with createFromSrid() - “INTERNAL:<srsid>” - handled with createFromSrsId() - “PROJ4:<proj4>” - handled with createFromProj4() - “WKT:<wkt>” - handled with createFromWkt()

If no prefix is specified, WKT definition is assumed.

definition – A String containing a coordinate reference system definition.

createFromString() / // TODO QGIS 3: remove “POSTGIS” and “INTERNAL”, allow PROJ4 without the prefix

QgsCoordinateReferenceSystem(id: int, type: QgsCoordinateReferenceSystem.CrsType = QgsCoordinateReferenceSystem.PostgisCrsId) Constructor a CRS object using a PostGIS SRID, an EPSG code or an internal QGIS CRS ID.

We encourage you to use EPSG code, WKT or Proj4 to describe CRS’s in your code wherever possible. Internal QGIS CRS IDs are not guaranteed to be permanent / involatile.

id – The ID valid for the chosen CRS ID type

type – One of the types described in CrsType / // TODO QGIS 3: remove type and always use EPSG code

QgsCoordinateReferenceSystem(srs: QgsCoordinateReferenceSystem ) Copy constructor

This class represents a coordinate reference system (CRS).

Coordinate reference system object defines a specific map projection, as well as transformations between different coordinate reference systems. There are various ways how a CRS can be defined: using well-known text (WKT), PROJ string or combination of authority and code (e.g. EPSG:4326). QGIS comes with its internal database of coordinate reference systems (stored in SQLite) that allows lookups of CRS and seamless conversions between the various definitions.

Most commonly one comes across two types of coordinate systems:

1. Geographic coordinate systems - based on a geodetic datum, normally with coordinates being latitude/longitude in degrees. The most common one is World Geodetic System 84 (WGS84). 2. Projected coordinate systems - based on a geodetic datum with coordinates projected to a plane, typically using meters or feet as units. Common projected coordinate systems are Universal Transverse Mercator or Albers Equal Area.

Internally QGIS uses proj4 library for all the math behind coordinate transformations, so in case of any troubles with projections it is best to examine the PROJ representation within the object, as that is the representation that will be ultimately used.

Methods that allow inspection of CRS instances include isValid(), authid(), description(), toWkt(), toProj4(), mapUnits() and others. Creation of CRS instances is further described in ref crs_construct_and_copy section below. Transformations between coordinate reference systems are done using QgsCoordinateTransform class.

For example, the following code will create and inspect “British national grid” CRS:

This will produce the following output:

This section gives an overview of various supported CRS definition formats:

1. Authority and Code. Also referred to as OGC WMS format within QGIS as they have been widely used in OGC standards. These are encoded as <auth>:<code> , for example EPSG:4326 refers to WGS84 system. EPSG is the most commonly used authority that covers a wide range of coordinate systems around the world.

An extended variant of this format is OGC URN. Syntax of URN for CRS definition is urn:ogc:def:crs:<auth>:[<version>]:<code> . This class can also parse URNs (versions are currently ignored). For example, WGS84 may be encoded as urn:ogc:def:crs:OGC:1.3:CRS84 .

QGIS adds support for “USER” authority that refers to IDs used internally in QGIS. This variant is best avoided or used with caution as the IDs are not permanent and they refer to different CRS on different machines or user profiles.

See authid() and createFromOgcWmsCrs() methods.

2. PROJ string. This is a string consisting of a series of key/value pairs in the following format: +param1=value1 +param2=value2 […] . This is the format natively used by the underlying proj4 library. For example, the definition of WGS84 looks like this:

+proj=longlat +datum=WGS84 +no_defs

See toProj4() and createFromProj4() methods.

3. Well-known text (WKT). Defined by Open Geospatial Consortium (OGC), this is another common format to define CRS. For WGS84 the OGC WKT definition is the following:

GEOGCS[“WGS 84”, DATUM[“WGS_1984”, SPHEROID[“WGS 84”,6378137,298.257223563,AUTHORITY[“EPSG”,”7030”]], AUTHORITY[“EPSG”,”6326”]], PRIMEM[“Greenwich”,0,AUTHORITY[“EPSG”,”8901”]], UNIT[“degree”,0.0174532925199433,AUTHORITY[“EPSG”,”9122”]], AUTHORITY[“EPSG”,”4326”]]

See toWkt() and createFromWkt() methods.

The database of CRS shipped with QGIS is stored in a SQLite database (see QgsApplication.srsDatabaseFilePath()) and it is based on the data files maintained by GDAL project (a variety of .csv and .wkt files).

Sometimes it happens that users need to use a CRS definition that is not well known or that has been only created with a specific purpose (and thus its definition is not available in our database of CRS). Whenever a new CRS definition is seen, it will be added to the local database (in user’s home directory, see QgsApplication.qgisUserDatabaseFilePath()). QGIS also features a GUI for management of local custom CRS definitions.

There are therefore two databases: one for shipped CRS definitions and one for custom CRS definitions. Custom CRS have internal IDs (accessible with srsid()) greater or equal to ref USER_CRS_START_ID. The local CRS databases should never be accessed directly with SQLite functions, instead you should use QgsCoordinateReferenceSystem API for CRS lookups and for managements of custom CRS.

In some cases (most prominently when loading a map layer), QGIS will try to ensure that the given map layer CRS is valid using validate() call. If not, a custom validation function will be called - such function may for example show a GUI for manual CRS selection. The validation function is configured using setCustomCrsValidation(). If validation fails or no validation function is set, the default CRS is assigned (WGS84). QGIS application registers its validation function that will act according to user’s settings (either show CRS selector dialog or use project/custom CRS).

The easiest way of creating CRS instances is to use QgsCoordinateReferenceSystem(const QString&) constructor that automatically recognizes definition format from the given string.

Creation of CRS object involves some queries in a local SQLite database, which may be potentially expensive. Consequently, CRS creation methods use an internal cache to avoid unnecessary database lookups. If the CRS database is modified, then it is necessary to call invalidateCache() to ensure that outdated records are not being returned from the cache.

Since QGIS 2.16 QgsCoordinateReferenceSystem objects are implicitly shared.

There are two different flavors of WKT: one is defined by OGC, the other is the standard used by ESRI. They look very similar, but they are not the same. QGIS is able to consume both flavors.


Using Remote Sensing and Geographic Information Systems to Identify the Underlying Properties of Urban Environments

Urban places represent built environments that are physically distinguishable from the natural environment, and are thus potentially identifiable through the use of remotely-sensed sources such as satellite images. This chapter begins with a justification of the use of the built environment as a signature of urban places. It provides an overview of how satellite images can be used to distill information about the urban environment, and of the role that geographic information systems play in the analysis. The chapter illustrates the approach to understanding the urbanness of places using data from Egypt. Variables derived from satellite images are combined with census data to improve understanding of the spatial variability in human behavior in the context of the urban-rural continuum. The chapter suggests that ways in which the type of analysis could be used to measure and understand phenomena such as urban sprawl and multinucleation of metropolitan areas.


Geographic Information System (GIS) Using IDRISI Software: Application in Coastal Management

Geographic information system (GIS) is a unique information system because the system are using referenced spatial data as data input and the resulting information is a solution for solving spatial problems that may not be resolved by others information system. IDRISI (derived from the name of an explorer, geographer and author of Moroccan nationality, Muhammad Al-Idrisi) is one of the geographic information system software developed by Clark Labs for geographic technology and cartographic analysis at Clark University, USA. IDRISI software is one of three proprietary software is widely used in various parts of the world in addition to ArcGIS software from environmental systems research institute (ESRI) and MapInfo Professional from MapInfo corporation. IDRISI has an advantage because spatial analysis can be done either in the raster and vector data formats other than that the price for each license is quite competitive, especially for researchers and educational institutions.


Bridge Inventory Using Geographic Information Systems (GIS)

Municipal governments are often challenged by the responsibility to maintain safe and reliable infrastructure within limited budgets. Bridge inventories and assessments are often used to prioritize critical improvements.

The project scope included a comprehensive inventory and assessment of all bridges in New Haven (CT) which the City either owned or maintained, and the development of a program to aid the City in managing its infrastructure resources. Historical inspection reports were reviewed prior to scheduling site visits. Site visits included photo documentation and visual condition inspection. Data collected from the records research, review of inspection reports, and field visits was compiled into a Bridge Inventory Report.

The Bridge Inventory Report consisted of a two-page summary of each bridge providing information on the bridge features, condition, short-term maintenance and repair recommendation, long term rehabilitation or replacement needs and sources of available funding. A red flag system was incorporated to aid the City in quickly identifying those bridges needing immediate attention.

GIS was used to store, manipulate and analyze the data collected for the inventory and assessment. ArcGIS was utilized to assess and analyze the field data collected at each bridge. GIS integrates and inter-relates geographic data (including locations, land use, municipal boundaries, natural resource data and aerial photos) with database information. Users view and analyze the inter-related data in a way that would be impossible by studying stand-alone maps and spreadsheets. Bridge conditions were prioritized and visualized using GIS. Delivering the report and recommendations in a GIS “digital map” format enabled the City to click through to digital photography and access the key data for each bridge.

Finally, statistical data was collected, evaluated, and presented which illustrated how the City of New Haven’s bridge infrastructure compared to other peer cities in the state.


ASJC Scopus subject areas

  • APA
  • Standard
  • Harvard
  • Vancouver
  • Author
  • BIBTEX
  • RIS

Research output : Contribution to journal › Article › peer-review

T1 - Using geographic information systems (GIS) to assess outcome disparities in patients with type 2 diabetes and hyperlipidemia

N2 - Objectives: Geographic information systems (GIS) tools can help expand our understanding of disparities in health outcomes within a community. The purpose of this project was (1) to demonstrate the methods to link a disease management registry with a GIS mapping and analysis program, (2) to address the challenges that occur when performing this link, and (3) to analyze the outcome disparities resulting from this assessment tool in a population of patients with type 2 diabetes mellitus. Methods: We used registry data derived from the University of California Davis Health System's electronic medical record system to identify patients with diabetes mellitus from a network of 13 primary care clinics in the greater Sacramento area. This information was converted to a database file for use in the GIS software. Geocoding was performed and after excluding those who had unknown home addresses we matched 8528 unique patient records with their respective home addresses. Socioeconomic and demographic data were obtained from the Geolytics, Inc. (East Brunswick, NJ), a provider of US Census Bureau data, with 2008 estimates and projections. Patient, socioeconomic, and demographic data were then joined to a single database. We conducted regression analysis assessing A1c level based on each patient's demographic and laboratory characteristics and their neighborhood characteristics (socioeconomic status [SES] quintile). Similar analysis was done for low-density lipoprotein cholesterol. Results: After excluding ineligible patients, the data from 7288 patients were analyzed. The most notable findings were as follows: There was, there was found an association between neighborhood SES and A1c. SES was not associated with low-density lipoprotein control. Conclusion: GIS methodology can assist primary care physicians and provide guidance for disease management programs. It can also help health systems in their mission to improve the health of a community. Our analysis found that neighborhood SES was a barrier to optimal glucose control but not to lipid control. This research provides an example of a useful application of GIS analyses applied to large data sets now available in electronic medical records.

AB - Objectives: Geographic information systems (GIS) tools can help expand our understanding of disparities in health outcomes within a community. The purpose of this project was (1) to demonstrate the methods to link a disease management registry with a GIS mapping and analysis program, (2) to address the challenges that occur when performing this link, and (3) to analyze the outcome disparities resulting from this assessment tool in a population of patients with type 2 diabetes mellitus. Methods: We used registry data derived from the University of California Davis Health System's electronic medical record system to identify patients with diabetes mellitus from a network of 13 primary care clinics in the greater Sacramento area. This information was converted to a database file for use in the GIS software. Geocoding was performed and after excluding those who had unknown home addresses we matched 8528 unique patient records with their respective home addresses. Socioeconomic and demographic data were obtained from the Geolytics, Inc. (East Brunswick, NJ), a provider of US Census Bureau data, with 2008 estimates and projections. Patient, socioeconomic, and demographic data were then joined to a single database. We conducted regression analysis assessing A1c level based on each patient's demographic and laboratory characteristics and their neighborhood characteristics (socioeconomic status [SES] quintile). Similar analysis was done for low-density lipoprotein cholesterol. Results: After excluding ineligible patients, the data from 7288 patients were analyzed. The most notable findings were as follows: There was, there was found an association between neighborhood SES and A1c. SES was not associated with low-density lipoprotein control. Conclusion: GIS methodology can assist primary care physicians and provide guidance for disease management programs. It can also help health systems in their mission to improve the health of a community. Our analysis found that neighborhood SES was a barrier to optimal glucose control but not to lipid control. This research provides an example of a useful application of GIS analyses applied to large data sets now available in electronic medical records.


Given the steadily increasing amount of geographic information on the Web, there is a strong need for suitable methods in exploratory data analysis that can be used to efficiently describe the characteristics of such large-scale, often noisy datasets. Existing methods in spatial data mining focus primarily on mining patterns describing spatial proximity relationships such as co-location patterns or spatial associations rules.

In this paper, we present a novel approach to describe the spatial characteristics of geographic information sources comprised of instances of geographic features. Using the concept of interaction characteristics of geographic features, similarities in how features are distributed in space can be computed and interesting patterns of similar features in the datasets regarding their geographic semantics (landmark, local, regional, global) can be determined. For this, we employ clustering techniques of spatial distance statistics.

We discuss the properties of our method and detail a comprehensive evaluation using publicly available datasets (Flickr, Twitter, OpenStreeMap). We demonstrate the feasibility of identifying groups of geographic features with distinct geographic semantics, which then can be used to select subsets of features for subsequent learning tasks or to compare different datasets.


ASJC Scopus subject areas

  • APA
  • Standard
  • Harvard
  • Vancouver
  • Author
  • BIBTEX
  • RIS

Research output : Contribution to journal › Article › peer-review

T1 - Considerations for using a geographic information system to assess environmental supports for physical activity

N2 - The use of a geographic information system (GIS) to study environmental supports for physical activity raises several issues, including acquisition and development quality, and analysis. We recommend to public health professionals interested in using GIS that they investigate available data, plan for data development where none exists, ensure the availability of trained personnel and sufficient time, and consider issues such as data quality, analyses, and confidentiality. This article shares information about data-related issues that we encountered when using GIS to validate responses to a questionnaire about environmental supports for physical activity.

AB - The use of a geographic information system (GIS) to study environmental supports for physical activity raises several issues, including acquisition and development quality, and analysis. We recommend to public health professionals interested in using GIS that they investigate available data, plan for data development where none exists, ensure the availability of trained personnel and sufficient time, and consider issues such as data quality, analyses, and confidentiality. This article shares information about data-related issues that we encountered when using GIS to validate responses to a questionnaire about environmental supports for physical activity.



Comments:

  1. Broc

    Well done! Keep it up!

  2. Chepe

    the interesting moment

  3. Doulabar

    Very interesting blog. All the most interesting is collected here. It's good that I found this blog, I read different notes here from time to time.



Write a message