作用:就是在灰度图中将灰度值小于阈值的像素保留,否则置为0.
实现代码:
function[]=Graylevelthresholding()
clear, clc, close all
% Load test image
img = imread('peter.png');
% Threshold
level = 105;
bwImg = img < level;
holeImg = img .* uint8(bwImg);
% Show images
subplot(1, 3, 1), imshow(img); title('Original Image');
subplot(1, 3, 2), imshow(bwImg); title('Thresholded Image');
subplot(1, 3, 3), imshow(holeImg); title('Binary Map \times Original');
% Save images
imwrite(bwImg, 'Graylevel_Thresholding_thresholded.png');
imwrite(holeImg, 'Graylevel_Thresholding_blend.png');
在ppt中,提了一个问题就是如何将图二的黑洞填上?
感觉是下面介绍的方法三
顾名思义该方法利用目标区域与背景区域之间的方差最大的思想,达到分割图像的目的。也就是说,选取最佳阈值T时,目标与背景之间的方差值最大,小于阈值T的区域为D1,大于阈值的区域为D2,如此一来即可将需要的区域区分开来。
σ within 2 ( T ) = N F g m d ( T ) N σ F g n d 2 ( T ) + N B g m d ( T ) N σ B g r n d 2 ( T ) \sigma_{\text {within}}^{2}(T)=\frac{N_{F g m d}(T)}{N} \sigma_{F g n d}^{2}(T)+\frac{N_{B g m d}(T)}{N} \sigma_{B g r n d}^{2}(T) σwithin2(T)=NNFgmd(T)σFgnd2(T)+NNBgmd(T)σBgrnd2(T)
于是,Ostu算法就是找到一个阈值T,使得 σ betwan 2 ( T ) = N Fgad ( T ) ⋅ N B g n d ( T ) N 2 ( μ F g n d ( T ) − μ B g n d ( T ) ) 2 \sigma_{\text {betwan}}^{2}(T)=\frac{N_{\text {Fgad}}(T) \cdot N_{B g n d}(T)}{N^{2}}\left(\mu_{F g n d}(T)-\mu_{B g n d}(T)\right)^{2} σbetwan2(T)=N2NFgad(T)⋅NBgnd(T)(μFgnd(T)−μBgnd(T))2最大
幸运的是,Matlab提供了这个函数的!
课堂代码如下:
% Load test image
% img = imread('peter.png');
% img = imread('brain.jpg');
% img = rgb2gray(imread('news.png'));
function []=Global_Thresholding()
img = rgb2gray(imread('front.png'));
% img = imread('paper.png');
% Perform Otsu thresholding
level = graythresh(img); % chooses Otsu threshold
otsuThresh = round(level * 255);
bwImg = im2bw(img, level);
% Show images
subplot(1, 3, 1), imshow(img); title('Original Image');
subplot(1, 3, 2), imshow(bwImg); title('Globally Thresholded Image');
subplot(1, 3, 3), imshow((1-bwImg) .* im2double(img)); title('Overlay');
axes('Parent', figure, 'FontSize', 18);
[counts,x] = imhist(img);
bar(x, counts); hold on;
h = plot(otsuThresh*ones(1,100), linspace(0,max(counts)), 'r-');
% title('Graylevel Histogram');
axis([0 255 0 max(counts)]);
set(gca, 'FontSize', 18);
set(gcf, 'Color', 'white');
% Save images
imwrite(bwImg, 'Global_Thresholding_bw.png');
saveas(gcf, 'Global_Thresholding_hist.png')
其中,需要解释一下im2bw
是将像素大于阈值的全部置为255,小于的全部置为0
实验效果:
Non-uniform areas: apply Otsu’s method (based on local histogram)
Uniform areas: classify the entire area as foreground or background based on mean value