Skip to content

Instantly share code, notes, and snippets.

@RdlP
Last active April 5, 2017 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RdlP/d6661c2a5a2036913be59fa7f971e447 to your computer and use it in GitHub Desktop.
Save RdlP/d6661c2a5a2036913be59fa7f971e447 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
using Emgu.CV;
using Emgu.CV.Util;
using Emgu.CV.UI;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using System.Runtime.InteropServices;
using System;
using UnityEngine.UI;
public class OpenCVUnity : MonoBehaviour {
public RawImage raw;
private WebCamTexture wct;
public Color32[] data;
void Start () {
wct = new WebCamTexture ();
wct.Play();
}
public static Image<Bgr, byte> UnityTextureToOpenCVImage(Color32[] data, int width, int height){
byte[,,] imageData = new byte[width, height, 3];
int index = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
imageData[x,y,0] = data[index].b;
imageData[x,y,1] = data[index].g;
imageData[x,y,2] = data[index].r;
index++;
}
}
Image<Bgr, byte> image = new Image<Bgr, byte>(imageData);
return image;
}
public static Texture2D OpenCVImageToUnityTexture(byte[,,] data, int width, int height){
Color32 [] imageData = new Color32[width*height];
int index = 0;
byte alpha = 255;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
imageData[index] = new Color32((data[x,y,2]),
(data[x,y,1]),
(data[x,y,0]),
alpha);
index++;
}
}
Texture2D toReturn = new Texture2D(width, height, TextureFormat.RGBA32, false);
toReturn.SetPixels32(imageData);
toReturn.Apply ();
toReturn.wrapMode = TextureWrapMode.Repeat;
return toReturn;
}
// Update is called once per frame
void Update () {
data = wct.GetPixels32 ();
Image<Bgr, byte> image = UnityTextureToOpenCVImage (data, wct.width, wct.height);
Image<Bgr, byte> blur = image.SmoothBlur(20,20,true);
Texture2D tex = OpenCVImageToUnityTexture (blur.Data, wct.width, wct.height);
raw.texture = tex;
// For test
//ConvolutionKernelF k = new ConvolutionKernelF (kernel);
//Image<Bgr, float> edge = image.Convolution (k);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment