RGB到FFMPEG中YUV转换的错误

Error in RGB to YUV conversion in FFmpeg

本文关键字:转换 错误 YUV FFMPEG RGB      更新时间:2023-10-16

我正在尝试将RGB图像转换为YUV。我正在使用OpenCV加载图像。

我称之为以下功能:

//I know IplImage is outdated 
IplImage* im = cvLoadImage("1.jpg", 1);
//....
bgr2yuv(im->imageData, dst, im->width, im->height);

下面给出了将颜色图像转换为YUV图像的功能。我正在使用ffmpeg来做到这一点。

void bgr2yuv(unsigned char *src, unsigned char *dest, int w, int h)
{
  AVFrame *yuvIm = avcodec_alloc_frame();
  AVFrame *rgbIm = avcodec_alloc_frame();
  avpicture_fill(rgbIm, src, PIX_FMT_BGR24, w, h);
  avpicture_fill(yuvIm, dest, PIX_FMT_YUV420P, w, h);
  av_register_all();
  struct SwsContext * imgCtx = sws_getCachedContext(imgCtx,
                                         w, h,(::PixelFormat)PIX_FMT_BGR24,
                                         w, h,(::PixelFormat)PIX_FMT_YUV420P,
                                         SWS_BICUBIC, NULL, NULL, NULL);
  sws_scale(imgCtx, rgbIm->data, rgbIm->linesize,0, h, yuvIm->data, yuvIm->linesize);
  av_free(yuvIm);
  av_free(rgbIm);
}

转换后我的输出错误。我认为这是由于iPlimage中发生的填充物。(我的输入图像宽度不是4的倍数)。

我更新了线条变量,即使我无法获得正确的输出。当我使用宽度为4的图像时,它的工作正常。

任何人都可以告诉代码中有什么问题。

检查iPlimage :: Align或iPlimage :: widthstep,并使用这些设置AVFRAME :: LINESize。例如,对于RGB帧,您将设置:

frame->linesize[0] = img->widthStep;

dst数组的布局可以是您想要的,这取决于您之后的使用方式。

我们需要如下:

rgbIm->linesize[0] = im->widthStep;

,但我认为来自sws_scale()的输出数据没有填充以使其成为4的倍数。因此,当您再次将此数据(dest)复制到Iplimage时在显示,保存等时创建问题。

因此我们需要设置widthStep=width如下:

IplImage* yuvImage = cvCreateImageHeader(cvGetSize(im), 8, 1);
yuvImage->widthStep = yuvImage->width;
yuvImage->imageData = dest;