Matlab image segmentation

Part 1. Implications of Image Segmentation

       Image segmentation is to divide the image into several disjoint regions according to the gray scale, color, geometric shape, spatial texture and other characteristics of the image; in fact, it is to extract the target in the picture and separate it from the background;

Part II. Types of Image Segmentation in Matlab

   1. Edge detection method (use the difference between the junction between the target and the background to extract the edge)

   2. Threshold segmentation method (set a threshold, the place below the threshold is 0 black, and the place above the threshold is 1 white)

   3. Region segmentation method ()

Part 3. Edge detection method

Main detection methods: differential operators (Roberts operator, Sobel operator, Prewit operator), LOG operator, Canny operator; 

1. Detection of line segments in the image:

Like filtering, there must be templates. There are four basic templates in total:

[-1 -1 -1; 2 2 2; -1 -1 -1] level detection

[-1 -1 2; -1 2 -1; 2 -1 -1] +45 degree detection

[-1 2 -1; -1 2 -1; -1 2 -1] vertical detection

[2 -1 -1; -1 2 -1; -1 -1 2] -45 degree detection

Then the template and image are combined and filtered, using the imfilter function

2. Differential operator

<1>Roberts operator:

clc
clear all
I = imread('dream.jpg');
I=rgb2gray(I);
[J, thresh] = edge(I, 'Roberts', 30/255); %进行边缘检测 ,Roberts算子, 分割阈值为30/255
figure;
subplot(121),imshow(I);
subplot(122),imshow(J);

The 30/255 inside is the segmentation threshold, the actual threshold is thresh*256, where thresh is the normalized value;

<2>Sobel operator: the usage is the same as that of Roberts operator, just change the parameter in edge to Sobel

<3>Prewit operator: The usage is the same as that of the Roberts operator, just change the parameter in edge to Prewit

3. LOG operator:

In the application of the edge function, both log and canny correspond to the sigma parameter, which is the standard deviation of the corresponding filter; Canny corresponds to the Gaussian filter (the default is sqrt(2)), and LOG corresponds to the Gaussian Laplacian filter tor (default is 2)

4. Canny operator:

Its special feature is that his threshold includes two, a low threshold and a high threshold; ignore the edge part below the low threshold, and keep the part above the high threshold;

Part IV. Threshold segmentation method

1. You can use the histogram to set the threshold. We first read the grayscale image, and then use the imhist function to display the histogram;

%图像分割(全局阈值,借助直方图)
clc
clear all
I=rgb2gray(imread('dream.jpg'));
figure (1)
imhist(I);
R=I>125;%大于125的地方为白(1),小于为黑(0)
figure(2);
imshow(R);

 It can be seen that we can find a threshold from the histogram and judge according to this threshold;

2. Otsu threshold segmentation, you can use the function graythresh to automatically obtain the threshold, and then segment according to this threshold;

%Otsu阈值分割
clc
clear all
I=rgb2gray(imread('dream.jpg'));
M=graythresh(I);%自动获取阈值
J=im2bw(I,M);%根据M的大小来进行分割
figure;
imshow(J);

 3. Iterative threshold segmentation, the principle is very simple. First, read the grayscale image, set a precision value (here S is set), and set an initial value variable S1 equal to the sum of the maximum and minimum values ​​of the grayscale image. One-half, then set two variables r1 and r2, r1 is the sum of all elements greater than the initial value variable S1, r2 is the sum of all elements less than or equal to S1; set the variable S2 equal to (average of r1 + average of r2 number)/2; after entering the while loop, make S1 equal to S2 after conversion, and then repeat the previous steps until the accuracy is less than the set accuracy S1; at this time, the obtained S2 is the threshold value, and then display the binary image through im2bw ;

%迭代式阈值分隔法
clc
clear all
I=rgb2gray(imread('dream.jpg'));
I=im2double(I);
S=0.1;
S1=(max(I(:))+min(I(:)))/2;
r1=find(I>S1);
r2=find(I<=S1);
S2=(mean(I(r1))+mean(I(r2)))/2;
while abs(S2-S1)>S
   S1=S2;
   r1=find(I>S1);
   r2=find(I<=S1);
   S2=(mean(I(r1))+mean(I(r2)))/2;
end
J=im2bw(I,S2);
figure;
imshow(J);

Part V. Region Segmentation Method

1. Region growing method:
region growing is to continuously compare a seed (that is, a point) with the surrounding points and then fuse the region with a large stroke. The fusion condition is that the similarity with the surrounding points is less than a certain accuracy; Then continue to expand the fusion outward until all similar points are fused and stop. Here we use the gray value to measure;

Region growth is generally divided into the following steps:

1. Determine the seed point

2. Determine whether to use the 8-neighborhood or the 4-neighborhood as the fusion object

3. The ratio of the difference between the gray value and the threshold value (other judgment conditions can also be added, set according to the actual situation)

