Creating raster where each cell records distance to sea?Creating raster with distance to feature using...

Why is there not a feasible solution for a MIP?

If an object moving in a circle experiences centripetal force, then doesn't it also experience centrifugal force, because of Newton's third law?

What is wrong with Justin Trudeau (or anyone) masquerading as Aladdin?

Is there any reason nowadays to use a neon indicator lamp instead of an LED?

Resolving moral conflict

Do we know the situation in Britain before Sealion (summer 1940)?

Can the U.S. president make military decisions without consulting anyone?

Is it a good idea to leave minor world details to the reader's imagination?

Social leper versus social leopard

How does this circuit start up?

Is it impolite to ask for halal food when traveling to and in Thailand?

The quicker I go up, the sooner I’ll go down - Riddle

How can I repair this gas leak on my new range? Teflon tape isn't working

Is it possible to encode a message in such a way that can only be read by someone or something capable of seeing into the very near future?

Is the mass of paint relevant in rocket design?

Meaning of 'ran' in German?

Does wetting a beer glass change the foam characteristics?

Who created the Lightning Web Component?

Do things made of adamantine rust?

Hiking with a mule or two?

Where Does VDD+0.3V Input Limit Come From on IC chips?

Will Proving or Disproving of any of the following have effects on Chemistry in general?

Counting most common combination of values in dataframe column

Is It Possible to Have Different Sea Levels, Eventually Causing New Landforms to Appear?



Creating raster where each cell records distance to sea?


Creating raster with distance to feature using QGIS?Using the Rule-based style to calculate each grid cell from overlapsQGIS--computing local standard deviation (from many bands) to each cellCreating polygons representing specific range of values within raster using QGIS?Changing cell size output for Proximity (Raster Distance) tool in QGISQGIS distance from a cell center to the nearest pointSubstracting raster values from 2 rasters with different cell sizes






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







2















I want to create a raster with a 25 metre × 25 metre resolution, where each cell contains the distance to the nearest coastline, as calculated from the center of the cell. To do this, all I have is a shapefile of the coastlines of New Zealand.



I have tried following Dominic Roye's tutorial for doing it in R which works... kind of. It is fine down to about a 1 km × 1 km resolution but if I try to go any higher the RAM it requires well exceeds that available on my PC (~ 70 gb of RAM required) or any other that I have access too. In saying that, I think this is a limitation of R and I suspect that QGIS might have a more computationally efficient way of creating this raster, but I am new to it and I can't quite figure out how to do it.



I have tried following Creating raster with distance to feature using QGIS? to create it in QGIS but it returns this error:




_core.QgsProcessingException: Could not load source layer for INPUT: C:/..../Coastline/nz-coastlines-and-islands-polygons-topo-150k.shp not
found




and I am not sure why.



Does anyone have any suggestions of what might be going wrong or an alternative way of doing this?










share|improve this question









New contributor



André.B is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

















  • 1





    Are you running a script to do this? Or are you using the tools in QGIS? Something to check, even though it sounds like it should - check the file actually exists where you say it does...also check that you have read and write access to that particular folder.

    – Keagan Allan
    7 hours ago











  • Currently using the tools but I am quite keen to learn the script, just not sure where to start. I am sure the file exists, as I have loaded the .shp file into QGIS and it pops up as an image. I should have read/write access too as I am an admin on the machine and it is just in my dropbox.

    – André.B
    7 hours ago











  • Try moving it out of Dropbox to a local drive. There may be an issue with the path causing QGIS to reject it. What you are looking to do should be pretty simple in QGIS. Which version of QGIS are you using?

    – Keagan Allan
    7 hours ago











  • The tool may require a raster input, which gives you this error.

    – Keagan Allan
    6 hours ago






  • 1





    Ok, try converting the polyline to a raster. The Proximity tool in QGIS needs a raster input. Play around with the settings as per the tool's help: docs.qgis.org/2.8/en/docs/user_manual/processing_algs/gdalogr/…. Take note, it is still an intensive process, I am testing it for fun now and it has been running for 30mins and still going...

    – Keagan Allan
    6 hours ago




















