FFMPEG: RGB to YUV conversion by binary ffmpeg and by code C++ give different results

荒凉一梦 提交于 2020-01-06 09:53:52

问题


I am trying to convert RGB frames (ppm format) to YUV420P format using ffmpeg. To make sure that my code C++ is good , I compared the output with the one created by this command (the same filer BILINEAR): ffmpeg -start_number 1 -i data/test512x512%d.ppm -sws_flags 'bilinear' -pix_fmt yuv420p data/test-yuv420p.yuv

My code :

static unsigned char *readPPM(int i)
{
  FILE *pF;
  unsigned char *imgRGB;
  unsigned char *imgBGR;
  int w,h;
  int c;
  int bit;
  char buff[16];

  char *filename;
  asprintf(&filename,"test512x512%d.ppm",i);
  pF = fopen(filename,"rb");
  free(filename);

  if (pF) {
    if (!fgets(buff, sizeof(buff), pF)) {
      return nullptr;
    }
    if (buff[0] != 'P' || buff[1] != '6') {
      fprintf(stderr, "Invalid image format (must be 'P6')\n");
    return nullptr;
  }
  c = getc(pF);
  while (c == '#') {
    while (getc(pF) != '\n') ;
      c = getc(pF);
  }
  ungetc(c, pF);
  // read size
  if (fscanf(pF, "%d %d", &w, &h) != 2) {
    fprintf(stderr, "Invalid image size (error loading '%s')\n", filename);
    return nullptr;

  }
  //read bit
  if (fscanf(pF, "%d", &bit) != 1) {
    fprintf(stderr, "Invalid rgb component (error loading '%s')\n", filename);
    exit(1);
  }

  imgRGB =(unsigned char*) malloc(3*h*w);
  imgBGR =(unsigned char*) malloc(3*h*w);
  //read pixel data from file
  int length = fread(imgBGR, sizeof(unsigned char)*3, w*h, pF) ;
  if (length != w*h) {
    fprintf(stderr, "Error loading image '%s'\n", filename);
    return nullptr;
  }


  int start=0;
  for (i=0; i < HEIGHT*WIDTH;i++) {
   imgRGB[start] = imgBGR[start];
   imgRGB[start+2]= imgBGR[start+2];
   imgRGB[start+1]= imgBGR[start+1];
   start+=3;
  }

  fclose(pF);
  free(imgBGR);
  return imgRGB;
}
else {
  return nullptr;
}
}

void Test_FFMPEG::FillFrame (uint8_t* pic, int index)
{

 avpicture_fill((AVPicture*)RGBFrame, pic, AV_PIX_FMT_RGB24, encodeContext->width, encodeContext->height);

  struct SwsContext* fooContext = sws_getContext(encodeContext->width, encodeContext->height,
  PIX_FMT_RGB24,
  encodeContext->width, encodeContext->height,
  PIX_FMT_YUV420P,
  SWS_BILINEAR  , nullptr, nullptr, nullptr);
  sws_scale(fooContext, RGBFrame->data, RGBFrame->linesize, 0, encodeContext->height, OrgFrame->data, OrgFrame->linesize);

  OrgFrame->pts = index;
}

The comparison result is not good. The are slight differences in Y and V but a lot in U. I cannot post my images but there is a part of Y is in U image. And it makes color change a little bit.

Can you tell me where is my error? Thanks you


回答1:


I'm not positive about the ffmpeg defaults, but using SWS_BILINEAR | SWS_ACCURATE_RND should produce better results.



来源:https://stackoverflow.com/questions/27449177/ffmpeg-rgb-to-yuv-conversion-by-binary-ffmpeg-and-by-code-c-give-different-re

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!