I suggest to pass kernel size as a parameter, because the first iteration produces 1x1. It is not enough for normal test.

Also there are some issues when kernelSize > roiSize.

Non-square kernels is OK