resize and save transparent PNG file in matlab

조회 수: 51 (최근 30일)
Mohsen Farjami
Mohsen Farjami 2018년 10월 11일
댓글: Walter Roberson 2021년 4월 8일
I have an transparent png file(colored image not black and white).I want to resize this png file and save that with transparent background.but i cant save that with transparent background.file saved with dark background.
[im,map]=imread('image.png');
im=ind2rgb(im,map);
im2=imresize(im,[200,200]);
imwrite(im2,'image2.png');
in above code image2.png saved with black background and not transparent
  댓글 수: 2
Mohsen Farjami
Mohsen Farjami 2018년 10월 11일
편집: Mohsen Farjami 2018년 10월 11일
thanks for reply but when i resize and save png file the file give dark background. this image is my png file

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2018년 10월 11일
편집: Guillaume 2018년 10월 11일
For a start you never retrieve the transparency information so it's no wonder it's not preserved.
PNG images have two ways to specify transparency. For grayscale and true colour images, the transparency can be specified as an additional alpha channel the same size as the image. You get that in matlab from the 3rd output of imread (not the 2nd). Indexed images in PNG cannot have an alpha channel
For all types of images (so grayscale, true colour and indexed), PNG also allows you to specify a specific colour as transparent. To get that transparent colour in matlab you have to use at the SimpleTransparencyData field of imfinfo.
Assuming your image is actually true colour and that your code is a mistake, then:
[im, ~, alpha] = imread('image.png'); %transparency not valid for index images, so no point in getting map
im2 = imresize(im, [200, 200]);
alpha2 = imresize(alpha, [200 200]);
imwrite(im2, 'image2.png');
If the transparency is actually the second type ( imfinfo will have 'simple' for the Transparency field, then:
fileinfo = imfinfo('image.png');
assert(strcmp(fileinfo.Transparency, 'simple'), 'This file does not have simple transparency')
im = imread('image.png'); %if image is actually indexed, you also need to retrieve the colour map
im2 = imresize(im, [200 200]);
imwrite(im2, 'image2.png', 'Transparency', fileinfo.SimpleTransparencyData);
However, in that second case, note that because of the default interpolation, some transparent pixel may get assigned a colour that is no longer transparent. Using the non-default 'nearest' interpolation option in imresize would solve that problem.
  댓글 수: 6
Ronan da Silva
Ronan da Silva 2021년 4월 7일
In the sample code above, you do not pass the resized alpha2 to imwrite .
I don't assume MATLAB assigns it automatically?
Ronan
Walter Roberson
Walter Roberson 2021년 4월 8일
imwrite(im2, 'image2.png', 'Alpha', alpha2);
^^^^^^^

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Images에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by