Code to remove black background from a PNG
조회 수: 14 (최근 30일)
이전 댓글 표시
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!