[英]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均值聚类代码,适用于“单个”图像。 但是,我需要一个用于目录中多个图像的代码。
因此,我创建了代码,但无法正常工作:“ 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))
,它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.