李国帅 2010
不通过第三方库函数进行直接转换
#include <TIME.H>
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
long writefile(fstream& oStream, char* content, long contentlen)
{
oStream.seekp(0, ios::end);
streamsize _Count = (streamsize)strlen(content);
//UINT nActual = (UINT)oStream.tellp();
//strcpy_s(content,contentlen,("<?xml version=\"1.0\" encoding=\"GB2312\" ?>\r\n<DateSet>\r\n</DateSet>"));
oStream.write(content, _Count + 1);//
return 0;
}
void YUV2RGB(unsigned char Y, unsigned char U, unsigned char V, unsigned char* pRGB)
{
int R, G, B;
B = (int)(1.164*(Y - 16) + 2.018*(U - 128));
G = (int)(1.164*(Y - 16) - 0.813*(V - 128) - 0.391*(U - 128));
R = (int)(1.164*(Y - 16) + 1.596*(V - 128));
// #define GETR(y,u,v) ((1.164 * (y - 16)) + (1.596 * ((v) - 128)))
// #define GETG(y,u,v) ((1.164 * (y - 16)) - (0.813 * ((v) - 128)) - (0.391 * ((u) - 128)))
// #define GETB(y,u,v) ((1.164 * (y - 16)) + (2.018 * ((u) - 128)))
//cout << "RGB("<<GETR(y,u,v)<<","<<GETG(y,u,v)<<","<<GETB(y,u,v)<<","<<")"<<endl;
//cout << "("<<(int)Y<<","<<(int)U<<","<<(int)V<<")->RGB("<<R<<","<<G<<","<<B<<","<<")"<<endl;
R = min(255, max(0, R));
G = min(255, max(0, G));
B = min(255, max(0, B));
pRGB[0] = R;
pRGB[1] = G;
pRGB[2] = B;
return;
}
void RGB2YUV(unsigned char R, unsigned char G, unsigned char B, unsigned char* pYUV)
{
int Y, U, V;
Y = 16 + 0.257*R + 0.504*G + 0.098*B;
U = 128 - 0.148*R - 0.291*G + 0.439*B;
V = 128 + 0.439*R - 0.368*G - 0.071*B;
Y = min(255, max(0, Y));
U = min(255, max(0, U));
V = min(255, max(0, V));
pYUV[0] = Y;
pYUV[1] = U;
pYUV[2] = V;
return;
}
int __cdecl main(int argc, CHAR **argv)
{
unsigned char RGB[3];
unsigned char YUV[3];
char* filename = "c:\\testyuv.log";
fstream oStream(filename, ios::app | ios::out | ios::in); // 定义打开输出流 ios::binary|
bool bRet = oStream.fail();
if (bRet) return 0;
int r = 255, g = 0, b = 0;
RGB2YUV(r, g, b, YUV);
cout << "(" << (unsigned int)(YUV[0]) << "," << (unsigned int)(YUV[1]) << "," << (unsigned int)(YUV[2]) << ")->RGB(" << r << "," << g << "," << b << "," << ")" << endl;
int y = (unsigned int)(YUV[0]), u = (unsigned int)(YUV[1]), v = (unsigned int)(YUV[2]);
YUV2RGB(y, u, v, RGB);
cout << "(" << (int)y << "," << (int)u << "," << (int)v << ")->RGB(" << (unsigned int)(RGB[0]) << "," << (unsigned int)(RGB[1]) << "," << (unsigned int)(RGB[2]) << "," << ")" << endl;
oStream.flush();
oStream.close(); // 关闭输出流
//::DeleteFile(filename);
system("PAUSE");
return 0;
}
//生成一个rgb白色图片
void write_demo_rgb_file()
{
unsigned char RGB[3];
char output[50];
int y, u, v;
for (y = 0; y < 256; y++)
{
for (u = 0; u < 256; u++)
for (v = 0; v < 256; v++) {
/* initialize coefficient table using formula definition */
YUV2RGB(y, u, v, RGB);
sprintf_s(output, 50, "(%u,%u,%u)->RGB(%u,%u,%u)", y, u, v, (unsigned int)(RGB[0]), (unsigned int)(RGB[1]), (unsigned int)(RGB[2]));
writefile(oStream, output, strlen(output));
}
}
}