4. Until growth stops, i.e. the point at which growth is no longer satisfied

Example:

clc
clear all
I=rgb2gray(imread('dream.jpg'));
if isinteger(I)%判断是否为整数数组,若不为整数数组I的值过大,这样设置的精度就得改变,不能太小,否则无法得到想要的图片
    I=im2double(I);
end
figure 
imshow(I)
[M,N]=size(I);
[y,x]=getpts; %单击取点后,按enter结束
x1=round(x);%获得整数x
y1=round(y);%获得整数y
seed=I(x1,y1); %获取中心像素灰度值

grow1=zeros(M,N);%要绘制二值图,就可以先设置为0数组
grow1(x1,y1)=1;%种子点设为1,满足条件的点在后续判断中也会设为一

growcount=1; %待处理点个数
threshold=0.15;%与isinteger相互结合起来理解,如果没有isinteger,该值应该变得很大

while growcount>0
    growcount=0;
     for i=1:M %让种子去融合图片中满足的所有点
        for j=1:N
            if grow1(i,j)==1 %点在"栈"内,即一开始先检测到种子点,然后根据判断条件去判断种子点邻域的点是否满足条件,若满足为1,然后进行下一轮循环进行判断,直到循环时没有点可以满足添加进行融合了
                if (i-1)>1&(i+1)<M&(j-1)>1&(j+1)<N %确保可以将8邻域完全放置
                    for u=-1:1 %8邻域生长
                        for v=-1:1
                            if (grow1(i+u,j+v)==0&abs(I(i+u,j+v)-seed)<=threshold)%只有在点为0的时候才进行,否则gowtcount会计算错误
                                grow1(i+u,j+v)=1;%种子合并其他点,只要满足条件的点都会和种子点一样置1
                                growcount=growcount+1;  %记录此次新生长的点个数
                            end
                        end
                    end
                end
            end
        end
    end
end

subplot(1,2,1),imshow(I);
title("original image")
subplot(1,2,2),imshow(grow1);
title("growed image")

You can refer to the region growing algorithm based on matlab to realize_minisal's blog-CSDN blog_matlab region growing code, the content is commented in it, as long as you understand the steps of region growing, the code will naturally understand;

2. Watershed segmentation method:

The watershed transformation method generally includes the following steps:

1. Read the grayscale image

2. Set the foreground mark (clean up the image by rebuilding on and rebuilding off), erosion + rebuilding on

3. Expansion + reconstruction closure

4. Morphological reconstruction + image inversion

5. Find the local maximum value + combine the grayscale image with the local maximum value

6. Eliminate the surrounding messy points for the local maximum (close operation first, then corrode)

7. Combining the modified local maximum with the grayscale image

8. Calculate the background mark, and use the cleaned image (that is, the reconstructed open and reconstructed closed image) for binarization

9. But ideally we don't want the background markers to be too close to the edges of the objects we want to segment, so we can do this by computing the bwwatershed transform of the distance transform and then looking for the resulting watershed ridge

10. Use the imimposemin function to modify the gradient magnitude image so that the regional minima are displayed on the pixels of the foreground and background markers;

11. Perform watershed segmentation on the modified gradient magnitude image (segment the boundary of the object)

12. Finally, for visual display, the original grayscale image, foreground marker, background marker, and segmented object can be combined into one picture, and the foreground and background markers are scaled to different integer values ​​in order to assign them different labels.

Example:

clc
clear all
I=rgb2gray(imread('apple.jpg'));
tidu=imgradient(I);
% figure;
% imshow(tidu,[]);
se=strel('disk',20);
fs=imerode(I,se);
fscj=imreconstruct(fs,I);
pz=imdilate(fscj,se);
pzcj=imcomplement(imreconstruct(imcomplement(pz),imcomplement(fscj)));
figure;
imshow(pzcj);
dgm=imregionalmax(pzcj);
figure;
imshow(dgm);
I2=labeloverlay(I,dgm);
figure;
imshow(I2);
se2 = strel(ones(5,5));
fgm2 = imclose(dgm,se2);
fgm3 = imerode(dgm,se2);
figure;
imshow(fgm3);
fgm4=bwareaopen(fgm3,15);
%I3=labeloverlay(I,fgm4);
I(fgm4)=255;
figure
imshow(I);
bw1=imbinarize(pzcj);
D = bwdist(bw1);
DL = watershed(D);
bgm = DL == 0;
figure;
imshow(bgm);
gmag2 = imimposemin(tidu, bgm|fgm4);
L=watershed(gmag2);
labels = imdilate(L==0,ones(3,3)) + 2*bgm + 3*fgm4;
I4 = labeloverlay(I,labels);
figure;
imshow(I4);

Guess you like

Origin blog.csdn.net/new_EAGLE/article/details/125821401