2















I want to create a raster with a 25 metre × 25 metre resolution, where each cell contains the distance to the nearest coastline, as calculated from the center of the cell. To do this, all I have is a shapefile of the coastlines of New Zealand.



I have tried following Dominic Roye's tutorial for doing it in R which works... kind of. It is fine down to about a 1 km × 1 km resolution but if I try to go any higher the RAM it requires well exceeds that available on my PC (~ 70 gb of RAM required) or any other that I have access too. In saying that, I think this is a limitation of R and I suspect that QGIS might have a more computationally efficient way of creating this raster, but I am new to it and I can't quite figure out how to do it.



I have tried following Creating raster with distance to feature using QGIS? to create it in QGIS but it returns this error:




_core.QgsProcessingException: Could not load source layer for INPUT: C:/..../Coastline/nz-coastlines-and-islands-polygons-topo-150k.shp not
found




and I am not sure why.



Does anyone have any suggestions of what might be going wrong or an alternative way of doing this?










share|improve this question









New contributor



André.B is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

















  • 1





    Are you running a script to do this? Or are you using the tools in QGIS? Something to check, even though it sounds like it should - check the file actually exists where you say it does...also check that you have read and write access to that particular folder.

    – Keagan Allan
    7 hours ago











  • Currently using the tools but I am quite keen to learn the script, just not sure where to start. I am sure the file exists, as I have loaded the .shp file into QGIS and it pops up as an image. I should have read/write access too as I am an admin on the machine and it is just in my dropbox.

    – André.B
    7 hours ago











  • Try moving it out of Dropbox to a local drive. There may be an issue with the path causing QGIS to reject it. What you are looking to do should be pretty simple in QGIS. Which version of QGIS are you using?

    – Keagan Allan
    7 hours ago











  • The tool may require a raster input, which gives you this error.

    – Keagan Allan
    6 hours ago






  • 1





    Ok, try converting the polyline to a raster. The Proximity tool in QGIS needs a raster input. Play around with the settings as per the tool's help: docs.qgis.org/2.8/en/docs/user_manual/processing_algs/gdalogr/…. Take note, it is still an intensive process, I am testing it for fun now and it has been running for 30mins and still going...

    – Keagan Allan
    6 hours ago
















2












2








2


1






I want to create a raster with a 25 metre × 25 metre resolution, where each cell contains the distance to the nearest coastline, as calculated from the center of the cell. To do this, all I have is a shapefile of the coastlines of New Zealand.



I have tried following Dominic Roye's tutorial for doing it in R which works... kind of. It is fine down to about a 1 km × 1 km resolution but if I try to go any higher the RAM it requires well exceeds that available on my PC (~ 70 gb of RAM required) or any other that I have access too. In saying that, I think this is a limitation of R and I suspect that QGIS might have a more computationally efficient way of creating this raster, but I am new to it and I can't quite figure out how to do it.



I have tried following Creating raster with distance to feature using QGIS? to create it in QGIS but it returns this error:




_core.QgsProcessingException: Could not load source layer for INPUT: C:/..../Coastline/nz-coastlines-and-islands-polygons-topo-150k.shp not
found




and I am not sure why.



Does anyone have any suggestions of what might be going wrong or an alternative way of doing this?










share|improve this question









New contributor



André.B is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











I want to create a raster with a 25 metre × 25 metre resolution, where each cell contains the distance to the nearest coastline, as calculated from the center of the cell. To do this, all I have is a shapefile of the coastlines of New Zealand.



I have tried following Dominic Roye's tutorial for doing it in R which works... kind of. It is fine down to about a 1 km × 1 km resolution but if I try to go any higher the RAM it requires well exceeds that available on my PC (~ 70 gb of RAM required) or any other that I have access too. In saying that, I think this is a limitation of R and I suspect that QGIS might have a more computationally efficient way of creating this raster, but I am new to it and I can't quite figure out how to do it.



