How do I change image background to black?

Hello! Is there a code that substitutes the image background with a black background?
I brought a picture as an example!

 Accepted Answer

DGM
DGM on 23 Mar 2022
Edited: DGM on 23 Mar 2022
For a crude binary masking:
inpict = imread('https://www.mathworks.com/matlabcentral/answers/uploaded_files/938679/image.jpeg');
hsvpict = rgb2hsv(inpict); % convert to hsv
mask = hsvpict(:,:,2) <= 0.25; % look for low-saturation regions
mask = bwareafilt(mask,1); % pick the largest object (the background)
outpict = inpict;
outpict(mask(:,:,[1 1 1])) = 0; % fill background with black
imshow(outpict)
It can be more complicated, but that's a basic approach. If you want to figure out what thresholds to use, you can try to open your image in the Color Thresholder app and explore the options.

More Answers (0)

Categories

Find more on Convert Image Type in Help Center and File Exchange

Products

Release

R2021b

Asked:

on 23 Mar 2022

Edited:

DGM
on 23 Mar 2022

Community Treasure Hunt

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

Start Hunting!