传统图像分割方法(基于阈值分割)
阈值法:基本思想是基于图像的灰度特征来计算一个或多个灰度阈值,并将图像中每个像素的灰度值与阈值相比较,最后将像素根据比较结果分到合适的类别中。因此,该类方法最为关键的一步就是按照某个准则函数来求解最佳灰度阈值。
一个简单实现:
import cv2 import numpy as np import matplotlib.pyplot as plt import collections as col path = r"laohu.jpg" path1 = r"laohu1.jpg" image = cv2.imread(path) temp = np.zeros((image.shape[0], image.shape[1], 1))
# gray=0.3 * r + 0.59*g + 0.11 * b temp[:,:, 0] = image[:,:, 0] * 0.11 + image[:,:, 1] * 0.59 + image[:,:, 2] * 0.3 # 绘制双峰图 y = list() for i in range(image.shape[0]): for j in range(image.shape[1]): y.append(int(temp[i, j, 0])) yy = col.Counter(y) yyy = list() xxx = list() for i in sorted(yy): xxx.append(i) yyy.append(yy[i]) print(yyy) x = [i for i in range(256)] plt.bar(xxx, yyy, width=2, fc="gray") plt.show() plt.savefig("bar.jpg") # 找到最低点,设置阈值 temp = np.where(temp > 115, temp, 0) cv2.imwrite(path1, temp)
结果:
before | after | |
![]()
|
![]()
|
|
|
![]()
|
![]()
|