使用Numpy进行图像量化
我想看看这个关于图像量化的示例代码,链接在这里。不过,这段代码有点老旧,Python和NumPy自那以后也发生了变化。
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)
错误信息显示在文件 "D:\Python30\lib\site-packages\scipy\cluster\vq.py" 的第454行,出错的地方是调用了kmeans函数,里面有个地方叫做 _kmeans,具体在第309行。
错误提示是:TypeError: 不支持浮点数以外的类型。
我可以把6改成6.0,但对于传给kmeans的NParray,我有点困惑,不知道该怎么处理。
我需要做些什么来更新代码,让这个示例能够正常运行呢?
1 个回答
1
我觉得你只需要把图片的像素转换成浮点数。在把像素传给kmeans之前,先把它们转换成浮点数类型,这样才能确保它们能正常使用:
import matplotlib.pyplot as plt
import numpy as np
from scipy.cluster.vq import kmeans, vq
# Reading the image
img = plt.imread('clearsky.jpg')
# Convert image pixels to float
pixel = np.reshape(img, (img.shape[0]*img.shape[1], 3)).astype(float)
# Performing the clustering
centroids, _ = kmeans(pixel, 6.0) # six colors will be found
# Quantization
qnt, _ = vq(pixel, centroids)
# Reshaping the result of the quantization
centers_idx = np.reshape(qnt, (img.shape[0], img.shape[1]))
clustered = centroids[centers_idx.astype(int)]
# Displaying the original and quantized images
plt.figure(figsize=(10, 5))
plt.subplot(121)
plt.imshow(img)
plt.title('Original Image')
plt.subplot(122)
plt.imshow(clustered.astype(np.uint8))
plt.title('Quantized Image')
plt.show()