0. 代码如下:
extern "C"
{
#ifdef __cplusplus
#define __STDC_CONSTANT_MACROS
#endif
}
extern "C" {
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
}
/**
* Split Y, U, V planes in YUV444P file.
* @param url Location of Input YUV file.
* @param w Width of Input YUV file.
* @param h Height of Input YUV file.
* @param num Number of frames to process.
*
*/
/**
* Convert YUV420P file to gray picture
* @param url Location of Input YUV file.
* @param w Width of Input YUV file.
* @param h Height of Input YUV file.
* @param num Number of frames to process.
*/
int simplest_yuv420_gray(const char* url, int w, int h, int num) {
FILE* fp = fopen(url, "rb+");
FILE* fp1 = fopen("output_gray.yuv", "wb+");
unsigned char* pic = (unsigned char*)malloc(w * h * 3 / 2);
for (int i = 0; i < num; i++) {
fread(pic, 1, w * h * 3 / 2, fp);
//Gray
memset(pic + w * h, 128, w * h / 2); //U、V分量置128
fwrite(pic, 1, w * h * 3 / 2, fp1);
}
free(pic);
fclose(fp);
fclose(fp1);
return 0;
}
int main()
{
simplest_yuv420_gray("lena_256x256_yuv420p.yuv", 256, 256, 1);
return 0;
}
这是因为U、V是图像中的经过偏置处理的色度分量。
色度分量在偏置处理前的取值范围是-128至127,这时候的无色对应的是“0”值。经过偏置后色度分量取值变成了0至255,因而此时的无色对应的就是128了。
上述调用函数的代码运行后,将会把一张分辨率为256x256的名称为lena_256x256_yuv420p.yuv的YUV420P格式的像素数据文件处理成名称为output_gray.yuv的YUV420P格式的像素数据文件。
1. 效果如下
像素格式,设置为YUV420
源图像如下:
处理之后的效果如下:
参考链接:
https://blog.csdn.net/leixiaohua1020/article/details/50534150