我正在使用此代码从我的Android手机获取CameraPreview
-
private Camera.PreviewCallback mPreviewCallback = new PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
synchronized (mQueue) {
if (mQueue.size() == MAX_BUFFER) {
mQueue.poll();
}
mQueue.add(data);
}
}
};
然后通过Sockets
-
mSocket = new Socket();
mSocket.connect(new InetSocketAddress(mIP, mPort), 10000);
BufferedOutputStream outputStream = new BufferedOutputStream(mSocket.getOutputStream());
BufferedInputStream inputStream = new BufferedInputStream(mSocket.getInputStream());
outputStream.write(mCameraPreview.getImageBuffer());
outputStream.flush();
我从this网站获得了这些代码,但服务器(我的Windows PC)编码在C++
,网站上的服务器代码位于Java
。我想解码CameraPreview
字节并在我的OpenCV窗口中显示它们。我可以接收字节,也显示它们,但我需要帮助将字节转换为图像。任何人都可以帮我这个吗?
对于那些不想访问服务器Java代码的网站的人来说,这是代码 -
在服务器端,使用缓冲区队列来缓存传入数据:
public int fillBuffer(byte[] data, int off, int len, LinkedList<byte[]> YUVQueue) {
mTotalLength += len;
mByteArrayOutputStream.write(data, off, len);
if (mTotalLength == mFrameLength) {
synchronized (YUVQueue) {
YUVQueue.add(mByteArrayOutputStream.toByteArray());
mByteArrayOutputStream.reset();
}
mTotalLength = 0;
System.out.println("received file");
}
return 0;
}
参考StackOverflow,我们可以使用以下代码解码NV21数据:
public static int[] convertYUVtoRGB(byte[] yuv, int width, int height)
throws NullPointerException, IllegalArgumentException {
int[] out = new int[width * height];
int sz = width * height;
int i, j;
int Y, Cr = 0, Cb = 0;
for (j = 0; j < height; j++) {
int pixPtr = j * width;
final int jDiv2 = j >> 1;
for (i = 0; i < width; i++) {
Y = yuv[pixPtr];
if (Y < 0)
Y += 255;
if ((i & 0x1) != 1) {
final int cOff = sz + jDiv2 * width + (i >> 1) * 2;
Cb = yuv[cOff];
if (Cb < 0)
Cb += 127;
else
Cb -= 128;
Cr = yuv[cOff + 1];
if (Cr < 0)
Cr += 127;
else
Cr -= 128;
}
int R = Y + Cr + (Cr >> 2) + (Cr >> 3) + (Cr >> 5);
if (R < 0)
R = 0;
else if (R > 255)
R = 255;
int G = Y - (Cb >> 2) + (Cb >> 4) + (Cb >> 5) - (Cr >> 1)
+ (Cr >> 3) + (Cr >> 4) + (Cr >> 5);
if (G < 0)
G = 0;
else if (G > 255)
G = 255;
int B = Y + Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6);
if (B < 0)
B = 0;
else if (B > 255)
B = 255;
out[pixPtr++] = 0xff000000 + (B << 16) + (G << 8) + R;
}
}
return out;
}