yuv420转为cv::Mat

函数1:读取avi格式的视频文件,转换成Yuv420格式,并写入文件

void WriteYuv()  
{  
    cv::VideoCapture vc;  
    bool flag = vc.open("S1000008.avi");  
    if (!flag)  
    {  
        printf("avi file open error \n");  
        system("pause");  
        exit(-1);  
    }  
  
    int frmCount = vc.get(CV_CAP_PROP_FRAME_COUNT);  
    frmCount -= 5;  
    printf("frmCount: %d \n", frmCount);  
  
    int w = vc.get(CV_CAP_PROP_FRAME_WIDTH);  
    int h = vc.get(CV_CAP_PROP_FRAME_HEIGHT);  
    int bufLen = w*h*3/2;  
    unsigned char* pYuvBuf = new unsigned char[bufLen];  
    FILE* pFileOut = fopen("result.yuv", "w+");  
    if (!pFileOut)  
    {  
        printf("pFileOut open error \n");  
        system("pause");  
        exit(-1);  
    }  
    printf("pFileOut open ok \n");  
      
    for (int i=0; i>srcImg;  
  
        cv::imshow("img", srcImg);  
        cv::waitKey(1);  
  
        cv::Mat yuvImg;  
        cv::cvtColor(srcImg, yuvImg, CV_BGR2YUV_I420);  
        memcpy(pYuvBuf, yuvImg.data, bufLen*sizeof(unsigned char));  
  
        fwrite(pYuvBuf, bufLen*sizeof(unsigned char), 1, pFileOut);  
    }  
  
    fclose(pFileOut);  
    delete[] pYuvBuf;  
}  

函数二,读取yuv420格式的文件,转换成cv::Mat格式,并予以显示

void DisplayYUV()  
{  
    int w = 1280;  
    int h = 720;  
    printf("yuv file w: %d, h: %d \n", w, h);  
  
    FILE* pFileIn = fopen("result.yuv", "rb+");  
    int bufLen = w*h*3/2;  
    unsigned char* pYuvBuf = new unsigned char[bufLen];  
    int iCount = 0;  
  
  
    for(int i=0; i<200; i++)  
    {  
        fread(pYuvBuf, bufLen*sizeof(unsigned char), 1, pFileIn);  
  
        cv::Mat yuvImg;  
        yuvImg.create(h*3/2, w, CV_8UC1);   
        memcpy(yuvImg.data, pYuvBuf, bufLen*sizeof(unsigned char));  
        cv::Mat rgbImg;  
        cv::cvtColor(yuvImg, rgbImg, CV_YUV2BGR_I420);  
  
        cv::imshow("img", yuvImg);  
        cv::waitKey(1);  
  
        printf("%d \n", iCount++);  
    }  
  
    delete[] pYuvBuf;  
  
  
    fclose(pFileIn);  
}  

 

你可能感兴趣的:(音视频开发)