opencv处理透明图片

本文由 @lonelyrains出品,转载请注明出处。
文章链接: http://blog.csdn.net/lonelyrains/article/details/50389034

opencv处理透明图片,主要是考虑图片的叠加。

//主函数操作
...
Mat dest,srcAlpha;

// imread后一个参数为-1表示读取带有alpha通道的图片
srcAlpha = imread("C:\\Users\\Administrator\\Desktop\\1.png",-1);
dest= imread("C:\\Users\\Administrator\\Desktop\\1.png");

// 表示从dest的第(50,100)设置对srcAlpha的叠加
mapToMat(srcAlpha, dest, 50, 100);
...

void mapToMat(const cv::Mat &srcAlpha, cv::Mat &dest, int x, int y)
{
    int nc = 3;
    int alpha = 0;

    for (int j = 0; j < srcAlpha.rows; j++)
    {
        for (int i = 0; i < srcAlpha.cols*3; i += 3)
        {
            // 目的图片为三通道,所以是三通道的遍历、四通道的源图
            // i/3*4表示第i/3个像素的位置 
            // i/3*4 + 3表示本像素的alpha通道的值
            alpha = srcAlpha.ptr<uchar>(j)[i / 3*4 + 3];
            //alpha = 255-alpha;
            if(alpha != 0) //4通道图像的alpha判断
            {
                for (int k = 0; k < 3; k++)
                {
                    // if (src1.ptr<uchar>(j)[i / nc*nc + k] != 0)
                    if( (j+y < dest.rows) && (j+y>=0) &&
                        ((i+x*3) / 3*3 + k < dest.cols*3) && ((i+x*3) / 3*3 + k >= 0) &&
                        (i/nc*4 + k < srcAlpha.cols*4) && (i/nc*4 + k >=0) )
                    {
                        dest.ptr<uchar>(j+y)[(i+x*nc) / nc*nc + k] = srcAlpha.ptr<uchar>(j)[(i) / nc*4 + k];
                    }
                }
            }
        }
    }
}

处理前
这里写图片描述

处理后这里写图片描述

本代码段所在的完整工程见另一篇博客 大家一起过圣诞

GitHub 加速计划 / opencv31 / opencv
238
21
下载
OpenCV: 开源计算机视觉库
最近提交(Master分支:4 个月前 )
a9f06448 Fix setup usage example async syntax 5 小时前
b229f1ef core: add NEON support for cvFloor in fast_math.hpp #28243 - This PR adds NEON intrinsics-based implementation for the cvFloor function in fast_math.hpp for Windows-ARM64. - Both float and double overloads now use NEON intrinsics for cvFloor Function. - calchist and calchist1d function uses cvFloor function for its computations. - After adding these changes both functions showed improvement in performance. **Performance Benchmarks:** <img width="956" height="273" alt="image" src="https://github.com/user-attachments/assets/a00c98cd-d245-4d11-a9fd-361a3bd89f59" /> See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request - [x] I agree to contribute to the project under Apache 2 License. - [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV - [x] The PR is proposed to the proper branch 1 天前
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