编写kmeans图像分割代码
时间: 2023-09-24 21:14:00 浏览: 97
利用kmeans进行图像分割
好的,以下是一个基于Python的K-means图像分割代码:
```python
import numpy as np
import cv2
def kmeans_image_segmentation(image, k=3):
# 转换图像数据类型,从[0, 255]变为[0, 1]
image = image.astype(np.float32) / 255.
# 改变图像形状以方便聚类
pixels = image.reshape((-1, 3))
# 设置K-means参数
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 50, 0.1)
flags = cv2.KMEANS_RANDOM_CENTERS
# 运行K-means算法
_, labels, centers = cv2.kmeans(pixels, k, None, criteria, 10, flags)
# 重新构造图像
segmented_image = centers[labels.flatten()]
segmented_image = segmented_image.reshape(image.shape)
# 返回分割后的图像
return segmented_image
# 示例
image = cv2.imread('input_image.jpg')
segmented_image = kmeans_image_segmentation(image)
cv2.imshow('Input Image', image)
cv2.imshow('Segmented Image', segmented_image)
cv2.waitKey(0)
```
希望这个代码能够帮助到你!
阅读全文