import cv2 import numpy as np from skleam.cluster import kMeans #读取图像并转换为灰度图 image=cv2.imread("1280.jpg") gray_image=cv2.cvtColor(image,cv2.COLOR_BGR2.GRAY) #将灰度图像数据转换为一维数组 pixels=gray_image.resape(-1,1) k=5 kmeans=KMeans(n clusters=k) kmeans.fit(pixels) centers=kmeans.cluster_centers_ labels=kmeans.cluster_centers_ centers=centers.astype(int) segmented_image=np.zeros_(gray_image) for i in range(gray_image.shape[0]); for j in range(gray_image.shape[1]); segmented_image[,j]=centers[labels[i*gray_image.shape[1]=j]]