How to write a Image with Alpha channel ?using imwrite matlab command?

13 views (last 30 days)
How to write a Image with Alpha channel ?using imwrite matlab command?
Example:
RGB=imread('football.jpg');
Alpha=?
imwrite(X,Y,X,X,)

Answers (1)

Voss
Voss on 8 Jul 2022
Edited: Voss on 8 Jul 2022
% original image
RGB=imread('football.jpg');
imshow(RGB)
Use .png format with Alpha parameter in imwrite
% Attempt to make the blue background green, using transparency/opacity
% parameter 'Alpha' and the 'Background' parameter, which is the color
% that shows "under" the places where the image is transparent.
% alpha is a matrix of uint8, based on a logical condition
alpha = uint8(255*(RGB(:,:,1) >= 100 | RGB(:,:,3) <= 50));
% the first pixel is fully transparent (no opacity)
alpha(1,1)
ans = uint8 0
% write the png file, with alpha and background
imwrite(RGB,'football.png','Alpha',alpha,'Background',[0 0.6 0])
% check the outcome
imshow(imread('football.png'))
% attempt to make the football transparent by
% using the opposite condition
alpha = uint8(255*(RGB(:,:,1) < 100 & RGB(:,:,3) > 50));
% the first pixel has no transparency (fully opaque)
alpha(1,1)
ans = uint8 255
% write the png file, with alpha and background
imwrite(RGB,'football.png','Alpha',alpha,'Background',[0 0.6 0])
% check the outcome
imshow(imread('football.png'))
  3 Comments
DGM
DGM on 9 Jul 2022
Edited: DGM on 9 Jul 2022
To pre-empt any confusion about what gets preserved, specifying both output arguments like this:
% get the RGB and alpha of the new image
[new_RGB,~,new_alpha] = imread('football.png');
will give you the original RGB content (of both the ball and blanket) and the new alpha as Voss demonstrates in the second example.
However, let's say you just want to discard the new alpha and get the original RGB content. Doing this:
% get the RGB and alpha of the new image
new_RGB = imread('football.png');
will not give you the expected RGB content anymore. As the first examples demonstrate, if no alpha is requested when reading an image which has alpha content, the image will interally be composited with a solid color field defined by the "BackgroundColor" field specified in the PNG file, or by the "BackgroundColor" option specified when calling imwrite() (default is black).
The lesson here is that if you want the actual content of the RGB channels, you need to request alpha if there's a possibility that the image may have alpha content -- even if you don't need it.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!