Skip to content

Instantly share code, notes, and snippets.

@Martin-Jung
Last active August 7, 2019 20:42
Show Gist options
  • Save Martin-Jung/6117c016be57d8526d18b0198d61b6f9 to your computer and use it in GitHub Desktop.
Save Martin-Jung/6117c016be57d8526d18b0198d61b6f9 to your computer and use it in GitHub Desktop.
import os
import subprocess
import rasterio
def extract_bands(file, bands=None):
dataset = rasterio.open(file)
if bands is None:
bands = range(1, dataset.count + 1)
elif isinstance(bands, int):
bands = [bands]
meta = dataset.meta.copy()
meta.update({
'count': 1
})
outfiles = []
#descriptions = rasterio.open(file).descriptions
for band in bands:
outfile = os.path.splitext(file)[0] + "_band_{}".format(band) + os.path.splitext(file)[1]
with rasterio.open(outfile, 'w', **meta) as dst:
dst.write(dataset.read(band), 1)
#if descriptions[band - 1] is not None:
# dst.set_band_description(1, descriptions[band-1])
outfiles.append(outfile)
return outfiles
f = 'AMPHIBIA_STACK_ESH_NodupsLC_927_sub1_fraction_10km-0000001536-0000000000.tif'
os.path.exists(f)
extract_bands(f)
library(stars)
library(tidyverse)
tif <- 'AMPHIBIA_STACK_ESH_NodupsLC_927_sub1_fraction_10km-0000001536-0000003072.tif'
x <- read_stars(tif,proxy = F)
t1 <- Sys.time()
for(i in stars::st_get_dimension_values(x,'band')){
y <- x %>% slice(index = i, along = "band")
write_stars(y,dsn = paste0('C:/Users/Martin/Downloads/drive-download-20190807T191621Z-001/','band',i,'.tif'),
type = 'UInt16')
}
Sys.time() - t1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment