How to Remove Black Background from Photo (Only Keep Region of Interest)

17 views (last 30 days)
Brian Peoples
Brian Peoples on 26 Jun 2020
Answered: Image Analyst on 10 Oct 2021
Here is my image:
My code so far only gets me my desired region but I wish to take out all the black parts so that I can do proper image analysis on the desired region without the rest interfering. Here is my image after I get my desired region:
My code is as follows:
I0 = imread('DSC_0043.jpg');
I1 = I0(:,:,3); % select 3d channel
I2 = im2bw(I1,graythresh(I1)-0.1); % binarization
imshow(I2)
h = msgbox('select region of interest');
uiwait(h)
p = ginput(1); % pick point
I3 = bwselect(~I2,p(1),p(2)); % select region of interest
I4 = cat(3,I3,I3,I3);
I5 = uint8(I4).*I0; % crop rgb image
%imshow(I5)
%I5(I5 ==0) = [];
%resize
imshow(I5);
Please any help would be amazing and greatly appreciated.

Answers (2)

Kartik Deshmukh
Kartik Deshmukh on 10 Oct 2021
Hi Brian Peoples,
How did you manage to fix the issue? I have the same problem for my image and I cannot seem to get rid of the black background so cannot analyse my image.
I'd appreciate your help!
  1 Comment
Image Analyst
Image Analyst on 10 Oct 2021
Kartik: Create your own question, and attach your image and say what is background and what is foreground. Also try the Color thresholder on the APps tab and show us the result. And tell us that "analyse" means to you. Also define "get rid of". You can crop the image, but it's probably not necessary - depends on what you want to do. You can analyze the foreground without "getting rid of" the background.

Sign in to comment.


Image Analyst
Image Analyst on 10 Oct 2021
Try this, where I used a color segmentation function generated by the Color Threshold app on the Apps tab of the tool ribbon:
% Demo 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. This is a horrible image. NEVER use JPG format for image analysis. Use PNG, TIFF, or BMP instead.
folder = [];
baseFileName = 'hair switch.jpeg';
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 image.
subplot(2, 2, 1);
imshow(rgbImage, []);
axis('on', 'image');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
caption = sprintf('Original RGB Image : "%s"\n%d rows by %d columns', baseFileName, rows, columns);
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 the image
[mask,maskedRgbImage] = createMask(rgbImage);
% Take the largest blob.
mask = bwareafilt(mask, 1);
% Fill any possible holes.
mask = imfill(mask, 'holes');
% Re-mask the image with the new mask.
% Mask the image using bsxfun() function to multiply the mask by each channel individually. Works for gray scale as well as RGB Color images.
maskedRgbImage = bsxfun(@times, rgbImage, cast(mask, 'like', rgbImage));
% Display the mask image.
subplot(2, 2, 2);
imshow(mask, []);
axis('on', 'image');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
title('Mask Image', 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
% Get the bounding box.
props = regionprops(mask, 'BoundingBox');
% Crop the image
croppedImage = imcrop(maskedRgbImage, props.BoundingBox);
% Display the mask image.
subplot(2, 2, 3:4);
imshow(croppedImage, []);
axis('on', 'image');
hp = impixelinfo(); % Set up status line to see values when you mouse over the image.
title('Cropped Image', 'FontSize', fontSize, 'Interpreter', 'None');
drawnow;
msgbox('Done!');
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 10-Oct-2021
%------------------------------------------------------
% Convert RGB image to chosen color space
I = rgb2hsv(RGB);
% Define thresholds for channel 1 based on histogram settings
channel1Min = 0.661;
channel1Max = 0.375;
% 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.103;
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

Community Treasure Hunt

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

Start Hunting!