python 灰度图k-means聚类
时间: 2023-08-30 13:11:16 浏览: 97
以下是使用Python进行灰度图像的K-means聚类的示例代码:
首先,导入所需的库:
```python
import numpy as np
import cv2
from sklearn.cluster import KMeans
```
然后,加载图像并将其转换为灰度图像:
```python
img = cv2.imread('image.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
接下来,将图像转换为一维数组以进行聚类:
```python
rows, cols = gray.shape
data = gray.reshape(rows * cols, 1)
```
然后,使用K-means算法进行聚类:
```python
kmeans = KMeans(n_clusters=3)
kmeans.fit(data)
```
最后,将每个像素分配到其所属的簇,并将其重新构造为图像:
```python
labels = kmeans.predict(data)
res = labels.reshape(rows, cols)
cv2.imshow('K-means Clustering', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
完整代码如下:
```python
import numpy as np
import cv2
from sklearn.cluster import KMeans
img = cv2.imread('image.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
rows, cols = gray.shape
data = gray.reshape(rows * cols, 1)
kmeans = KMeans(n_clusters=3)
kmeans.fit(data)
labels = kmeans.predict(data)
res = labels.reshape(rows, cols)
cv2.imshow('K-means Clustering', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
注意:这里使用的是K-means算法,聚类的数量(即n_clusters)可以根据需要进行更改。
阅读全文