MATLAB: How to change the black color into transparency in png format

image processingtransparency

colorImage = imread('13100.png');
grayImage = rgb2gray(colorImage);
mserRegions = detectMSERFeatures(grayImage);
mserRegionsPixels = vertcat(cell2mat(mserRegions.PixelList));
mserMask = false(size(grayImage));
ind = sub2ind(size(mserMask), mserRegionsPixels(:,2), mserRegionsPixels(:,1));
mserMask(ind) = true;
f=figure();imshow(mserMask,'Border','tight');
maskedimage = immultiply(colorImage, repmat(mserMask, [1, 1, size(colorImage, 3)]));
imshow(maskedimage,'Border','tight');
TransparencyMaskedImage = maskedimage;
TransparencyMaskedImage(repmat(~mserMask, 1, 1, 3)) = ??;
imshow(TransparencyMaskedImage,'Border','tight');

Best Answer

To just write it transparent with imwrite, you do not need any of the three lines
TransparencyMaskedImage = maskedimage;
TransparencyMaskedImage(repmat(~mserMask, 1, 1, 3)) = ??;
imshow(TransparencyMaskedImage,'Border','tight');
instead,
imwrite(maskedimage, 'YourFileName.png', 'Transparency', [0 0 0]);
If you want to display the image with transparency, then
mask = double( any(maskedimage, 3) );
image(maskedimage, 'AlphaData', mask ) %notice this is not imshow