Code to remove black background from a PNG
15 ビュー (過去 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.
4 件のコメント
回答 (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
参考
カテゴリ
Help Center および 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!