Code to remove black background from a PNG
9 次查看(过去 30 天)
显示 更早的评论
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/169560/image.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.
回答(2 个)
Walter Roberson
2018-1-28
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.
0 个评论
Muhammad Zeeshan Ahmed Khan
2021-3-12
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)
1 个评论
Walter Roberson
2021-3-12
编辑:Walter Roberson
2021-3-12
Copied without attribution from my answer to https://www.mathworks.com/matlabcentral/answers/365228-can-a-png-image-be-displayed-without-displaying-the-black-fill-in-the-guide#answer_289605
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!