Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

预览窗口不支持透明图片 #3

Closed
sxjeru opened this issue Nov 2, 2021 · 4 comments
Closed

预览窗口不支持透明图片 #3

sxjeru opened this issue Nov 2, 2021 · 4 comments

Comments

@sxjeru
Copy link
Owner

sxjeru commented Nov 2, 2021

简而言之,OpenCV直接用imshowimwrite 生成jpg的方式,都无法正确显示 PNG 中的透明部分。

在此感谢 @TansuoTro ,这位大佬提供了一个函数用于解决此问题。

下列内容改编自他的回复。

@sxjeru
Copy link
Owner Author

sxjeru commented Nov 2, 2021

原因:
jpg 不存在 alpha 通道,导致原 alpha 通道随机填充到原来RGB值缺省的地方,因此透明部分的RGB变了。
(另外,imshow 不支持透明是公认的——)

@sxjeru
Copy link
Owner Author

sxjeru commented Nov 2, 2021

解决方案:
使 PNG 的 alpha 通道变成 RGB,然后将 RGB 缺省的地方填充为 bg 的 RGB 值。
(bg 为白色背景,生成见下方代码)

@sxjeru
Copy link
Owner Author

sxjeru commented Nov 2, 2021

读取一张图片,并生成一个白色背景。(Mat type 须使用CV_8UC3

Mat imageMain = imread(imageName, IMREAD_UNCHANGED);
Mat bg(imageMain.rows, imageMain.cols, CV_8UC3, Scalar(255, 255, 255));
imageOverlay(imageMain, bg, 0, 0);

以下函数由 @TansuoTro 提供,感谢。

void imageOverlay(const Mat &pic, Mat &bg, int x, int y)
{
    int channelNum = 3;
    int alpha = 0; 
 
    for (int i = 0; i < pic.rows; i++)
    {
        for(int j = 0; j < pic.cols * 3; j += 3)
        {
            alpha = pic.ptr<uchar>(i)[j / 3*4 + 3];
 
            if(alpha != 0)
            {
                for (int k = 0; k < 3; k++)
                {
                    if( (i+y < bg.rows) && (i+y>=0) &&
                        ((j+x*3) / 3*3 + k < bg.cols*3) && ((j+x*3) / 3*3 + k >= 0) &&
                        (i/channelNum*4 + k < bg.cols*4) && (j/channelNum*4 + k >=0) )
                    {
                        bg.ptr<uchar>(i+y)[(j+x*channelNum) / channelNum*channelNum + k] = 
                        pic.ptr<uchar>(i)[(j) / channelNum*4 + k];
                    }
                }
            }
        }
    }
}

@sxjeru sxjeru closed this as completed Nov 2, 2021
@sxjeru
Copy link
Owner Author

sxjeru commented Nov 2, 2021

最后是聊天记录全截图,只能说百科群(82170277)人才辈出——

image

image

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant