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