我正在尝试使用一个学校项目的numpy/scipy的k-means算法执行图像量化(减少图像的颜色数)。algirithm很好用,但我还想计算算法每次迭代的误差之和,即样本到其最近的聚类中心的距离之和(这是项目任务之一)。 我找不到任何kmeans的numpy方法或其他快速、优雅的方式来实现这一点。 有这样的方法吗?如果没有,最好的方法是什么?我的目标是最小化现有kmeans算法的任何重新实现。在
下面我添加了我的代码
import scipy.cluster.vq as vq
def quantize_rgb(im_orig, n_quant, n_iter):
"""
A function that performs optimal quantization of a given RGB image.
:param im_orig: the input RGB image to be quantized (float32 image with values in [0, 1])
:param n_quant: the number of intensities the output image should have
:param n_iter: the maximum number of iterations of the optimization procedure (may converge earlier.)
"""
reshaped_im = im_orig.reshape(im_orig.shape[0] * im_orig.shape[1], 3)
centroids, label = vq.kmeans2(reshaped_im, n_quant, n_iter)
reshaped_im = centroids[label]
im_quant = reshaped_im.reshape(im_orig.shape[0], im_orig.shape[1], 3)
return im_quant
简单使用
一次只进行一次迭代。在
相关问题 更多 >
编程相关推荐