Android拍摄视频流的格式转换(YUV --- RGB)
Android允许用户实时捕获摄像头的视频流,这在利用摄像头的AR应用中非常有用。可以利用摄像流实时做画面图像的分析,并做出许多有用的应用。比如人脸识别,条码识别,特定图像替换等等,不过大多数图像处理软件在处理时是需要RGB格式的图像,而默认的视频流是压缩的YUV格式,Android下是YUV420SP,这个格式,虽然可以在程序中修改,但是修改后好像不起作用,也就是说只能得到编码为YUV420SP的视频流,这就需要把YUV420SP的视频流转换成RGB格式的图像,用于图像识别。
static public void decodeYUV420SP(byte[] rgbBuf, byte[] yuv420sp, int width, int height) {
final int frameSize = width * height;
if (rgbBuf == null)
throw new NullPointerException("buffer 'rgbBuf' is null");
if (rgbBuf.length
throw new IllegalArgumentException("buffer 'rgbBuf' size "
+ rgbBuf.length + " if (yuv420sp == null)
throw new NullPointerException("buffer 'yuv420sp' is null");
if (yuv420sp.length
throw new IllegalArgumentException("buffer 'yuv420sp' size " + yuv420sp.length
+ " int i = 0, y = 0;
int uvp = 0, u = 0, v = 0;
int y1192 = 0, r = 0, g = 0, b = 0;
for (int j = 0, yp = 0; j uvp = frameSize + (j >> 1) * width;
u = 0;
v = 0;
for (i = 0; i y = (0xff & ((int) yuv420sp[yp])) - 16;
if (y <0) y &#61; 0;
if ((i & 1) &#61;&#61; 0) {
v &#61; (0xff & yuv420sp[uvp&#43;&#43;]) - 128;
u &#61; (0xff & yuv420sp[uvp&#43;&#43;]) - 128;
}
y1192 &#61; 1192 * y;
r &#61; (y1192 &#43; 1634 * v);
g &#61; (y1192 - 833 * v - 400 * u);
b &#61; (y1192 &#43; 2066 * u);
if (r <0) r &#61; 0; else if (r > 262143) r &#61; 262143;
if (g <0) g &#61; 0; else if (g > 262143) g &#61; 262143;
if (b <0) b &#61; 0; else if (b > 262143) b &#61; 262143;
rgbBuf[yp * 3] &#61; (byte)(r >> 10);
rgbBuf[yp * 3 &#43; 1] &#61; (byte)(g >> 10);
rgbBuf[yp * 3 &#43; 2] &#61; (byte)(b >> 10);
}
}
}