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
Walter Roberson
2018년 1월 28일
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()
Daniel Khoo
2018년 1월 28일
Daniel Khoo
2018년 1월 28일
Daniel Khoo
2018년 1월 28일
답변 (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.
Muhammad Zeeshan Ahmed Khan
2021년 3월 12일
0 개 추천
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
카테고리
도움말 센터 및 File Exchange에서 Lighting, Transparency, and Shading에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!