You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Numpy的图像量化旧代码报错,如何更新以正常运行?

图像量化代码适配新版Python/Scipy的问题

我参考了一篇旧博客的图像量化示例代码,但由于Python、Numpy和Scipy版本更新,代码运行报错。

原代码如下:

from pylab import imread,imshow,figure,show,subplot
from numpy import reshape,uint8,flipud
from scipy.cluster.vq import kmeans,vq

img = imread('clearsky.jpg')

# reshaping the pixels matrix
pixel = reshape(img,(img.shape[0]*img.shape[1],3))

# performing the clustering
# print(type(pixel))
centroids,_ = kmeans(pixel,6) # six colors will be found
# quantization
qnt,_ = vq(pixel,centroids)

# reshaping the result of the quantization
centers_idx = reshape(qnt,(img.shape[0],img.shape[1]))
clustered = centroids[centers_idx]

figure(1)
subplot(211)
imshow(flipud(img))
subplot(212)
imshow(flipud(clustered))
show()

运行时在第12行centroids,_ = kmeans(pixel,6)处报错,错误信息:

File "D:\Python30\lib\site-packages\scipy\cluster\vq.py", line 454, in kmeans
book, dist = _kmeans(obs, guess, thresh=thresh)
File "D:\Python30\lib\site-packages\scipy\cluster\vq.py", line 309, in _kmeans
code_book.shape[0])
File "_vq.pyx", line 340, in scipy.cluster._vq.update_cluster_means
TypeError: type other than float or double not supported

我知道可以把6改为6.0,但不清楚如何处理传入kmeans的Numpy数组,请问需要如何更新代码才能让示例正常运行?


解决方案

需要做三处关键修改,适配新版Scipy的要求:

  • 将像素数组转换为浮点型(float/double),因为新版kmeans要求输入数据为浮点类型,而imread读取的图像默认是uint8(8位无符号整数),不符合要求。
  • 将聚类数量参数改为浮点型(如6.0),避免参数类型冲突。
  • 量化结果转回uint8类型,确保图像能被imshow正确显示。

修正后的完整代码:

from pylab import imread, imshow, figure, show, subplot
from numpy import reshape, uint8, flipud
from scipy.cluster.vq import kmeans, vq

img = imread('clearsky.jpg')

# 重塑像素矩阵并转换为float类型
pixel = reshape(img, (img.shape[0] * img.shape[1], 3)).astype(float)

# 执行聚类:传入浮点型像素数组与浮点型聚类数量
centroids, _ = kmeans(pixel, 6.0)
# 量化
qnt, _ = vq(pixel, centroids)

# 重塑量化结果并转回uint8类型(图像显示要求)
centers_idx = reshape(qnt, (img.shape[0], img.shape[1]))
clustered = centroids[centers_idx].astype(uint8)

figure(1)
subplot(211)
imshow(flipud(img))
subplot(212)
imshow(flipud(clustered))
show()

修改说明

  1. 像素类型转换:.astype(float)将uint8的像素数组转为浮点型,满足kmeans的输入类型限制。
  2. 聚类数量参数:6.0替代6,解决Scipy参数类型校验问题。
  3. 结果类型还原:量化后的数组转回uint8,因为图像显示接口只支持0-255的整数像素值。

内容的提问来源于stack exchange,提问作者Ghoul Fool

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 10:03:12