1. 需要引入 OpenCVForUnity 命名空间,结构图如下:
2.代码如下:
using OpenCVForUnity;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RemoveImage : MonoBehaviour {
public int alpha = 150;
void Start()
{
//把图片读进三通道的容器
var src = Imgcodecs.imread(Application.streamingAssetsPath + "/open.jpg", 1);
//把尺寸设置为大小
Imgproc.resize(src, src, new Size(500, 500));
//建立一个四通道的容器
var dst = new Mat(src.cols(), src.rows(), CvType.CV_8UC4);
//转换色彩空间
Imgproc.cvtColor(src, dst, Imgproc.COLOR_BGR2RGBA);
// 遍历一下这个 dst 容器, 里面是处理图像的逻辑 会输出一个处理过的 dst 返回出来
for (int i = 0; i < dst.cols(); i++)
{
for (int j = 0; j < dst.rows(); j++)
{
//这个150是阈值,你可以自己定义来试试效果
if (dst.get(j, i)[0] > alpha)
{
dst.put(j, i, 255, 255, 255, 0);
}
}
}
// 定义一个 Texture2D 对象
var tex = new Texture2D(dst.cols(), dst.rows(), TextureFormat.RGBA32, false);
// 将 dst 转换成这个 Texture2D 对象
Utils.matToTexture2D(dst, tex);
// 将处理后的图片现实在 RawImage 组件上
var raw = this.GetComponentInChildren<RawImage>();
raw.texture = tex;
raw.SetNativeSize();
}
}
3.效果如下:
4.参考链接如下: https://www.jianshu.com/p/3f1876c62b11