-
Notifications
You must be signed in to change notification settings - Fork 2
Create dataset from existing dataset
Steve Loveless edited this page Jan 6, 2023
·
1 revision
Sometimes you want to create a new dataset (raster) that's similar to one you already have, but just with some altered pixel values. That can be accomplished a number of ways, but here's one.
require 'ffi-gdal'
require 'gdal'
source_path = 'my_source.tif'
dest_path = 'my_dest.tif'
pixel_multiplier = 3476.291264111359
source_dataset = GDAL::Dataset.open(source_path, 'r')
source_band = source_dataset.raster_band(1)
# Get the pixels from the band as an NArray. NArray makes it easy to
# change pixels values, which can be written back to the new dataset.
source_pixels = source_band.to_na
# Multiple each source pixel by some value.
#
# This is just a simple example, but you could alter the source pixels
# in any way at this point; as long as you end up with an NArray that
# are the same dimensions of the destination raster (ex. the NArray
# must be 640x480 if the destination raster is 640x480), you'll be good.
dest_pixels = source_pixels * pixel_multiplier
driver = GDAL::Driver.by_name('GTiff')
# Using the block format of GDAL::Driver#create_dataset here, which closes
# the file at the end of the block.
driver.create_dataset(dest_path, source_band.x_size, source_band.y_size, data_type: :GDT_Float64) do |dest_dataset|
dest_dataset.projection = source_dataset.projection
dest_dataset.geo_transform = source_dataset.geo_transform
dest_band = dest_dataset.raster_band(1)
dest_band.write_xy_narray(dest_pixels)
end
And that's it! That code:
- Opens the source raster file
- Reads pixel values from the first raster band into an NArray
- Creates a new dataset called "my_dest.tif" using the same dimensions, projection and geo_transform (object that describes the orientation of the raster in space).
- Writes the transformed pixel data, as an NArray, to the new raster.