Color based image segmentation

When actually processing an image, it is often necessary to segment the image and then extract the ROI. This study note records how to use Matlab to achieve color-based image segmentation.

1. RGB to YCBCR color space conversion.

2. Binarize the image with the threshold of each channel.

3. Morphological treatment: corrosion, expansion, hole filling.

4. Connected area extraction.

The main Matla graphics processing functions involved are as follows: rgb2ycbcr (color space conversion), roicolor (ROI binarization), imerode (erosion), imdilate (expansion), imfill (hole filling), regionprops (region properties). The specific implementation of these functions still refer to Gonzalez's "Digital Image Processing", and matlab help documents, and paper references.

Not much to say, look at the code specifically, there are comments for each step.

% clear the variable, read the image
clear;close all
RGB = imread('images/girl.jpg');

figure('name','process'),
subplot(2,2,1),imshow(RGB),title('原始RGB'),

%convert frame from RGB to YCBCR colorspace (convert to YCBCR space)
YCBCR = rgb2ycbcr(RGB);
whos,
subplot(2,2,2),imshow(YCBCR),title('YCBCR'),
%filter YCBCR image between values and store filtered image to threshold
%matrix (binarize each channel with its threshold)
Y_MIN = 0; Y_MAX = 256;
Cb_MIN = 100;   Cb_MAX = 127;
Cr_MIN = 138;   Cr_MAX = 170;
threshold=roicolor(YCBCR(:,:,1),Y_MIN,Y_MAX)&roicolor(YCBCR(:,:,2),Cb_MIN,Cb_MAX)&roicolor(YCBCR(:,:,3),Cr_MIN,Cr_MAX);
subplot(2,2,3),imshow(threshold),title('YCBCR binarization'),

%perform morphological operations on thresholded image to eliminate noise
%and emphasize the filtered object(s) (for morphological processing: erosion, dilation, hole filling)
erodeElement = strel ('square', 3);
dilateElement=strel('square', 8) ;
threshold = imerode (threshold, erodeElement);
threshold = imerode (threshold, erodeElement);
threshold=imdilate(threshold, dilateElement);
threshold=imdilate(threshold, dilateElement);
threshold=imfill(threshold,'holes');
subplot(2,2,4),imshow(threshold),title('morphological processing'),

% Get the 'basic' property of the area, 'Area', 'Centroid', and 'BoundingBox'
figure('name','processing result'),
stats = regionprops(threshold, 'basic');
[C,area_index]=max([stats.Area]);
% Locate face area
face_locate=[stats(area_index).Centroid(1),stats(area_index).Centroid(2)];
imshow(RGB);title('after'),hold on
text(face_locate(1),face_locate(2)-40,  'face','color','red');
plot(face_locate(1),face_locate(2), 'b*');
rectangle('Position',[stats(area_index).BoundingBox],'LineWidth',2,'LineStyle','--','EdgeColor','r'),
hold off

 

The effect after running is as follows:

Matlab image processing study notes (2): color-based image segmentation

Matlab image processing study notes (2): color-based image segmentation



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325802866&siteId=291194637