Looking over your code, I don't see how it will be faster than pure Python. It's exclusively calling Python methods (rasterio methods, np.dstack is Python) and those aren't executed any faster just because the function is compiled with Cython.
The key to speeding things up is in here:
# Iterate over rows and columns in this block
for x in xrange(x_wsize):
for y in xrange(y_wsize):
t = tuple(in_arr[x, y])
if t not in d:
d[t] = index
index += 1
out_arr[x_start + x, y_start + y] = d[t]
See if you can change this from a slow Python loop over all pixels in the array to code that exploits Numpy's much faster array operations. It'll be tricky, no doubt, because of the index accounting, but I think you could trade memory in the form of more numpy arrays/masks for improved speed.
Alternatively, optimize it for Cython by using cdef
for all the variables in the loop, particularly x
and y
and using typed memory views for array access. I think you might find rasterio's io_multi_cfloat64 a useful example.
You can read specific bands in a single call using rasterio by passing a list/tuple of band numbers (Following the GDAL convention, bands are indexed from 1):
import rasterio
rasterio.__version__
'1.0a8'
dataset = rasterio.open('multiband.tif')
dataset.count
4
dataset.read((1,2)) #read 1st two bands into an array.
array([[[ 85, 98, 75, ..., 53, 55, 55],
[ 84, 94, 76, ..., 54, 55, 54],
[ 68, 60, 55, ..., 53, 54, 53],
...,
[ 67, 67, 66, ..., 63, 63, 62],
[255, 255, 255, ..., 255, 255, 255],
[255, 255, 255, ..., 255, 255, 255]],
[[ 78, 88, 65, ..., 41, 43, 45],
[ 77, 84, 66, ..., 42, 43, 44],
[ 61, 51, 46, ..., 41, 42, 43],
...,
[ 77, 77, 77, ..., 71, 70, 69],
[255, 255, 255, ..., 255, 207, 255],
[255, 255, 255, ..., 191, 0, 135]]], dtype=uint8)
Best Answer
I was just looking for a similar technique and found this method based on the rasterio/merge.py function given here.
You can check out my example with two orthomosaic images here.
However, I'm not sure this is the best method...no doubt the dude himself @sgillies has more insight into this!