Improved the getCentroids function