I have tried following Creating raster with distance to feature using QGIS? to create it in QGIS but it returns this error:




_core.QgsProcessingException: Could not load source layer for INPUT: C:/..../Coastline/nz-coastlines-and-islands-polygons-topo-150k.shp not
found




and I am not sure why.



Does anyone have any suggestions of what might be going wrong or an alternative way of doing this?







qgis shapefile r rasterization






share|improve this question









New contributor



André.B is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










share|improve this question









New contributor



André.B is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








share|improve this question




share|improve this question








edited 8 hours ago









PolyGeo

55.2k17 gold badges88 silver badges259 bronze badges




55.2k17 gold badges88 silver badges259 bronze badges






New contributor



André.B is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








asked 9 hours ago









André.BAndré.B

1144 bronze badges




1144 bronze badges




New contributor



André.B is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




New contributor




André.B is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.













  • 1





    Are you running a script to do this? Or are you using the tools in QGIS? Something to check, even though it sounds like it should - check the file actually exists where you say it does...also check that you have read and write access to that particular folder.

    – Keagan Allan
    7 hours ago











  • Currently using the tools but I am quite keen to learn the script, just not sure where to start. I am sure the file exists, as I have loaded the .shp file into QGIS and it pops up as an image. I should have read/write access too as I am an admin on the machine and it is just in my dropbox.

    – André.B
    7 hours ago











  • Try moving it out of Dropbox to a local drive. There may be an issue with the path causing QGIS to reject it. What you are looking to do should be pretty simple in QGIS. Which version of QGIS are you using?

    – Keagan Allan
    7 hours ago











  • The tool may require a raster input, which gives you this error.

    – Keagan Allan
    6 hours ago






  • 1





    Ok, try converting the polyline to a raster. The Proximity tool in QGIS needs a raster input. Play around with the settings as per the tool's help: docs.qgis.org/2.8/en/docs/user_manual/processing_algs/gdalogr/…. Take note, it is still an intensive process, I am testing it for fun now and it has been running for 30mins and still going...

    – Keagan Allan
    6 hours ago
















  • 1





    Are you running a script to do this? Or are you using the tools in QGIS? Something to check, even though it sounds like it should - check the file actually exists where you say it does...also check that you have read and write access to that particular folder.

    – Keagan Allan
    7 hours ago











  • Currently using the tools but I am quite keen to learn the script, just not sure where to start. I am sure the file exists, as I have loaded the .shp file into QGIS and it pops up as an image. I should have read/write access too as I am an admin on the machine and it is just in my dropbox.

    – André.B
    7 hours ago











  • Try moving it out of Dropbox to a local drive. There may be an issue with the path causing QGIS to reject it. What you are looking to do should be pretty simple in QGIS. Which version of QGIS are you using?

    – Keagan Allan
    7 hours ago











  • The tool may require a raster input, which gives you this error.

    – Keagan Allan
    6 hours ago






  • 1





    Ok, try converting the polyline to a raster. The Proximity tool in QGIS needs a raster input. Play around with the settings as per the tool's help: docs.qgis.org/2.8/en/docs/user_manual/processing_algs/gdalogr/…. Take note, it is still an intensive process, I am testing it for fun now and it has been running for 30mins and still going...

    – Keagan Allan
    6 hours ago










1




1





Are you running a script to do this? Or are you using the tools in QGIS? Something to check, even though it sounds like it should - check the file actually exists where you say it does...also check that you have read and write access to that particular folder.

– Keagan Allan
7 hours ago





Are you running a script to do this? Or are you using the tools in QGIS? Something to check, even though it sounds like it should - check the file actually exists where you say it does...also check that you have read and write access to that particular folder.

– Keagan Allan
7 hours ago













Currently using the tools but I am quite keen to learn the script, just not sure where to start. I am sure the file exists, as I have loaded the .shp file into QGIS and it pops up as an image. I should have read/write access too as I am an admin on the machine and it is just in my dropbox.

