OpenCV For Unity 入门教程(二): 实现简单的图片合成

using System.Collections;
using System.Collections.Generic;
using OpenCVForUnity;
using UnityEngine;
using UnityEngine.UI;

public class ImageSynthesis : MonoBehaviour {

    void Start()
    {
        GetComponent<RawImage>().texture = MatMerg();
    }
    Texture2D MatMerg()
    {
        // 将图片转换成 mat 数据
        Mat bgmat = Imgcodecs.imread(Application.streamingAssetsPath + "/bg.png", Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);
        Mat qj = Imgcodecs.imread(Application.streamingAssetsPath + "/qj.png", Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);
        // 进行图像彩色空间转换
        Imgproc.cvtColor(bgmat, bgmat, Imgproc.COLOR_BGR2RGB);
        Imgproc.cvtColor(qj, qj, Imgproc.COLOR_BGRA2RGBA);

        Mat bgmat_roi = new Mat(bgmat, new OpenCVForUnity.Rect(797, 269, qj.cols(), qj.rows()));
        cvAdd4cMat_q(bgmat_roi, qj, 1.0);
        Texture2D texture = new Texture2D(bgmat.cols(), bgmat.rows(), TextureFormat.RGBA32, false);
        Utils.matToTexture2D(bgmat, texture);
        return texture;
    }
    private bool cvAdd4cMat_q(Mat dst, Mat scr, double scale)
    {
        if (dst.channels() != 3 || scr.channels() != 4)
        {
            return true;
        }
        if (scale < 0.01)
            return false;
        List<Mat> scr_channels = new List<Mat>();
        List<Mat> dstt_channels = new List<Mat>();
        Core.split(scr, scr_channels);
        Core.split(dst, dstt_channels);
        //            CV_Assert(scr_channels.size() == 4 && dstt_channels.size() == 3);

        if (scale < 1)
        {
            scr_channels[3] *= scale;
            scale = 1;
        }
        for (int i = 0; i < 3; i++)
        {
            dstt_channels[i] = dstt_channels[i].mul(new Mat(scr_channels[3].size(), CvType.CV_8UC1, new Scalar(255.0 / scale)) - scr_channels[3], scale / 255.0);

            dstt_channels[i] += scr_channels[i].mul(scr_channels[3], scale / 255.0);
        }
        Core.merge(dstt_channels, dst);
        return true;
    }

}

猜你喜欢

转载自blog.csdn.net/qq_39097425/article/details/83016205
今日推荐