- Home /
Problem with capture image from web camera.
Hi, I am going to pass the image captured with my own plugin to unity. But I found that Texture2D.Apply() function is very slow. And the game runs only on 12-15 fps. Is there any possibility to walk around the Apply() function? May I pass the image to the VRAM directly?
Thanks in advance!
My code is as follow.
using UnityEngine;
using System.Collections; using System.Runtime.InteropServices; using System.Threading;
public class WebCamera : MonoBehaviour {
[DllImport("OpencvKinectGrabber.dll", EntryPoint = "InitSystem")]
public static extern void InitSystem();
[DllImport("OpencvKinectGrabber.dll", EntryPoint = "GetImage")]
public static extern bool GetImage(byte[] data);
[DllImport("OpencvKinectGrabber.dll", EntryPoint = "InitSystem")]
public static extern void EndSystem();
WebCamTexture webcamTex ;
WebCamDevice[] devices;
Texture2D cvTexture;
Color32[] colors;
byte[] data;
Thread hThread;
public RenderTexture renderTexture;
bool quit = false;
// Use this for initialization
void Start () {
/*
devices = WebCamTexture.devices;
webcamTex = new WebCamTexture(devices[1].name,640,480,30);
print(devices[1].name);
renderer.material.mainTexture = webcamTex;
webcamTex.Play();
*/
InitSystem();
cvTexture = new Texture2D(640,480);
colors = new Color32[640*480];
data = new byte[640*480*4];
renderer.material.mainTexture = cvTexture;
hThread = new Thread(Loop);
hThread.Start();
}
void Loop()
{
while(!quit)
{
bool result = GetImage(data);
if(!result)
return;
for (int i=0;i<480;i++)
{
for (int j = 0;j<640;j++)
{
colors[(i*640+j)].b = data[(i*640+j)*4+0];
colors[(i*640+j)].g = data[(i*640+j)*4+1];
colors[(i*640+j)].r = data[(i*640+j)*4+2];
colors[(i*640+j)].a = 255;
}
}
}
}
// Update is called once per frame
void Update () {
cvTexture.SetPixels32(colors);
cvTexture.Apply(false);
}
void OnApplicationQuit()
{
quit = true;
EndSystem();
}
}
I'm a bit confused at what you're trying to do. From what I understand, you want to display a picture created in your plugin in Unity.
It looks like you get the pixels from your plugin with GetImage() and apply it on a texture2D.
In this case, why are you using a WebcamTexture?
Hi Dnjata , I am not using the webcamTexture. What I am going to do is to write the image data into the VRA$$anonymous$$ directly, not using the Texture2D.Apply() function. Because it is quite slow. Thx.
Your answer
![](https://koobas.hobune.stream/wayback/20220613070506im_/https://answers.unity.com/themes/thub/images/avi.jpg)