I am in the process of converting some matlab code to python. I working with a 3d volume h x w x d represented as an numpy array, I am extracting smaller 3d patches from this volume using the function from SO here. So if I have 32x32x32 array and extract 16x16x16 patches I end up with a shape (2, 2, 2, 16, 16, 16) After processing each patch I would like to put it back into shape h x w x d basically reverse window_nd What would be the idiomatic numpy way without looping each dimension? Since I also need to work with 2d and 4d data I would like to avoid creating a function for each dimension.
1 Answer
Normally, writing back to as_strided views is not advised because it can cause race conditions, but since you only made blocks, this should work:
original_shaped_array = windowed_array.transpose(0,3,1,4,2,5).reshape(32,32,32) Additionally, if you never copied the windowed array, and do calculations in-place, the data should be changed in the original array - a windowed view is simply a new view into the same data. Don't do this if there is any overlap
2 Comments
Hamza Yerlikaya
basically each patch is sent to a segmentation algorithm that returns a new patch of the same size segmented. So original patch is untouched used as read only. I am actually tring to combine these segmented patches back into original shape
as_stridedcreates aviewof the source array, so it does not reorder anything. What kind of processing are you doing? Depending on the processing the changes might already appear in the source. Or reshaping might be enough. Sometimes a tranpose is need as well, though I'm not sure that's ever the case withas_stridedarrays.reshapeandtranspose, and do the reverse with a complementary mix. Most examples work with 2d arrays (e.g. images) but the ideas extend to 3d.