MATLAB: Using the alpha-channel to change the background of an image

Опубликовано: 27 Октябрь 2024
на канале: buckmasterinstitute
1,661
13

Created and recorded by Yiming Cai. October 2021

Music by Armin Heller, see https://lmms.io/lsp/?action=show&file...,   / twilight-area   and https://creativecommons.org/licenses/...


Picture background replacement has a very wide range of applications in real life. In many action movies, actors are shot in green scenes, and then the required background is synthesised when editing. In fact, change the background of a picture is very simple, the main idea is to identify the background through the alpha channel. This video will teach you how to change the picture background in Matlab by using alpha channel.

Before introducing how to change the background of a picture, I would like to talk about the alpha channel first. Alpha channel is a channel that represents the transparency of a picture. Different from other channels in image storage, the alpha channel only has one bit, and only contains 0 and 1. If all bits in the alpha channel are 0, then the picture is transparent. Notice that not all picture files have an alpha channel, for example, jpg files don't have an alpha channel.

In this tutorial, we are going to use a png file with transparent background. The first thing we want to do is get the alpha channel from the picture.

[image, ~, alpha] = imread(‘filename.png’)
image = im2double(image)
alpha = im2double(alpha)

And let’s see how the alpha channel looks like

imshow(alpha)

Now you can see, in the alpha channel, place with transparent background is all black.

Let's import our background image

background = imread(’background.png’)
background = im2double(background)
imshow(background)

And it will be better if our background and the original picture has the same size. If it's not, let change the size.

background = imsize(background, image.size1, image.size2)

After change the size, let’s see how our background looks like

imshow(background)

And let’s combine original image and background together.

newimage = repmat (alpha, [1, 1, 3]).*image + (1-repmat(alpha, [1, 1, 3]).*background

Because the alpha channel is a 2d array, while our actual png files are 3d array in Matlab, it’s essential to repeat our alpha channel three time so multiply of images can work. That’s why we are using repmat here. Now let’s see what we get.

imshow(newimage)

So in this video, we talked about what alpha channel is and how to change image background by using alpha channel. It's a very important skill if you are interested in graphic processing, and also widely used in real life. Hope this video is helpful.