MATLAB Answers


Cant change the background using image segmentaton

Asked by Firecky Dwika on 5 Aug 2019
Latest activity Commented on by Image Analyst
on 16 Aug 2019
Hello, im a beginner at MATLAB. I tried to change the background of the image to white and turns out the image become weird.
Here is the code i used:
L= imbinarize(J);
L= imcomplement(L);
L= imfill(L,'holes');
L= bwareaopen(L,100);
str= strel('disk',5);
L= imerode(L,str);
figure, imshow(L);
Img2= imread('background.jpg');
R = I(:,:,1);
G = I(:,:,2);
B = I(:,:,3);
R2 = Img2(:,:,1);
G2 = Img2(:,:,2);
B2 = Img2(:,:,3);
R2(L) = R(L);
G2(L) = G(L);
B2(L) = B(L);
RGB = cat(3,R2,G2,B2);
figure, imshow(RGB);
Can anyone help me, please?


Show 1 older comment
you have any source i can read into? i really have no clue how to do it properly, please...
and i want to change the background of original image to white by combining the original image with the background....
Please answer the followings (specifically)-
  • What you have (please attach data/image)?
  • What you want?
these are the images i used.
2.jpg background.jpg
i want to combine the original image with the second image, so i have a leaf with white background. but this is what i get:
Can you tell me what should i do?

Sign in to comment.

2 Answers

Answer by Image Analyst
on 8 Aug 2019

Why do you think that code will identify background, whatever that is, in an image of a bunch of leaves? What is the background? All the other leaves except the central one? Anything not the brown spots? Whatever, your algorithm is not good. I suggest you just start by hand tracing whatever you think is background by adapting my attached masking demo.


Sign in to comment.

Answer by Neuropragmatist on 8 Aug 2019

This image looks like a real nightmare for edge detection etc and I don't know if you are really every going to get something satisfactory.
Do you need a robust automated method or is this just a once off?
If you need to do this a lot in future (for example if you want to collect images of samples for a scientific study) I would suggest photographing the leaf on a solid colour background - like a sheet of paper. That will allow you to do what you want much more easily, quickly and in a reliably automated way.
If this is a once off I would suggest (and this is going to sound like a joke but it isn't) using the 'remove background' feature in PowerPoint, or manually cutting the leaf out using software like MS paint (free), Inkscape (free) or Photoshop (not free).
Sorry can't be more help,


sorry for late reply, i did like what you suggest but the outcome doesnt change...
Explain how manually tracing or painting over the background to remove it, like you definitely said you tried, could NOT work? That doesn't make sense to us.

Sign in to comment.