Alpha blending in different size two images

☆樱花仙子☆ 提交于 2019-12-22 18:41:14

问题


Alpha blending in same size two images is explained here. How do we implement this for two different size images. Ex: 600x400 pixels PNG for foreground and a 700x380 pixels JPG for background. In the mentioned link, Both the images are same size.


回答1:


First of, resizing is a bad idea. Unless both images are resized together (which won't solve the problem), resizing will change the final result in undesired ways (e.g. the foreground object will appear larger than intended).

Alpha blending is usually used to add foreground elements to a background image. Therefore, I would fix the size of the background image, and consider it also the output image size. In applications, one might need to have the foreground exit the background image, but that is a specific application which requires more input (how to extend the background borders?).

Since the background image has a fixed size, we need a way to handle the alpha blending of a smaller image. Consider the simplified case, where the smaller (foreground) image is aligned with the larger (background) image at the point (0,0). Then, you can iterate over the background image, check if it overlaps the foreground image, and if it does, blend them.

Solving the general cases introduces another problem: positioning. You need to know where to place the foreground element. This requires some additional input.

Given a smaller image and a position where you want to place it, you can alpha blend against a larger image using an algorithm as follows:

let posx and posy be the placement position of the foreground image
let foreground.sizex and foreground.sizey the size of the foreground image
for each row of the background image
    for each column of the background image
        // check if the position overlaps the foreground image
        if column - posx >= 0 and column - posx < foreground.sizex
            if row - posy >= 0 and row - posy < foreground.sizey
                 alpha blend the background and the foreground
        else
            output background value

Note that the subtraction of the placement position of the foreground image is basically a translation.

To show this idea visually, to get the output

, you can think of it as if the images were the same size and check for overlap. If they overlap, blend. If they don't, keep the background. This would result in something like this (added a black border to show the smaller size of the foreground image):

If you don't want the foreground image to be placed in the upper left corner, simply translate it. posx and posy represent the translation applied to the foreground image, i.e. the coordinates of the red dot:



来源:https://stackoverflow.com/questions/55953418/alpha-blending-in-different-size-two-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!