【发布时间】:2018-03-07 15:59:30
【问题描述】:
我有个小疑问希望你能解决。
我想统一创建一个 android 应用程序。该应用程序包括激活设备的摄像头并在屏幕上查看它。为此,我想基于基于 OpenCV 的原生 C++ 代码。
我有生成的代码,但是当我运行应用程序时,我看到的是场景而不是图像,我有一种感觉,这是因为 OpenCV 的 VideoCapture 功能我没有很好地用于 android。你能帮我附上代码吗:
C++:
__declspec(dllexport) void iniciar(int& widt, int& heigh) {
camera.open(0);
if (!camera.isOpened())
{
return;
}
widt = (int)camera.get(CV_CAP_PROP_FRAME_WIDTH);
heigh = (int)camera.get(CV_CAP_PROP_FRAME_HEIGHT);
trueRect.x = 5;
trueRect.y = 5;
trueRect.width = 100;
trueRect.height = 100;
midX = 1;
midY = 1;
wi = 0;
he = 0;
}
__declspec(dllexport)
void video(unsigned char* arr) {
Mat frame;
Mat resi;
Mat dst;//dst image
camera >> frame;
if (frame.empty()) {
return;
}
flip(frame, dst,1);
//resize(dst, resi, Size(width, height));
cv::cvtColor(dst, dst, COLOR_BGR2RGB);
copy(dst.datastart, dst.dataend, arr);
}
C#:
public class camara : MonoBehaviour {
[DllImport("NativoPrincipio")]
public static extern void video(byte[] img);
[DllImport("NativoPrincipio")]
public static extern void iniciar(ref int widt, ref int heigh);
WebCamTexture back;
Texture2D textura;
byte[] imgData;
int width = 0;
int height = 0;
// Use this for initialization
void Start () {
back = new WebCamTexture();
//GetComponent<Renderer>().material.mainTexture = back;
//back.Play();
iniciar(ref width, ref height);
}
// Update is called once per frame
void Update ()
{
imgData = new byte[width * height * 4];
video(imgData);
textura = new Texture2D(width, height, TextureFormat.RGB24, false);
textura.LoadRawTextureData(imgData);
textura.Apply();
GetComponent<Renderer>().material.mainTexture = textura;
imgData = null;
textura = null;
}}
【问题讨论】:
-
imgData = new byte[width * height * 4];为什么要乘以 4?您的相机是否提供 4 通道图像? -
因为是 RGB 图像,我尝试放置 3 个通道但失败。所以我放了 4 个频道
-
RGB表示 3 个通道。如果您的代码失败,那是因为其他原因。正如@uelordi 建议的那样,尝试使用Java 本机代码捕获图像,仅使用OpenCV 处理图像。
标签: c# android c++ opencv unity3d