vini
vini

Reputation: 4732

Giving an image a black background?

Is there any way of removing a white background and turning it into black in MATLAB?

Say i have this image:

enter image description here

I get the following output when i apply the code suggested in the answer: Which isn't perfect

enter image description here

Upvotes: 2

Views: 3213

Answers (4)

Youri Leenman
Youri Leenman

Reputation: 248

You should draw the image to a black background.

//Your bitmap
Bitmap originalImage = new Bitmap(100, 100);

//Black background
Bitmap bitmap = new Bitmap(100, 100);
Graphics g = Graphics.FromImage(bitmap);

//Draw the background
g.FillRectangle(Brushes.Black, 0, 0, 100, 100);

//Draw the original bitmap over the black one
g.DrawImage(originalImage, 0, 0);

Upvotes: 0

Alceu Costa
Alceu Costa

Reputation: 9889

The problem, as Andrey noticed, is that not all background pixels are "255 white". This probably is happening due to JPEG compression algorithm and also because there's a shadow of the fruit in the image.

To solve this problem, first get a binary mask of the fruit region by blurring the image (this is necessary to overcome the JPEG artifacts) and then threshold the image with a very high value, but a little lower than 255. Here's the solution in Matlab:

I = imread('https://i.sstatic.net/5p4jV.jpg'); % Load your image.
H = fspecial('gaussian'); % Create the filter kernel.
I = imfilter(I,H); % Blur the image.

Mask = im2bw(Ig, 0.9); % Now we are generating the binary mask.
I([Mask, Mask, Mask]) = 0; % Now we have the image.

Here's the output (you can also try different threshold values in im2bw):

enter image description here

Upvotes: 6

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

You fail due to the anti-aliasing effect that blurs the edges your image. These pixels that were not removed are not 255! They are a bit lower. Basically you have 2 options:

(I wrote them from the perspective of using Matlab).

  1. Select the relevant part by using imfreehand and then create a mask by calling createMask from the API.
  2. Finding the correct threshold level, which isn't 255. (Much harder - if possible)

Here is a Matlab code for the first:

function SO1
    im = imread('c:\x.jpg');
    figure();
    imshow(im);
    f = imfreehand();
    mask = f.createMask();
    mask = repmat(mask,[1 1 3]);
    im(~mask) = 0;
    figure;imshow(im);
end

Upvotes: 2

Mercury
Mercury

Reputation: 1965

yes. if your image is save as a variable called img:

thr = 255;
mask = sum(img,3)==thr*3;
for i=1:3
    c = img(:,:,i);
    c(mask)=0;
    img(:,:,i)=c;
end

|-)

Upvotes: -1

Related Questions