– André.B
7 hours ago





Currently using the tools but I am quite keen to learn the script, just not sure where to start. I am sure the file exists, as I have loaded the .shp file into QGIS and it pops up as an image. I should have read/write access too as I am an admin on the machine and it is just in my dropbox.

– André.B
7 hours ago













Try moving it out of Dropbox to a local drive. There may be an issue with the path causing QGIS to reject it. What you are looking to do should be pretty simple in QGIS. Which version of QGIS are you using?

– Keagan Allan
7 hours ago





Try moving it out of Dropbox to a local drive. There may be an issue with the path causing QGIS to reject it. What you are looking to do should be pretty simple in QGIS. Which version of QGIS are you using?

– Keagan Allan
7 hours ago













The tool may require a raster input, which gives you this error.

– Keagan Allan
6 hours ago





The tool may require a raster input, which gives you this error.

– Keagan Allan
6 hours ago




1




1





Ok, try converting the polyline to a raster. The Proximity tool in QGIS needs a raster input. Play around with the settings as per the tool's help: docs.qgis.org/2.8/en/docs/user_manual/processing_algs/gdalogr/…. Take note, it is still an intensive process, I am testing it for fun now and it has been running for 30mins and still going...

– Keagan Allan
6 hours ago







Ok, try converting the polyline to a raster. The Proximity tool in QGIS needs a raster input. Play around with the settings as per the tool's help: docs.qgis.org/2.8/en/docs/user_manual/processing_algs/gdalogr/…. Take note, it is still an intensive process, I am testing it for fun now and it has been running for 30mins and still going...

– Keagan Allan
6 hours ago












2 Answers
2






active

oldest

votes


















2
















With PyQGIS and GDAL python library is not very difficult to do that. You need geo transform parameters (top left x, x pixel resolution, rotation, top left y, rotation, n-s pixel resolution) and rows and columns number for creating resulting raster. For calculating the distance to the nearest coastline, it is necessary a vector layer for representing coastline.



With PyQGIS, each raster point as center of the cell is calculated and its distance to coastline is measured by using 'closestSegmentWithContext' method from QgsGeometry class. GDAL python library is used for producing a raster with these distance values in rows x columns array.



Following code was used for creating a distance raster (25 m × 25 m resolution and 1000 rows x 1000 columns) starting in point (397106.7689872353, 4499634.06675821); near to west coastline of USA.



from osgeo import gdal, osr
import numpy as np
from math import sqrt

registry = QgsProject.instance()

line = registry.mapLayersByName('shoreline_10N')

crs = line[0].crs()

wkt = crs.toWkt()

feats_line = [ feat for feat in line[0].getFeatures()]

pt = QgsPoint(397106.7689872353, 4499634.06675821)

xSize = 25
ySize = 25

rows = 1000
cols = 1000

raster = [ [] for i in range(cols) ]

x = xSize/2
y = - ySize/2

for i in range(rows):
for j in range(cols):
point = QgsPointXY(pt.x() + x, pt.y() + y)
tupla = feats_line[0].geometry().closestSegmentWithContext(point)
raster[i].append(sqrt(tupla[0]))

x += xSize
x = xSize/2
y -= ySize

data = np.array(raster)

# Create gtif file
driver = gdal.GetDriverByName("GTiff")

output_file = "/home/zeito/pyqgis_data/distance_raster.tif"

dst_ds = driver.Create(output_file,
cols,
rows,
1,
gdal.GDT_Float32)

#writting output raster
dst_ds.GetRasterBand(1).WriteArray( data )

transform = (pt.x(), xSize, 0, pt.y(), 0, -ySize)

#setting extension of output raster
# top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution
dst_ds.SetGeoTransform(transform)

# setting spatial reference of output raster
srs = osr.SpatialReference()
srs.ImportFromWkt(wkt)
dst_ds.SetProjection( srs.ExportToWkt() )

