⭐ 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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值