YV12转换到IplImage

来源:互联网 发布:java程序员常用的软件 编辑:程序博客网 时间:2024/06/03 16:36

最近做海康网络摄像机的时候碰到需要将YV12格式图像转换到IplImage让OpenCV来处理它,考虑到效率问题,所以用空间来换取时间。结果还是可以接受的,一秒钟转换1280 * 720的图像30帧左右,足矣。


YV12的格式请参考:

1.http://zyg0227.blog.51cto.com/1043164/295479

2.http://zh.wikipedia.org/wiki/YUV


Code.

#define max(a,b) (((a) > (b)) ? (a) : (b))#define min(a,b) (((a) < (b)) ? (a) : (b))uchar* table_r = 0;uchar* table_g = 0;uchar* table_b = 0;void YV12_2_IplImage(const uchar* yvData, IplImage* img){uchar* pData = (uchar*)img->imageData;uchar* y = (uchar*)yvData;uchar* u = y + img->imageSize / 3;uchar* v = y + img->imageSize / 3 + ((img->width / 2 + img->width % 2) * (img->height / 2 + img->height % 2));int tw = img->width / 2 + img->width % 2;int cr, cg, cb;int r, c;for (r = 0; r < img->height; ++r){for (c = 0; c < img->width; ++c){*pData++ = table_r[((int)*y << 8) + *v];*pData++ = table_g[((int)*y << 16) + ((int)*u << 8) + *v];*pData++ = table_b[((int)*y << 8) + *u];if(c % 2 == 1){++u;++v;}++y;}if(r % 2 == 0){u -= tw;v -= tw;}}}void InitColorTable(){table_r = new uchar[256 * 256];table_g = new uchar[256 * 256 * 256];table_b = new uchar[256 * 256];for (int i = 0; i < 256; ++i){for (int j = 0; j < 256; ++j){int cc = i + 1.13983 * (j - 128);table_r[(i << 8) + j] = min(max(cc, 0), 255);}}for (int i = 0; i < 256; ++i){for (int j = 0; j < 256; ++j){int cc = i + 2.03211 * (j - 128);table_b[(i << 8) + j] = min(max(cc, 0), 255);}}for (int i = 0; i < 256; ++i){for (int j = 0; j < 256; ++j)for (int k = 0; k < 256; ++k){int cc = i - 0.39465 * (j - 128) - 0.58060 * (k - 128);table_g[(i << 16) + (j << 8) + k] = min(max(cc, 0), 255);}}}