How to extract objects from a colored image and save them as separate images for future use?

I have an image that contains numerous rice seeds laid on a coloured background and I want to separate the seed pixels from the image such that the i have the image of each rice seed saved as a separate picture. The reason i want to do that is that i want to extract features from each rice seed picture later to train a neural network to be able to identify to which variety the seed belongs to. The picture is attached, it isn't ideal but it is what i have to get started on developing an algo.

 Risposta accettata

Alright, here's the code. Accept the answer if it does what you need:
% Demo by Image Analyst, December, 2020.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clearvars;
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 16;
fprintf('Beginning to run %s.m ...\n', mfilename);
%-----------------------------------------------------------------------------------------------------------------------------------
% Read in image.
folder = [];
baseFileName = 'rice green background.jpg';
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% The file doesn't exist -- didn't find it there in that folder.
% Check the entire search path (other folders) for the file by stripping off the folder.
fullFileNameOnSearchPath = baseFileName; % No path this time.
if ~exist(fullFileNameOnSearchPath, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
rgbImage = imread(fullFileName);
[rows, columns, numberOfColorChannels] = size(rgbImage)
% Display the test image full size.
subplot(1, 2, 1);
imshow(rgbImage, []);
axis('on', 'image');
caption = sprintf('Original Image : "%s"', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Set up figure properties:
% Enlarge figure to full screen.
hFig1 = gcf;
hFig1.Units = 'Normalized';
hFig1.WindowState = 'maximized';
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
hFig1.Name = 'Demo by Image Analyst';
% Mask to find the rice.
[riceMask, maskedRGBImage] = createMask(rgbImage);
% Get rid of blobs less than 500 in size.
riceMask = bwareaopen(riceMask, 500);
% Display the test image full size.
subplot(1, 2, 2);
imshow(riceMask, []);
axis('on', 'image');
caption = sprintf('Mask Image : "%s"', baseFileName);
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
props = regionprops(riceMask, 'BoundingBox', 'Area')
allAreas = sort([props.Area])
numRows = ceil(sqrt(length(props)));
hFig = figure;
hFig.WindowState = 'maximized'
for k = 1 : length(props)
thisBox = props(k).BoundingBox;
croppedImage = imcrop(rgbImage, thisBox);
subplot(numRows, numRows, k);
imshow(croppedImage);
caption = sprintf('Blob #%d area = %d', k, props(k).Area);
title(caption, 'FontSize', 8);
drawnow;
end
fprintf('Done running %s.m ...\n', mfilename);
function [BW,maskedRGBImage] = createMask(RGB)
%createMask Threshold RGB image using auto-generated code from colorThresholder app.
% [BW,MASKEDRGBIMAGE] = createMask(RGB) thresholds image RGB using
% auto-generated code from the colorThresholder app. The colorspace and
% range for each channel of the colorspace were set within the app. The
% segmentation mask is returned in BW, and a composite of the mask and
% original RGB images is returned in maskedRGBImage.
% Auto-generated by colorThresholder app on 22-Dec-2020
%------------------------------------------------------
% Convert RGB image to chosen color space
I = rgb2hsv(RGB);
% Define thresholds for channel 1 based on histogram settings
channel1Min = 0.852;
channel1Max = 0.220;
% Define thresholds for channel 2 based on histogram settings
channel2Min = 0.431;
channel2Max = 1.000;
% Define thresholds for channel 3 based on histogram settings
channel3Min = 0.533;
channel3Max = 1.000;
% Create mask based on chosen histogram thresholds
sliderBW = ( (I(:,:,1) >= channel1Min) | (I(:,:,1) <= channel1Max) ) & ...
(I(:,:,2) >= channel2Min ) & (I(:,:,2) <= channel2Max) & ...
(I(:,:,3) >= channel3Min ) & (I(:,:,3) <= channel3Max);
BW = sliderBW;
% Initialize output masked image based on input image.
maskedRGBImage = RGB;
% Set background pixels where BW is false to zero.
maskedRGBImage(repmat(~BW,[1 1 3])) = 0;
end

Più risposte (1)

Very easy. Just use the Color threshold on the apps tab of the tool ribbon to make a mask for the rice color. Then call regionprops() to get the bounding boxes. Then in a loop, call imcrop() to crop out each grain to it's own box. Let me know if you can't figure it out. Here's a start
[mask, maskedImage] = createMask(rgbImage); % From Color Thresholder
props = regionprops(mask, 'BoundingBox')
numRows = ceil(sqrt(length(props)));
hFig = figure;
hFig.WindowState = 'maximized'
for k = 1 : length(props)
thisBox = props(k).BoundingBox;
croppedImage = imcrop(rgbImage, thisBox);
subplot(numRows, numRows, k);
imshow(croppedImage);
end

Categorie

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by