接着上篇文章,如果得到的yuv是倒的,但我希望得到正的图,即将左边的yuv_out.yuv旋转180度,希望得到右图rotate180.yuv
这里需要理解,yuv420p图片,宽w,高h,图像分辨率是w*h,但是并不是说图像在内存中就是w*h的“正方形”内存大小,它的实际内存是超过w*h的,具体是y占了w*h,然后接着u占了w/2*h/2,接着是v占w/2*h/2。
图像旋转180度,则原图的最右下角应该为我们目标图的第一个点,然后以此从右往左,从下往上进行像素点读取。
void yuv_rotate_180(const char* yuvfilename,int width,int height){
FILE* fp = NULL;
fopen_s(&fp,yuvfilename,"rb");
uint8_t* yuvbuf = new uint8_t[width*height * 3 / 2];
fread(yuvbuf, width*height * 3 / 2, 1, fp);
fclose(fp);
uint8_t* dstbuf = new uint8_t[width*height*3/2];
int idx = 0;
//旋转180:将右下角的点作为第一个点,从右往左,从下往上取点
//Y 宽:[0,w-1] 高:[0,h-1]
for (int i = height-1; i >=0; i--){
for (int j = width-1 ; j >= 0; j--){
dstbuf[idx++] = *(yuvbuf+(i*width+j));
}
}
uint8_t* uheader = yuvbuf + width*height;
//U
for (int i = height/2 - 1; i >= 0; i--){
for (int j = width/2-1 ; j >= 0; j--){
dstbuf[idx++] = *(uheader + (i*width / 2 + j));
}
}
uint8_t* vheader = uheader + width*height/4;
//V
for (int i = height / 2 - 1; i >= 0; i--){
for (int j = width / 2-1 ; j >=0; j--){
dstbuf[idx++] = *(vheader + (i*width / 2 + j));
}
}
FILE* fpout = NULL;
fopen_s(&fpout,"rotate180.yuv","wb");
fwrite(dstbuf, width*height * 3 / 2,1,fpout);
fclose(fpout);
delete[] yuvbuf;
delete[] dstbuf;
}
拓展一下,如果由手机摄像头拍出来的照片,我们希望做水平镜像翻转,其实原理都一样,直接上代码
//镜像翻转
void yuv_flip(const char* yuvfilename, int width, int height){
FILE* fp = NULL;
fopen_s(&fp, yuvfilename, "rb");
uint8_t* yuvbuf = new uint8_t[width*height * 3 / 2];
fread(yuvbuf, width*height * 3 / 2, 1, fp);
fclose(fp);
uint8_t* dstbuf = new uint8_t[width*height * 3 / 2];
int idx = 0;
//水平翻转:将右上角的点作为第一个点,从右往左,从上往下取点
//Y 宽:[0,w-1] 高:[0,h-1]
for (int i = 0; i<height; i++){
for (int j = width - 1; j >= 0; j--){
dstbuf[idx++] = *(yuvbuf + (i*width + j));
}
}
uint8_t* uheader = yuvbuf + width*height;
//U
for (int i = 0; i < height / 2 ; i++){
for (int j = width / 2 - 1; j >= 0; j--){
dstbuf[idx++] = *(uheader + (i*width / 2 + j));
}
}
uint8_t* vheader = uheader + width*height / 4;
//V
for (int i = 0; i < height / 2; i++){
for (int j = width / 2 - 1; j >= 0; j--){
dstbuf[idx++] = *(vheader + (i*width / 2 + j));
}
}
FILE* fpout = NULL;
fopen_s(&fpout, "flip_out.yuv", "wb");
fwrite(dstbuf, width*height * 3 / 2, 1, fpout);
fclose(fpout);
delete[] yuvbuf;
delete[] dstbuf;
}