dst_ds = None


After running above code, resulting raster was loaded in QGIS and it looks as in following image (pseudocolor with 5 classes and Spectral ramp). Projection is UTM 10 N (EPSG:32610)



enter image description here






share|improve this answer




























  • This might not be an issue but one thing that I am a little worried about is that the polygon is of New Zealand and its surrounding islands which means it includes a huge amount of the surrounding sea. I am trying to get my head around the code, but with your example would I be able to set the value for all the cells at sea to NA? I am really only interested in the distance to the sea from points on land.

    – André.B
    3 hours ago



















1
















I would try other way around. If you are using poligon of NZ then convert polygon edges to line. After that create buffer on the boundary for every 25 meters of distance from boundary(maybe centorid might help in determing when to stop). Then cut buffers out with polygon and then convert that polygons to raster.
I am not sure this would work but definitely you gonna need less RAM. And PostGiS is great when you have performance issues.



Hope it might help at least a little bit :)






share|improve this answer




























    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "79"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });







    André.B is a new contributor. Be nice, and check out our Code of Conduct.










    draft saved

    draft discarded
















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f336427%2fcreating-raster-where-each-cell-records-distance-to-sea%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2
















    With PyQGIS and GDAL python library is not very difficult to do that. You need geo transform parameters (top left x, x pixel resolution, rotation, top left y, rotation, n-s pixel resolution) and rows and columns number for creating resulting raster. For calculating the distance to the nearest coastline, it is necessary a vector layer for representing coastline.



    With PyQGIS, each raster point as center of the cell is calculated and its distance to coastline is measured by using 'closestSegmentWithContext' method from QgsGeometry class. GDAL python library is used for producing a raster with these distance values in rows x columns array.



    Following code was used for creating a distance raster (25 m × 25 m resolution and 1000 rows x 1000 columns) starting in point (397106.7689872353, 4499634.06675821); near to west coastline of USA.



    from osgeo import gdal, osr
    import numpy as np
    from math import sqrt

    registry = QgsProject.instance()

    line = registry.mapLayersByName('shoreline_10N')

    crs = line[0].crs()

    wkt = crs.toWkt()

    feats_line = [ feat for feat in line[0].getFeatures()]

    pt = QgsPoint(397106.7689872353, 4499634.06675821)

    xSize = 25
    ySize = 25

    rows = 1000
    cols = 1000

    raster = [ [] for i in range(cols) ]

    x = xSize/2
    y = - ySize/2

    for i in range(rows):
    for j in range(cols):
    point = QgsPointXY(pt.x() + x, pt.y() + y)
    tupla = feats_line[0].geometry().closestSegmentWithContext(point)
    raster[i].append(sqrt(tupla[0]))

    x += xSize
    x = xSize/2
    y -= ySize

    data = np.array(raster)

    # Create gtif file
    driver = gdal.GetDriverByName("GTiff")

    output_file = "/home/zeito/pyqgis_data/distance_raster.tif"

    dst_ds = driver.Create(output_file,
    cols,
    rows,
    1,
    gdal.GDT_Float32)

    #writting output raster
    dst_ds.GetRasterBand(1).WriteArray( data )

    transform = (pt.x(), xSize, 0, pt.y(), 0, -ySize)

    #setting extension of output raster
    # top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution
    dst_ds.SetGeoTransform(transform)

    # setting spatial reference of output raster
    srs = osr.SpatialReference()
    srs.ImportFromWkt(wkt)
    dst_ds.SetProjection( srs.ExportToWkt() )

    dst_ds = None


    After running above code, resulting raster was loaded in QGIS and it looks as in following image (pseudocolor with 5 classes and Spectral ramp). Projection is UTM 10 N (EPSG:32610)



    enter image description here






    share|improve this answer




























    • This might not be an issue but one thing that I am a little worried about is that the polygon is of New Zealand and its surrounding islands which means it includes a huge amount of the surrounding sea. I am trying to get my head around the code, but with your example would I be able to set the value for all the cells at sea to NA? I am really only interested in the distance to the sea from points on land.

      – André.B
      3 hours ago
















    2
















    With PyQGIS and GDAL python library is not very difficult to do that. You need geo transform parameters (top left x, x pixel resolution, rotation, top left y, rotation, n-s pixel resolution) and rows and columns number for creating resulting raster. For calculating the distance to the nearest coastline, it is necessary a vector layer for representing coastline.



    With PyQGIS, each raster point as center of the cell is calculated and its distance to coastline is measured by using 'closestSegmentWithContext' method from QgsGeometry class. GDAL python library is used for producing a raster with these distance values in rows x columns array.



    Following code was used for creating a distance raster (25 m × 25 m resolution and 1000 rows x 1000 columns) starting in point (397106.7689872353, 4499634.06675821); near to west coastline of USA.



    from osgeo import gdal, osr
    import numpy as np
    from math import sqrt

    registry = QgsProject.instance()

    line = registry.mapLayersByName('shoreline_10N')

    crs = line[0].crs()

    wkt = crs.toWkt()

    feats_line = [ feat for feat in line[0].getFeatures()]

    pt = QgsPoint(397106.7689872353, 4499634.06675821)

    xSize = 25
    ySize = 25

    rows = 1000
    cols = 1000

    raster = [ [] for i in range(cols) ]

    x = xSize/2
    y = - ySize/2

    for i in range(rows):
    for j in range(cols):
    point = QgsPointXY(pt.x() + x, pt.y() + y)
    tupla = feats_line[0].geometry().closestSegmentWithContext(point)
    raster[i].append(sqrt(tupla[0]))

    x += xSize
    x = xSize/2
    y -= ySize

    data = np.array(raster)

    # Create gtif file
    driver = gdal.GetDriverByName("GTiff")

    output_file = "/home/zeito/pyqgis_data/distance_raster.tif"

    dst_ds = driver.Create(output_file,
    cols,
    rows,
    1,
    gdal.GDT_Float32)

    #writting output raster
    dst_ds.GetRasterBand(1).WriteArray( data )

    transform = (pt.x(), xSize, 0, pt.y(), 0, -ySize)

    #setting extension of output raster
    # top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution
    dst_ds.SetGeoTransform(transform)

    # setting spatial reference of output raster
    srs = osr.SpatialReference()
    srs.ImportFromWkt(wkt)
    dst_ds.SetProjection( srs.ExportToWkt() )

    dst_ds = None


    After running above code, resulting raster was loaded in QGIS and it looks as in following image (pseudocolor with 5 classes and Spectral ramp). Projection is UTM 10 N (EPSG:32610)



    enter image description here






    share|improve this answer




























    • This might not be an issue but one thing that I am a little worried about is that the polygon is of New Zealand and its surrounding islands which means it includes a huge amount of the surrounding sea. I am trying to get my head around the code, but with your example would I be able to set the value for all the cells at sea to NA? I am really only interested in the distance to the sea from points on land.

      – André.B
      3 hours ago














    2














    2










    2









    With PyQGIS and GDAL python library is not very difficult to do that. You need geo transform parameters (top left x, x pixel resolution, rotation, top left y, rotation, n-s pixel resolution) and rows and columns number for creating resulting raster. For calculating the distance to the nearest coastline, it is necessary a vector layer for representing coastline.



    With PyQGIS, each raster point as center of the cell is calculated and its distance to coastline is measured by using 'closestSegmentWithContext' method from QgsGeometry class. GDAL python library is used for producing a raster with these distance values in rows x columns array.



    Following code was used for creating a distance raster (25 m × 25 m resolution and 1000 rows x 1000 columns) starting in point (397106.7689872353, 4499634.06675821); near to west coastline of USA.



    from osgeo import gdal, osr
    import numpy as np
    from math import sqrt

    registry = QgsProject.instance()

    line = registry.mapLayersByName('shoreline_10N')

    crs = line[0].crs()

    wkt = crs.toWkt()

    feats_line = [ feat for feat in line[0].getFeatures()]

    pt = QgsPoint(397106.7689872353, 4499634.06675821)

    xSize = 25
    ySize = 25

    rows = 1000
    cols = 1000

    raster = [ [] for i in range(cols) ]

    x = xSize/2
    y = - ySize/2

    for i in range(rows):
    for j in range(cols):
    point = QgsPointXY(pt.x() + x, pt.y() + y)
    tupla = feats_line[0].geometry().closestSegmentWithContext(point)
    raster[i].append(sqrt(tupla[0]))

    x += xSize
    x = xSize/2
    y -= ySize

    data = np.array(raster)

    # Create gtif file
    driver = gdal.GetDriverByName("GTiff")

    output_file = "/home/zeito/pyqgis_data/distance_raster.tif"

    dst_ds = driver.Create(output_file,
    cols,
    rows,
    1,
    gdal.GDT_Float32)

    #writting output raster
    dst_ds.GetRasterBand(1).WriteArray( data )

    transform = (pt.x(), xSize, 0, pt.y(), 0, -ySize)

    #setting extension of output raster
    # top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution
    dst_ds.SetGeoTransform(transform)

    # setting spatial reference of output raster
    srs = osr.SpatialReference()
    srs.ImportFromWkt(wkt)
    dst_ds.SetProjection( srs.ExportToWkt() )

    dst_ds = None


    After running above code, resulting raster was loaded in QGIS and it looks as in following image (pseudocolor with 5 classes and Spectral ramp). Projection is UTM 10 N (EPSG:32610)



    enter image description here






    share|improve this answer















    With PyQGIS and GDAL python library is not very difficult to do that. You need geo transform parameters (top left x, x pixel resolution, rotation, top left y, rotation, n-s pixel resolution) and rows and columns number for creating resulting raster. For calculating the distance to the nearest coastline, it is necessary a vector layer for representing coastline.



    With PyQGIS, each raster point as center of the cell is calculated and its distance to coastline is measured by using 'closestSegmentWithContext' method from QgsGeometry class. GDAL python library is used for producing a raster with these distance values in rows x columns array.



    Following code was used for creating a distance raster (25 m × 25 m resolution and 1000 rows x 1000 columns) starting in point (397106.7689872353, 4499634.06675821); near to west coastline of USA.



    from osgeo import gdal, osr
    import numpy as np
    from math import sqrt

    registry = QgsProject.instance()

    line = registry.mapLayersByName('shoreline_10N')

    crs = line[0].crs()

    wkt = crs.toWkt()

    feats_line = [ feat for feat in line[0].getFeatures()]

    pt = QgsPoint(397106.7689872353, 4499634.06675821)

    xSize = 25
    ySize = 25

    rows = 1000
    cols = 1000

    raster = [ [] for i in range(cols) ]

    x = xSize/2
    y = - ySize/2

    for i in range(rows):
    for j in range(cols):
    point = QgsPointXY(pt.x() + x, pt.y() + y)
    tupla = feats_line[0].geometry().closestSegmentWithContext(point)
    raster[i].append(sqrt(tupla[0]))

    x += xSize
    x = xSize/2
    y -= ySize

    data = np.array(raster)

    # Create gtif file
    driver = gdal.GetDriverByName("GTiff")

    output_file = "/home/zeito/pyqgis_data/distance_raster.tif"

    dst_ds = driver.Create(output_file,
    cols,
    rows,
    1,
    gdal.GDT_Float32)

    #writting output raster
    dst_ds.GetRasterBand(1).WriteArray( data )

    transform = (pt.x(), xSize, 0, pt.y(), 0, -ySize)

    #setting extension of output raster
    # top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution
    dst_ds.SetGeoTransform(transform)

    # setting spatial reference of output raster
    srs = osr.SpatialReference()
    srs.ImportFromWkt(wkt)
    dst_ds.SetProjection( srs.ExportToWkt() )

    dst_ds = None


    After running above code, resulting raster was loaded in QGIS and it looks as in following image (pseudocolor with 5 classes and Spectral ramp). Projection is UTM 10 N (EPSG:32610)



    enter image description here







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 4 hours ago

























    answered 4 hours ago









    xunilkxunilk

    15.4k3 gold badges19 silver badges43 bronze badges




    15.4k3 gold badges19 silver badges43 bronze badges
















    • This might not be an issue but one thing that I am a little worried about is that the polygon is of New Zealand and its surrounding islands which means it includes a huge amount of the surrounding sea. I am trying to get my head around the code, but with your example would I be able to set the value for all the cells at sea to NA? I am really only interested in the distance to the sea from points on land.

      – André.B
      3 hours ago



















    • This might not be an issue but one thing that I am a little worried about is that the polygon is of New Zealand and its surrounding islands which means it includes a huge amount of the surrounding sea. I am trying to get my head around the code, but with your example would I be able to set the value for all the cells at sea to NA? I am really only interested in the distance to the sea from points on land.

      – André.B
      3 hours ago

















    This might not be an issue but one thing that I am a little worried about is that the polygon is of New Zealand and its surrounding islands which means it includes a huge amount of the surrounding sea. I am trying to get my head around the code, but with your example would I be able to set the value for all the cells at sea to NA? I am really only interested in the distance to the sea from points on land.

    – André.B
    3 hours ago





    This might not be an issue but one thing that I am a little worried about is that the polygon is of New Zealand and its surrounding islands which means it includes a huge amount of the surrounding sea. I am trying to get my head around the code, but with your example would I be able to set the value for all the cells at sea to NA? I am really only interested in the distance to the sea from points on land.

    – André.B
    3 hours ago













    1
















    I would try other way around. If you are using poligon of NZ then convert polygon edges to line. After that create buffer on the boundary for every 25 meters of distance from boundary(maybe centorid might help in determing when to stop). Then cut buffers out with polygon and then convert that polygons to raster.
    I am not sure this would work but definitely you gonna need less RAM. And PostGiS is great when you have performance issues.



    Hope it might help at least a little bit :)






    share|improve this answer






























      1
















      I would try other way around. If you are using poligon of NZ then convert polygon edges to line. After that create buffer on the boundary for every 25 meters of distance from boundary(maybe centorid might help in determing when to stop). Then cut buffers out with polygon and then convert that polygons to raster.
      I am not sure this would work but definitely you gonna need less RAM. And PostGiS is great when you have performance issues.



      Hope it might help at least a little bit :)






      share|improve this answer




























        1














        1










        1









        I would try other way around. If you are using poligon of NZ then convert polygon edges to line. After that create buffer on the boundary for every 25 meters of distance from boundary(maybe centorid might help in determing when to stop). Then cut buffers out with polygon and then convert that polygons to raster.
        I am not sure this would work but definitely you gonna need less RAM. And PostGiS is great when you have performance issues.



        Hope it might help at least a little bit :)






        share|improve this answer













        I would try other way around. If you are using poligon of NZ then convert polygon edges to line. After that create buffer on the boundary for every 25 meters of distance from boundary(maybe centorid might help in determing when to stop). Then cut buffers out with polygon and then convert that polygons to raster.
        I am not sure this would work but definitely you gonna need less RAM. And PostGiS is great when you have performance issues.



        Hope it might help at least a little bit :)







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 7 hours ago









        KumbraKumbra

        497 bronze badges




        497 bronze badges


























            André.B is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded

















            André.B is a new contributor. Be nice, and check out our Code of Conduct.













            André.B is a new contributor. Be nice, and check out our Code of Conduct.












            André.B is a new contributor. Be nice, and check out our Code of Conduct.
















            Thanks for contributing an answer to Geographic Information Systems Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f336427%2fcreating-raster-where-each-cell-records-distance-to-sea%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

            Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

            Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...