I wasn't able either to export with raster
, but an alternative would be to use writeJPEG()
from package jpeg
. Note that:
writeJPEG()
expects an array as input: using as.array(r)
does the trick
writeJPEG()
expects RGB values between 0-1. In my case, reading with raster, they were 0-255, so just rescale!
Your example didn't work for me, but here is one, using the R logo, importing it with raster()
adding some (truly beautiful) art, and exporting to jpg:
library(raster)
library(jpeg)
r <- stack(system.file("img","Rlogo.jpg",package="jpeg"))
r$Rlogo.1 <- getValues(r$Rlogo.1)/2
plotRGB(r)
writeJPEG(as.array(r)/255, "out.jpeg")
edit: even more specific, the problem lies with .astype(uint16)
. Without this conversion, it loads fine. Also show(limg.read())
also works
original:
The problem lies with the show(rio.open(georeferenced.tif))
. The data is saved properly, and when loaded all operations you would want to perform should work fine. if you're only interested in showing the image, you can show(limg.read([1,2,3])
Further, an (ugly) workaround would be to re-load and save the data. Then you can also resample so your rasters overlap (for calculations). When performed directly on the PNG, this crashed my kernel (sounds like a bug).
I also changed the arguments for the rasterio.open('w')
to use the shape of your img
in stead of the reference image in case they do not exactly match. optionally, you could maybe resample your georeferenced image, so
import rasterio as rio
from rasterio.enums import Resampling
from rasterio.plot import show
#Input png image, to convert as geotiff
img = rio.open('/path/to.png')
img = img.read([1,2,3])
img = img.astype('uint16')
show(img) #shows true color
# Input image for coordinate reference
with rio.open('/path/to/reference.tif') as naip:
#open georeferenced.tif for writing
with rio.open(
'georeferenced.tif',
'w',
driver='GTiff',
count=img.shape[0],
height=img.shape[1],
width=img.shape[2],
dtype=img.dtype,
crs=naip.crs,
transform=naip.transform,
) as dst:
dst.write(img)
with rio.open('georeferenced.tif') as limg:
show(limg) #1 band only shows
show(limg.read([1,2,3])) #shows true color
#resample so pixels overlap with reference
limg = limg.read(out_shape=(3,naip.shape[0],naip.shape[1]),
resampling=Resampling.nearest)
with rio.open('resampled.tif','w',
driver='GTiff',
count=limg.shape[0],
height=limg.shape[1],
width=limg.shape[2],
dtype=limg.dtype,
crs=naip.crs,
transform=naip.transform,
) as dst:
dst.write(limg)
The writing is a bit verbose, but a passing of **naip.profile
does not work, since the count is different, unless your reference layer has the same number of bands. an alternative would be storing naip.profile, and then changing the count manually.
Best Answer
eventually this worked for me: