Reputation: 4732
Is there any way of removing a white background and turning it into black in MATLAB?
Say i have this image:
I get the following output when i apply the code suggested in the answer: Which isn't perfect
Upvotes: 2
Views: 3213
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
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):
Upvotes: 6
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).
imfreehand
and then create a mask by calling createMask
from the API.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
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