print(row)
plt.imshow(img)
plt.show()
#### 大津算法
import numpy as np
import cv2
from matplotlib import pyplot as plt
#读取图片
img = cv2.imread(‘segmentation3.png’)
灰度化
gray_img = 0.2126img[:,:,2] + 0.7152img[:,:,1] + 0.0722*img[:,:,0]
gray_img = gray_img.astype(np.uint8)
#初始化方差
kesai = 0
for gray in range(0,256):
v0 = gray_img[np.where(gray_img < gray)]
v1 = gray_img[np.where(gray_img >= gray)]
if len(v0) != 0:
u0 = np.mean(v0)
w0 = len(v0)/(gray_img.shape[0]gray_img.shape[1])
else:
u0 = 0
w0 = 0
if len(v1) != 0:
u1 = np.mean(v1)
w1 = len(v1)/(gray_img.shape[0]gray_img.shape[1])
else:
u1 = 0
w1 = 0
kesai_new = w0w1(u0-u1)**2
if kesai_new > kesai:
kesai = kesai_new
threshold = gray
print('kesai = ',kesai)
print('threshold = ',threshold)
#二值化,但用更新后的阈值threshold
gray_img[gray_img>=threshold] = 255
gray_img[gray_img<threshold] = 0
img[:,:,0] = gray_img
img[:,:,1] = gray_img
img[:,:,2] = gray_img
plt.imshow(img)
plt.show()
###
### 分水岭算法
## 基于聚类的分割
由两个大步骤组成:图像特征提取和k聚类算法。k聚类算法的实现很简单,首先初始化簇心,计算每个点到簇心的距离,以距簇心越近,就属于该簇心,然后更新每个点的簇心值,进行下一步计算直到不能更新为止。图像特征提取,由于是单张图片,所以直接用像素值即可,将其转化为列数据。
import numpy as np
import cv2
def kMeans(data, iter, k):
data = data.reshape(-1, 3)
data = np.column_stack((data, np.ones(img.shape[0]*img.shape[1])))
# 1.随机产生初始簇心
cluster_center = data[np.random.choice(img.shape[0]*img.shape[1], k),:]
# 2.分类
distance = [[] for j in range(k)]
for i in range(iter):
#print(“迭代次数:”, i)
# 2.1距离计算
for j in range(k):
distance[j] = np.sqrt(np.sum((data - cluster_center[j])**2, axis=1))#每一行单独左右计算
# 2.2归类
data[:, 3] = np.argmin(distance, axis=0) #每一列单独上下计算
# 3.计算新簇心
for j in range(k):
cluster_center[j] = np.mean(data[data[:, 3] == j], axis=0)
return data[:, 3]
img = cv2.imread(‘image.png’)
image_show = kMeans(img, 100, 2)
image_show = image_show.reshape(img.shape[0], img.shape[1])
cv2.imshow(‘image_s