天天看點

unity android讀取本地圖檔,Unity之讀取本地圖檔

1.下載下傳Opencv for unity.

2.把OpenCVForUnity下的StreamingAssets拖到Assets下。

3.點選Tools->opencv for unity->set plugin import settings.

4.

using UnityEngine;

using System.Collections;

using OpenCVForUnity;

using System;

using System.Collections.Generic;

public class imageTest : MonoBehaviour {

public Texture2D img;

// Use this for initialization

void Start () {

}

// Update is called once per frame

void Update () {

if (Input.GetKeyDown(KeyCode.A)){

int height = 500;

string imgpath = "/Users/shiyuhuang/Downloads/ATOCAR/ATOCAR_UNITY_2/ATOCAR_UNITY/13.jpg";

Mat imgMat2 = Imgcodecs.imread(imgpath);

Mat imgMat = new Mat ();

int new_w, new_h=500;

double scale  = new_h/Convert.ToDouble(imgMat2.rows ());

new_w = Convert.ToInt32 (imgMat2.cols () * scale);

Imgproc.resize (imgMat2, imgMat,new Size( Convert.ToDouble(new_w), Convert.ToDouble(new_h)) );

Listchannels = new List();

OpenCVForUnity.Core.split (imgMat,channels);

Mat a = new Mat ();

a = channels [0];

channels [0] = channels [2];

channels [2] = a;

OpenCVForUnity.Core.merge (channels,imgMat);

Debug.Log("您按下了A鍵"+imgMat.size());

SpriteRenderer spr = gameObject.GetComponent();

Texture2D texture2d = new Texture2D (new_w, new_h);

Utils.matToTexture2D (imgMat, texture2d);

Sprite sp = Sprite.Create(texture2d,new UnityEngine.Rect(0, 0, new_w, new_h), new Vector2(0.5f,0.5f) );//注意居中顯示采用0.5f值

spr.sprite = sp;

//            gameObject.GetComponent().material.mainTexture = texture2d;

//            Mat imgMat2 = new Mat (texture2d.height, texture2d.width, CvType.CV_8UC4);

//            Utils.texture2DToMat (texture2d, imgMat2);

//            Imgcodecs.imwrite ("/Users/shiyuhuang/Downloads/ATOCAR/ATOCAR_UNITY_2/ATOCAR_UNITY/test2.jpg",imgMat2);

}

}

}