📄 convertyuv.cpp
字号:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<iostream>
#define MY(a,b,c) (( a* 0.2989 + b* 0.5866 + c* 0.1145))
#define MU(a,b,c) (( a*(-0.1688) + b*(-0.3312) + c* 0.5000 + 128))
#define MV(a,b,c) (( a* 0.5000 + b*(-0.4184) + c*(-0.0816) + 128))
#define DY(a,b,c) (MY(a,b,c) > 255 ? 255 : (MY(a,b,c) < 0 ? 0 : MY(a,b,c)))
#define DU(a,b,c) (MU(a,b,c) > 255 ? 255 : (MU(a,b,c) < 0 ? 0 : MU(a,b,c)))
#define DV(a,b,c) (MV(a,b,c) > 255 ? 255 : (MV(a,b,c) < 0 ? 0 : MV(a,b,c)))
#define WIDTH 352
#define HEIGHT 288
void ReadBmp(unsigned char *RGB,FILE *fp);
void Convert(unsigned char *RGB, unsigned char *YUV);
int main()
{
int i=1;
char file[255];
FILE *fp;
FILE *fp2;
unsigned char *YUV = NULL;
unsigned char *RGB = NULL;
unsigned int imgSize = WIDTH*HEIGHT;
if((fp2 = fopen("C:\\test.cif", "wb")) == NULL)
{
return 0;
}
RGB = (unsigned char*)malloc(imgSize*6);
YUV = (unsigned char*)malloc(imgSize + (imgSize>>1));
for(i=1; i<2; i++)
{
sprintf(file, "C:\\test.bmp", i);
if((fp = fopen(file, "rb")) == NULL)
continue;
printf("Open file: %s\n", file);
ReadBmp(RGB, fp);
Convert(RGB, YUV);
fwrite(YUV, 1, imgSize+(imgSize>>1), fp2);
fclose(fp);
}
fclose(fp2);
if(RGB)
free(RGB);
if(YUV)
free(YUV);
printf("done\n");
system("pause");
return 1;
}
void ReadBmp(unsigned char *RGB,FILE *fp)
{
int i,j;
unsigned char temp;
fseek(fp,54, SEEK_SET);
fread(RGB+WIDTH*HEIGHT*3, 1, WIDTH*HEIGHT*3, fp);
for(i=HEIGHT-1,j=0; i>=0; i--,j++)
{
memcpy(RGB+j*WIDTH*3,RGB+WIDTH*HEIGHT*3+i*WIDTH*3,WIDTH*3);
}
for(i=0; (unsigned int)i < WIDTH*HEIGHT*3; i+=3)
{
temp = RGB[i];
RGB[i] = RGB[i+2];
RGB[i+2] = temp;
}
}
void Convert(unsigned char *RGB, unsigned char *YUV)
{
unsigned int i,x,y,j;
unsigned char *Y = NULL;
unsigned char *U = NULL;
unsigned char *V = NULL;
Y = YUV;
U = YUV + WIDTH*HEIGHT;
V = U + ((WIDTH*HEIGHT)>>2);
for(y=0; y < HEIGHT; y++)
for(x=0; x < WIDTH; x++)
{
j = y*WIDTH + x;
i = j*3;
Y[j] = (unsigned char)(DY(RGB[i], RGB[i+1], RGB[i+2]));
if(x%2 == 1 && y%2 == 1)
{
j = (WIDTH>>1) * (y>>1) + (x>>1);
U[j] = (unsigned char)
((DU(RGB[i ], RGB[i+1], RGB[i+2]) +
DU(RGB[i-3], RGB[i-2], RGB[i-1]) +
DU(RGB[i -WIDTH*3], RGB[i+1-WIDTH*3], RGB[i+2-WIDTH*3]) +
DU(RGB[i-3-WIDTH*3], RGB[i-2-WIDTH*3], RGB[i-1-WIDTH*3]))/4);
V[j] = (unsigned char)
((DV(RGB[i ], RGB[i+1], RGB[i+2]) +
DV(RGB[i-3], RGB[i-2], RGB[i-1]) +
DV(RGB[i -WIDTH*3], RGB[i+1-WIDTH*3], RGB[i+2-WIDTH*3]) +
DV(RGB[i-3-WIDTH*3], RGB[i-2-WIDTH*3], RGB[i-1-WIDTH*3]))/4);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -