⭐ Unity里 用OpenCv 插件将png图片透明部分变成白色,让后黑白二值化处理

using UnityEngine;
using OpenCVForUnity.CoreModule;
using OpenCVForUnity.ImgprocModule;
using OpenCVForUnity.UnityUtils;

public class ImageProcessing : MonoBehaviour
{
    public UnityEngine.UI.RawImage raw;

    void Start()
    {
        // 加载图片并将其转换为RGBA格式
        string imagePath = Application.streamingAssetsPath + "/image.png";
        Texture2D inputTexture = new Texture2D(2, 2);
        byte[] imageData = System.IO.File.ReadAllBytes(imagePath);
        inputTexture.LoadImage(imageData);

        Mat rgbaMat = new Mat(inputTexture.height, inputTexture.width, CvType.CV_8UC4);
        Utils.texture2DToMat(inputTexture, rgbaMat);

        // 将透明区域变为白色
        Mat alphaMat = new Mat();
        Core.extractChannel(rgbaMat, alphaMat, 3);
        Core.bitwise_not(alphaMat, alphaMat);
        Core.bitwise_and(rgbaMat, new Scalar(255, 255, 255, 255), rgbaMat, alphaMat);

        // 转换为灰度图像
        Mat grayMat = new Mat();
        Imgproc.cvtColor(rgbaMat, grayMat, Imgproc.COLOR_RGBA2GRAY);

        // 二值化处理
        Mat binaryMat = new Mat();
        Imgproc.threshold(grayMat, binaryMat, 0, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU);

        // 显示处理后的图像
        Texture2D outputTexture = new Texture2D(binaryMat.cols(), binaryMat.rows(), TextureFormat.RGBA32, false);
        Utils.matToTexture2D(binaryMat, outputTexture);
        raw.texture = outputTexture;
    }
}

你可能感兴趣的:(unity,opencv,游戏引擎)