Function to downsample a 2D matrix such as images