1. 程式人生 > >ffmpeg將rgba資料轉成png圖片

ffmpeg將rgba資料轉成png圖片

最近在做熱區圖分析,需要對視訊中的一些熱區資訊產生熱區圖,併疊加到視訊背景圖上,主要工作有兩部分:

1.分析熱區資料,生成rgba資料(本文暫時先不講具體實現);

2.用ffmepg將rgba資料生成png圖(主要講這部分內容);

具體實現程式碼如下:

bool save_pic(AVFrame *frm, AVPixelFormat pfmt, AVCodecID cid, const char* filename, int width, int height)
{
int outbuf_size = width * height*4;
uint8_t * outbuf = (uint8_t*)malloc(outbuf_size);
int got_pkt = 0;

FILE* pf;
pf = fopen(filename, "wb");
if (pf == NULL)
	return false;
AVPacket pkt;
AVCodec *pCodecRGB24;
AVCodecContext *ctx = NULL;
pCodecRGB24 = avcodec_find_encoder(cid);
if (!pCodecRGB24)
	return false;
ctx = avcodec_alloc_context3(pCodecRGB24);
ctx->bit_rate = 3000000;
ctx->width = width;
ctx->height = height;
AVRational rate;
rate.num = 1;
rate.den = 25;
ctx->time_base = rate;
ctx->gop_size = 10;
ctx->max_b_frames = 0;
ctx->thread_count = 1;
ctx->pix_fmt = pfmt;


int ret = avcodec_open2(ctx, pCodecRGB24, NULL);
if (ret < 0)
	return false;

//	int size = ctx->width * ctx->height * 4;
av_init_packet(&pkt);
static int got_packet_ptr = 0;
pkt.size = outbuf_size;
pkt.data = outbuf;
got_pkt = avcodec_encode_video2(ctx, &pkt, frm, &got_packet_ptr);
frm->pts++;
if (got_pkt == 0)
{
	fwrite(pkt.data, 1, pkt.size, pf);
}
else
{
	return false;
}
fclose(pf);
return true;
}
具體測試程式碼如下:
save_pic(pFrame,AV_PIX_FMT_RGBA,AV_CODEC_ID_PNG,pImagePath,OUT_PNG_PIC_WIDTH,OUT_PNG_PIC_HEIGHT);
測試結果如下:

左邊是原始圖,右邊是生成的熱區圖