草庐IT

基于阈值的7种图像分割方法以及Python实现

风华明远 2023-08-26 原文

阈值图像分割的7种方法

1. 什么是阈值分割

阈值分割是根据图像的灰度特征按照设定的阈值将图像分割成不同的子区域。简单的理解就是先将图像进行灰度处理,然后根据灰度值和设定的灰度范围将图像灰度分类。比如0-128的是一类,129-255是一类。
根据不同的分类方法,阈值分割有以下7种方法:

  1. 固定阈值分割
  2. 直方图双峰法
  3. 迭代阈值图像分割
  4. 自适应阈值图像分割
  5. 大津法 OTSU
  6. 均值法
  7. 最佳阈值

2. 固定阈值分割

固定阈值分割是最简单的阈值分割方法,其方法就是将灰度值大于某一阈值的像素点置为255,而小于等于该阈值的点设置为0。这是最简单的图像分割方法,适用范围很窄。对于比较简单的图像有较好的效果。对应的CV2函数为cv2.threshold(src, thresh, maxval,cv2.THRESH_BINARY)。用numpy实现此功能非常简单,只需要1行代码:

    return np.where(((img>thresh) & (img<maxval)),255,0)

np.where的第一个参数是条件,可以设置多条件。第二个是条件成立时,numpy数组的取值,而第三个参数是不成立的取值。
完成的比较代码如下:

# coding:utf8
import cv2
import numpy as np
import matplotlib.pyplot as plt


def fix_threshold(img, thresh, maxval=255):
    return np.where(((img > thresh) & (img < maxval)), 255, 0)


img = cv2.imread('xk.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

ret, th = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
fix = fix_threshold(img_gray, 127, 255)

plt.subplot(131), plt.imshow(img_gray, cmap='gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(132), plt.imshow(th, cmap='gray')
plt.title('CV2 Image1'), plt.xticks([]), plt.yticks([])
plt.subplot(133), plt.imshow(fix, cmap='gray')
plt.title('Fix Image2'), plt.xticks([]), plt.yticks([])
plt.show()

3.灰度直方图双峰法

灰度直方图通常双峰属性(bimodal,一个前景峰值,另一个为背景峰值)。两个峰值之间的最小值可以认为是最优二值化的分界点。
算法如下:
(1)查找直方图最大值firstPeak
(2)通过下面的公式结算第二峰:
s e c o n d P e a k = max ⁡ x [ ( x − f r i s t P e a k ) 2 ∗ h i s t ( x ) ] secondPeak = \max\limits_{x}[(x-fristPeak)^2*hist(x)] secondPeak=xmax[(xfristPeak)2hist(x)]
(3)双峰之间的灰度最小值为分界点(需要考虑最大峰值的灰度数值可能小于第二大峰值的灰度值)
此方法得到的阈值与CV2中threshold函数得到的阈值并不是完全一致的。本方法较为简单,对于处理简单的图像比较有效,但是对于复杂的图片,比如遥感图片效果就很差。后面的文章会增加解读遥感图片的部分。

# coding:utf8
import cv2
import numpy as np
from matplotlib import pyplot as plt

def GrayHist(img):
    grayHist = np.zeros(256,dtype=np.uint64)
    for v in range(256):
        grayHist[v] = np.sum(img==v)
    return grayHist

def threshTwoPeaks(image):

    # 计算灰度直方图
    hist = GrayHist(image)
    # 寻找灰度直方图的最大峰值对应的灰度值
    maxLoc = np.where(hist == np.max(hist)) #maxLoc 中存放的位置
    firstPeak = maxLoc[0][0]
    # 寻找灰度直方图的第二个峰值对应的灰度值
    elementList = np.arange(256,dtype = np.uint64)
    measureDists = np.power(elementList - firstPeak,2) * hist

    maxLoc2 = np.where(measureDists == np.max(measureDists))
    secondPeak = maxLoc2[0][0]

    # 找到两个峰值之间的最小值对应的灰度值,作为阈值
    thresh = 0
    if secondPeak > firstPeak:
        firstPeak,secondPeak=secondPeak,firstPeak
    temp = hist[secondPeak:firstPeak]
    minloc = np.where(temp == np.min(temp))
    thresh = secondPeak + minloc[0][0] + 1
    # 找到阈值之后进行阈值处理,得到二值图
    threshImage_out = image.copy()
    # 大于阈值的都设置为255
    threshImage_out[threshImage_out > thresh] = 255
    # 小于阈值的都设置为0
    threshImage_out[threshImage_out <= thresh] = 0
    return thresh, threshImage_out

if __name__ == "__main__":

    img = cv2.imread('dt.jpg')
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)


    th, img_new = threshTwoPeaks(img_gray)
    th1,img_new_1 = cv2.threshold(img_gray, 0, 255,  cv2.THRESH_BINARY + cv2.THRESH_TRIANGLE)
    print(th,th1)
    plt.subplot(131), plt.imshow(img_gray, cmap='gray')
    plt.title('Original Image'), plt.xticks([]), plt.yticks([])
    plt.subplot(132), plt.imshow(img_new, cmap='gray')
    plt.title('Image'), plt.xticks([]), plt.yticks([])
    plt.subplot(133), plt.imshow(img_new_1, cmap='gray')
    plt.title('CV2 Image1'), plt.xticks([]), plt.yticks([])
    plt.show()


有关基于阈值的7种图像分割方法以及Python实现的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  6. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  7. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  8. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  9. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  10. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

随机推荐