Code to remove black background from a PNG

I have a image of a uneven profile (non-rectangular) of a fibre (under microscopy) as a PNG file.
However, when i import it to matlab and view it via imshow, there is a black background behind the PNG image. I am trying to convert the image to binary/ black and white to analyse the ratio of 0 and 1 pixels, and the black background affects the values of 0.
May I ask for a type of code that is able to remove the background and resize the image, in conjuction with this code below:
sample = imread('cutt.png');
level = graythresh(sample);
BlackWhite = im2bw(sample,0.3);
imshow(BlackWhite);
figure, imhist(BlackWhite);
Thank you in advance.

4 Comments

Can you attach a sample? To confirm, the black is not present in the original source but it is seen in the png?
I have a suspicion that there might be an alpha map stored with the png. Try looking at the third output of imread()
Hi Walter,
Thanks for your quick response. Attached is the sequence of how I edited the image to isolate the fibre itself to the point where it's displayed on matlab.
I am using paint 3D, magic select the region I want and saved on a transparent canvas, before exporting it as a 2D Png file.
And to confirm, the black is not present at all in the png, but when appears when imshow is used- might be to make the image rectangular since the profile of the fibre is not a rectangular.

Sign in to comment.

Answers (2)

transparent canvas is handled in PNG files by using an alpha channel. You can read that alpha channel from PNG files by giving a third output argument:
[sample, map, sample_alpha] = imread('cutt.png');
and then you can display it:
imshow(sample, 'alphadata', sample_alpha);
The data in sample will (probably) be 0 at the places the alpha is 0 (transparent), but passing alphadata parameter to imshow() or image() will inform the graphics system of which pixels to plot.
You can determine which pixels to pay attention to by examine the sample_alpha matrix: anything 0 is to be ignored, anything non-zero has data. You will probably only see 0.0 and 1.0 values in your situation.
When you image() or imagesc() or imshow(), pass an option 'AlphaData' that is an array with the desired transparency, with 1 meaning to show the image completely and 0 meaning not showing the image at all (that is, show the background completely there.)
If the PNG had alpha information stored with it that you read with imread() then you should be able to use that transparency information directly.
[YourImage, ~, ImageAlpha] = imread('YourFile.png');
image(YourImage, 'AlphaData', ImageAlpha)

Asked:

on 28 Jan 2018

Edited:

on 12 Mar 2021

Community Treasure Hunt

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

Start Hunting!