MATLAB Answers

How to Remove Black From Background of Cropped Image

70 views (last 30 days)
Brian Peoples
Brian Peoples on 9 Jul 2020
Answered: Image Analyst on 10 Jul 2020
Hello--
This is not important to the analysis of the picture I am doing, but more for a visual aspect. I was wondering if you had an idea on how I could remove the black background from this already cropped image. My image is as follows:
Here's the already cropped image (1st part of subplot):
My code is as follows (thank you image analyst for all the help thus far):
% Demo to mask of hair switch.
% By Image Analyst.
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.
%file = 'C:\Users\bpeoples\Downloads\MATLAB GLOSS MEASUREMENTS\Sample_Image_Folder\Measurements\Blonde_Hair_Diffused\3CROP_trial 3';
file = 'C:\Users\bpeoples\Downloads\MATLAB GLOSS MEASUREMENTS\Sample_Image_Folder\Measurements\Blonde_Hair_Diffused\3CROP_trial 3';
filename = dir(fullfile(file, '*.jpg'));
total_images = numel(filename);
f = fullfile(file, filename(1).name);
rgbImage = imread(f);
[rows, columns, numberOfColorChannels] = size(rgbImage);
% Display the RGB image full size.
subplot(2, 2, 1);
imshow(rgbImage, []);
axis('on', 'image');
caption = sprintf('Original Image : "%s"', filename(1).name);
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';
% Do color segmentation to get the blue tape.
[BW,maskedRGBImage] = createMask(rgbImage);
mask = ~BW;
% Get rid of blobs smaller than 10,000 pixels.
mask = bwareaopen(mask, 10000);
% Display the binary image.
subplot(2, 2, 2);
imshow(mask, []);
axis('on', 'image');
caption = sprintf(' Mask Image');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
% Get the area and centroid.
labeledImage = bwlabel(mask);
props = regionprops(labeledImage, 'Area', 'Centroid');
allAreas = [props.Area]
xy = vertcat(props.Centroid);
% Find out which one is closest to the middle.
x = xy(:, 1);
middlex = columns/2
distanceFromMiddle = abs(x - middlex)
[minDistance, indexOfMiddle] = min(distanceFromMiddle)
% Keep the middle blob.
hairMask = ismember(labeledImage, indexOfMiddle);
hairMask = imfill(hairMask, 'holes');
%convert masked image to rgb
I4 = cat(3,hairMask,hairMask,hairMask);
I5 = uint8(I4(500:3499,1:4500,3)).*rgbImage(500:3499,1:4500,1:3);
%_________ divide into 3 equal segments
Top = uint8(I4(500:1500,2250:3750,3)).*rgbImage(500:1500,2250:3750,1:3); %might have to change horizontal scale(.,!,)
Middle = uint8(I4(1500:2500,2250:3750,3)).*rgbImage(1500:2500,2250:3750,1:3);
Bottom = uint8(I4(2500:3499,2250:3750,3)).*rgbImage(2500:3499,2250:3750,1:3);
%__________ transform the 3 segments into rectangles
% Top_Rectangle = Top(1:1001,500:1250,1:3);
% Middle_Rectangle = Middle(1:1001,480:1200,1:3);
% Bottom_Rectangle = Bottom(1:650,400:1200,1:3);
%_________
figure(3);
subplot(2,2,1);
imshow(I5, []);
axis('on', 'image');
caption = sprintf('crop');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
subplot(2,2,2);
imshow(Top, []);
axis('on', 'image');
caption = sprintf('Top');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
subplot(2,2,3);
imshow(Bottom, []);
axis('on', 'image');
caption = sprintf('Bottom');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
subplot(2,2,4);
imshow(Middle, []);
axis('on', 'image');
caption = sprintf('Middle');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
%__________
% Display the RGB image full size.
figure(1)
subplot(2, 2, 3);
imshow(hairMask, []);
axis('on', 'image');
caption = sprintf('Hair Mask');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
% Display the RGB image full size.
subplot(2, 2, 4);
imshow(I5, []);
axis('on', 'image');
caption = sprintf('RGB Hair Mask');
title(caption, 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
%=====================================================================================================
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 06-Jul-2020
%------------------------------------------------------
% Convert RGB image to chosen color space
I = rgb2hsv(RGB);
% Define thresholds for channel 1 based on histogram settings
channel1Min = 0.580; %orig .410
channel1Max = 0.670; %orig. .670
% Define thresholds for channel 2 based on histogram settings
channel2Min = 0.000;
channel2Max = 1.000;
% Define thresholds for channel 3 based on histogram settings
channel3Min = 0.000;
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

Answers (1)

Image Analyst
Image Analyst on 10 Jul 2020
When you get your top, middle, and bottom images, you can crop each by finding the non-black mask.
% Find where at least one pixel in Red, Green, or Blue Channel is not zero.
nonBlackMask = Top(:, :, 1) ~= 0 | Top(:, :, 2) ~= 0 | Top(:, :, 3) ~= 0;
nonBlackMask = bwareafilt(nonBlackMask, 1); % Take largest region only.
% Measure the Bounding Box.
props = regionprops(nonBlackMask, 'BoundingBox');
% Now crop
Top = imcrop(Top, props.BoundingBox);
Do the same for Middle and Bottom.

Community Treasure Hunt

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

Start Hunting!