压缩所有图像后结束循环

时间:2018-11-15 15:38:07

标签: python k-means image-compression

我正在编写一个程序来压缩文件夹中存在的所有图像。在压缩所有图像之后,循环不会结束。所有压缩过程结束后如何终止。

def compress():
    algorithm = "full"
    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')

0 个答案:

没有答案