sws_scale YUV --> RGB 失真图像



我想转换YUV420P图像(从H.264流接收)到RGB,同时也调整它的大小,使用sws_scale
原始图像的大小为480 × 800。只要转换成相同的尺寸就可以了。
但是当我尝试改变尺寸时,我得到了一个扭曲的图像,具有以下模式:

  • 更改为481 × 800将产生失真的B&W图像,看起来像是从中间剪切的
  • 482 × 800将会更加失真
  • 483 × 800是扭曲的,但在颜色
  • 484 × 800 ok(缩放正确)。

现在遵循这个模式-只有当两者之间的差除以4时,缩放才会正常工作。

下面是我解码和转换图像的示例代码。所有的方法都显示"成功"。

int srcX = 480;
int srcY = 800;
int dstX = 481; // or 482, 483 etc
int dstY = 800;
AVFrame* avFrameYUV = avcodec_alloc_frame();
avpicture_fill((AVPicture *)avFrameYUV, decoded_yuv_frame, PIX_FMT_YUV420P, srcX , srcY);
AVFrame *avFrameRGB = avcodec_alloc_frame();
AVPacket avPacket;
av_init_packet(&avPacket);
avPacket.size = read; // size of raw data
avPacket.data = raw_data; // raw data before decoding to YUV
int frame_decoded = 0;
int decoded_length = avcodec_decode_video2(g_avCodecContext, avFrameYUV, &frame_decoded, &avPacket);
int size = dstX * dstY * 3;
struct SwsContext *img_convert_ctx = sws_getContext(srcX, srcY, SOURCE_FORMAT, dstX, dstY, PIX_FMT_BGR24, SWS_BICUBIC, NULL, NULL, NULL);
avpicture_fill((AVPicture *)avFrameRGB, rgb_frame, PIX_FMT_RGB24, dstX, dstY);
sws_scale(img_convert_ctx, avFrameYUV->data, avFrameYUV->linesize, 0, srcY, avFrameRGB->data, avFrameRGB->linesize);
// draws the resulting frame with windows BitBlt
DrawBitmap(hdc, dstX, dstY, rgb_frame, size);
sws_freeContext(img_convert_ctx); 

当您制作位图图像时,图像宽度必须是4的倍数。

所以你需要改变宽度比如480484 488 492…

这是一个方法来改变为4的倍数

#define WIDTHBYTES(bits) (((bits) + 31) / 32 * 4)
void main()
{
    BITMAPFILEHEADER bmFileHeader;
    BITMAPINFOHEADER bmInfoHeader;
    // load image
    // ...
    // when you use the method, put parameter like this.
    int tempWidth = WIDTHBYTES(width * bmInfoHeader.biBitCount);
}

我希望你能解决这个问题。

最新更新