如何对某个目录下的多张图片做K-means聚类并保存到另一个目录下? (在本地)

How to do K-means clustering for multiple images in certain directory and save it to another directory? (on local)

import numpy as np
import cv2

img = cv2.imread('home.jpg')
Z = img.reshape((-1,3))

# convert to np.float32
Z = np.float32(Z)

# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 8
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)

# Now convert back into uint8, and make original image
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((img.shape))

cv2.imshow('res2',res2)
cv2.waitKey(0)
cv2.destroyAllWindows()

以上代码很简单,是基本的 K-Means 聚类代码,适用于 "single" 图像。但是,我需要目录中多个图像的代码。

因此,我创建了代码,但它无法正常工作并出现错误:'PngImageFile' 对象没有属性 'reshape'(已解决问题)

但在那之后我遇到了错误问题:'numpy.ndarray' 对象没有属性 'save'。我认为这是因为我更改了代码

img = Image.open(fullpath)
#to
img = np.array(Image.open(fullpath))

下面是我正在处理的代码。

path = "Desktop/Gray/fmtial_gb/good_crop/"
sub_path = "Desktop/Gray/fmtial_gb/good_crop_result/"
dirs = os.listdir(path)
def kmean():
    from os import listdir,makedirs
    from os.path import isfile,join
    import matplotlib.pylab as plt
    import matplotlib.image as mpimg
    import cv2
    import numpy as np
    from PIL import Image
    import os.path, sys
    for item in dirs:
        fullpath = os.path.join(path,item)
        pathos = os.path.join(sub_path,item)
        if os.path.isfile(fullpath):
            #img = Image.open(fullpath)
            img = np.array(Image.open(fullpath))
            f, e = os.path.splitext(pathos)
            #img = cv2.imread('Desktop/Gray/fmtial_gb/good_crop/RD091090(80)Cropped.bmp')
            Z = img.reshape((-1,3))

            # convert to np.float32
            Z = np.float32(Z)

            # define criteria, number of clusters(K) and apply kmeans()
            criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
            K = 2
            ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)

            # Now convert back into uint8, and make original image
            center = np.uint8(center)
            res = center[label.flatten()]
            res2 = res.reshape((img.shape))

            #cv2.imshow('res2',res2)
            #cv2.waitKey(0)
            #cv2.destroyAllWindows()

            Image.fromarray(res2).save(f + 'kmeans.png', "png", quality=100)     
kmean()   

我认为这是因为您正在尝试重塑 PIL 图像对象而不是 numpy 数组。

尝试将 img = Image.open(fullpath) 更改为 img = np.array(Image.open(fullpath)),应该可以。