3

I'm trying to import an .asc file in python to clip it with a shapefile. For the clipping I'll use:

import earthpy.clip as cl
clip = cl.clip_shp(shp_file, asc_file)

However this won't work since my .asc doesn't have a CRS. This is how the header of the .asc looks like:

ncols         1900
nrows         1400
xllcorner     182900
yllcorner     326300
cellsize      10
NODATA_value  -999.990

This is how I import the .asc file

import rasterio as rio
asc_loc = r'file.asc'
raster = rio.open(asc_loc)
print(raster.crs)

The print shows none

Question: how can I add a the CRS to an imported .asc file? (Preferably with rastario or geopandas.)

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Dylan_w
  • 472
  • 5
  • 19
  • Do you know the .asc coordinate system? For example, EPSG code? – LuisTavares Nov 07 '19 at 14:45
  • An asc. file can be plotted without projection right? But I think it's: EPSG: 19914 (Dutch coordinate system) – Dylan_w Nov 08 '19 at 14:34
  • 1
    Right and provided your raster and shapefile have the same CRS, you can also clip without adding a CRS to the raster. Nevertheless, I'm going to give the answer for the given EPSG. – LuisTavares Nov 08 '19 at 17:38

2 Answers2

3

To add a CRS to a raster

import rasterio.crs

crs = rasterio.crs.CRS({"init": "epsg:19914"})  
with rasterio.open('/path/to/file.format') as src:
    src.crs = crs
print (src.crs)

If that doesn't work, and since the CRS will never be saved to an asc.file,

better use gdal_translate first, from the command line, to convert to Geotiff, before using the raster with rasterio:

gdal_translate -of "GTiff" -a_srs EPSG:19914 in.asc out.tif
LuisTavares
  • 2,146
  • 2
  • 12
  • 18
  • Thanks, I found another question here: https://gis.stackexchange.com/questions/42584/how-to-call-gdal-translate-from-python-code combined with your answer I managed to convert the .asc file into a geotiff and adding a CRS. – Dylan_w Nov 11 '19 at 07:35
  • 1
    I found I had to pass the crs as a parameter in the open() function, like `with rasterio.open('/path/to/file.format', crs="EPSG:19914") as src:` – Graham S Jul 28 '20 at 20:45
1

Looks like you are missing a .prj file.

If you have the .prj file, it should be stored along with your .asc file having same name

raster_image.asc
raster_image.prj

.prj file will contain the spatial reference information.

Zeeshan
  • 1,078
  • 9
  • 14