ffplay 读取单通道的灰度图片时会将其扩充为 AV_PIX_FMT_RGB0
,upload_texture() 函数中对应的 SDL 格式为 SDL_PIXELFORMAT_BGR888
,因此可以正常播放。
经过神经网络算法处理后得到单通道灰度帧数据,ffplay 中的 upload_texture() 函数进行处理时,AV_PIX_FMT_GRAY8
对应的 SDL 格式为 SDL_PIXELFORMAT_UNKNOWN
,视频播放会中断。因此需要把灰度帧使用 sws_scale() 函数进行转化。
/* frame -> frameRGB */
/* frameRGB -> torch::Tensor */
/* torch::Tensor -> frameGRAY */
/* frameGRAY -> frame */
torch::Tensor frameGRAY = out;
int frameGRAY_width = frameRGB->width;
int frameGRAY_height = frameRGB->height;
*img_convert_ctx = sws_getCachedContext(*img_convert_ctx,
frameGRAY_width, frameGRAY_height, AV_PIX_FMT_GRAY8,
frame->width, frame->height, frame->format,
sws_flags, NULL, NULL, NULL);
if (*img_convert_ctx != NULL) {
uint8_t *pixels[4], *frameGRAY_data[8];
int pitch[4], frameGARY_linesize[8];
frameGRAY_data[0] = out.data_ptr();
frameGARY_linesize[0] = frameGRAY_width;
if (!SDL_LockTexture(*tex, NULL, (void **)pixels, pitch)) {
sws_scale(*img_convert_ctx, (const uint8_t * const *)frameGRAY_data, frameGARY_linesize,
0, frameGRAY_height, frame->data, frame->linesize);
SDL_UnlockTexture(*tex);
}
} else {
av_log(NULL, AV_LOG_FATAL, "Cannot initialize the conversion context\n");
ret = -1;
}