使用OpenCVForUnity分割图片

最近的一个需求,引申出对图片裁切、拼接、矫正相关的系列需求,不知不觉已经使用了4-5种方法。如unity的GetPixels32(),SetPixels32()有512*512的尺寸限制问题,如C#中的system.drawing有跨平台的问题等。最终感觉使用opencv是综合效果最好的一种选择。今次实例如图,把原图按中心十字裁切成4张新图,显示在4个新的Image上。


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

public class CropTexture2D : MonoBehaviour
{
    public Mat mat;
    public Texture2D source;
    public Texture2D[] result = new Texture2D[4];
    public RawImage[] output = new RawImage[4];

    void Start()
    {
        int width = source.width;
        int height = source.height;
        //Debug.Log(width + "*" + height); // 256*256, 打印查看一下图片尺寸

        //rows 是行数,对应height
        //cols 是列数,对应width
        mat = new Mat(height, width, CvType.CV_8UC3); // Mat对象尺寸要和Texture2d一样
        Utils.texture2DToMat(source, mat);

        for (int i = 0; i < 2; i++)
        {
            for (int t = 0; t < 2; t++)
            {
                int id = i * 2 + t;
                Debug.Log("[顺序]" + (id)); //0->1->2->3

                // 按output数组中的顺序,裁切并赋予新图片
                OpenCVForUnity.Rect rectCrop = new OpenCVForUnity.Rect(width / 2 * t, height / 2 * i, width / 2, height / 2); // 调试小心,超出取值范围,unity会奔溃
                Mat croppedImage = new Mat(mat, rectCrop);

                result[id] = new Texture2D(croppedImage.width(), croppedImage.height()); // Texture2d尺寸也要和Mat一样
                Utils.matToTexture2D(croppedImage, result[id]);
                output[id].texture = result[id];
            }
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值