Python 压缩后.jpg和.jpeg的大小增加
我正在尝试使用K-means算法压缩图像,但是一些.jpg图像的大小在压缩后增加了。如何为.jpg和.jpeg图像执行此操作。在应用压缩之前,我已将jpg和jpeg图像保存为png格式Python 压缩后.jpg和.jpeg的大小增加,python,k-means,image-compression,Python,K Means,Image Compression,我正在尝试使用K-means算法压缩图像,但是一些.jpg图像的大小在压缩后增加了。如何为.jpg和.jpeg图像执行此操作。在应用压缩之前,我已将jpg和jpeg图像保存为png格式 for f in os.listdir('.'): if f.endswith('.png'): image = io.imread(f,0) rows = image.shape[0] cols = image.shape[1] pixe
for f in os.listdir('.'):
if f.endswith('.png'):
image = io.imread(f,0)
rows = image.shape[0]
cols = image.shape[1]
pixels = image.reshape(image.shape[0] * image.shape[1], image.shape[2])
kmeans = MiniBatchKMeans(n_clusters=128, n_init=10, max_iter=200)
kmeans.fit(pixels)
clusters = np.asarray(kmeans.cluster_centers_, dtype=np.uint8)
labels = np.asarray(kmeans.labels_, dtype=np.uint8)
labels = labels.reshape(rows, cols)
colored = clusters[labels]
# np.save('codebook'+f+'.npy', clusters)
io.imsave('compressed_' + f, colored)
img1 = mpimg.imread(f,0)
img2 = mpimg.imread('compressed_' + f,0)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 10))
ax1.imshow(img1)
ax1.set_title('Original image')
ax2.imshow(img2)
ax2.set_title('Compressed image')
plt.show()
fig, ax = plt.subplots(2, 1)
img = cv2.imread(f, 0)
ax[0].hist(img.ravel(), 256, [0, 256]);
ax[0].set_title("Original image")
img1 = cv2.imread('compressed_' + f,0)
ax[1].hist(img1.ravel(), 256, [0, 256]);
ax[1].set_title("Compressed image")
plt.show()
print('size of original image: ', int(os.stat(f).st_size / 1024), 'kB')
print('size of compressed image:', int(os.stat('compressed_' + f).st_size / 1024), 'kB')
如果我正确理解了您的方法,您可以使用K-means聚类来减少图像中的颜色数量,方法是找到颜色相似的像素区域(簇)并将它们分组在一起 虽然从理论上讲,这可以减少图像的文件大小,但将其再次保存为jpeg会在缩小的图像上应用完全不同的图像压缩算法,这无法充分利用具有锐利边缘的相同颜色的大区域。这必然会使图像“模糊”,在某些情况下,甚至会导致文件大小增加
尝试以不同的格式(例如,作为png文件)存储缩小后的图像,这样可以利用较大、颜色均匀的区域。在应用压缩算法之前,我已将jpeg文件转换为png,但仍然,这些图片的尺寸更大。如果无法访问您的样本图片,我认为无法说明任何更详细或更具体的内容。也许你可以让你的程序打印出更多关于它实际功能的信息。它发现了多少个集群,它们有多大,它们做了什么?@SamratShrestha-这与压缩前图像的文件类型无关,而是与存储压缩图像时使用的文件类型有关。如果您使用最精细的压缩算法并将结果存储为bmp文件,那么您将丢弃通过压缩算法获得的所有结果。当保存为jpeg时,同样的情况也会发生(在小得多的范围内)。如果您在某个地方发布了示例图像,您会忘记告诉我们在哪里。在评论中重复问题的文本似乎是多余的。对不起,我添加了它。