传统图像分割方法(基于阈值分割)
阈值法:基本思想是基于图像的灰度特征来计算一个或多个灰度阈值,并将图像中每个像素的灰度值与阈值相比较,最后将像素根据比较结果分到合适的类别中。因此,该类方法最为关键的一步就是按照某个准则函数来求解最佳灰度阈值。
一个简单实现:
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 | |
![]()
|
![]()
|
|
|
![]()
|
![]()
|
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)