文章目录
##视频帧缩放裁剪-ffmpeg
应用场景:对视频进行无变形缩放选定要裁剪的坐标点、对应的宽高进行裁
裁剪对应方法:
///yuv 截取
AVFrame* scaleYUVbufferprocess(int start_x,int start_y,int dst_w,int dst_h,AVFrame *temp) {
AVFrame *dst = NULL;
dst = av_frame_alloc();
dst->format = AV_PIX_FMT_YUV420P;
dst->width = dst_w;
dst->height = dst_h;
av_frame_get_buffer(dst, 0);
//Y
for(int i = 0; i < dst_h;i++){
int m = (start_y + i) * temp->linesize[0] + start_x;
int n = i * dst->linesize[0];
for(int j = 0; j < dst_w; j++){
dst->data[0][n + j] = temp->data[0][m + j ];
}
}
//U
for(int i = 0; i < dst_h/2;i++){
int m = (start_y/2 + i) * temp->linesize[1] + start_x/2;
int n = i * dst->linesize[1];
for(int j = 0; j < dst_w/2; j++){
dst->data[1][n + j] = temp->data[1][m + j ];
}
}
for(int i = 0; i < dst_h/2;i++){
int m = (start_y/2 + i) * temp->linesize[2] + start_x/2;
int n = i * dst->linesize[2];
for(int j = 0; j < dst_w/2; j++){
dst->data[2][n + j] = temp->data[2][m + j ];
}
}
return dst;
}
进行正交缩放(防止变形)再裁剪调用案例,可以用场景,移动端进行图片缩放裁剪编码成视频:
AVFrame* scaleAVFrameClipping(AVFrame *src,int dst_w,int dst_h){
SwsContext *sws = NULL;
int temp_w = src->width;
int temp_h = src->height;
float src_ratio = ((float)src->width)/src->height;
float dst_ratio = ((float)dst_w)/dst_h;
int start_x = 0;
int start_y = 0;
if(src_ratio > dst_ratio){
temp_h = dst_h;
temp_w = ((float)dst_h)/src->height * src->width;
start_x = (temp_w - dst_w + 1)/2;
}
else if(src_ratio < dst_ratio){
temp_w = dst_w;
temp_h = ((float)dst_w)/src->width * src->height;
start_y = (temp_h - dst_h + 1)/2;
}else{
temp_w = dst_w;
temp_h = dst_h;
}
if(start_x % 2 == 1){
start_x -= 1;
}
if(start_y %2 == 1){
start_y -= 1;
}
printf("---temp w %d,h %d,start_x %d,y %d \n",temp_w,temp_h,start_x,start_y);
AVFrame *temp;
temp = av_frame_alloc();
temp->format = AV_PIX_FMT_YUV420P;
temp->width = temp_w;
temp->height = temp_h;
av_frame_get_buffer(temp,0);
sws = sws_getContext(src->width, src->height, static_cast<AVPixelFormat>(src->format), temp_w, temp_h, AV_PIX_FMT_YUV420P, 2, NULL, NULL, NULL);
sws_scale(sws,src->data,src->linesize,0,src->height,temp->data,temp->linesize);
AVFrame *dst = scaleYUVbufferprocess(start_x,start_y,dst_w,dst_h,temp);
dst->pts = src->pts;
av_frame_free(&temp);
if(sws != NULL) {
sws_freeContext(sws);
}
return dst;
}