ffmpeg rotation video-processing

Rotación de videos con FFmpeg



rotation video-processing (10)

¿Has probado la transpose todavía? Me gusta (de la otra respuesta)

ffmpeg -i input -vf transpose=2 output

Si está utilizando una versión anterior, debe actualizar ffmpeg si desea usar la función de transposición, como se agregó en octubre de 2011.

La página de download FFmpeg ofrece compilaciones estáticas que puede ejecutar directamente sin tener que compilarlas.

He estado tratando de averiguar cómo rotar videos con FFmpeg. Estoy trabajando con videos de iPhone tomados en modo retrato. Sé cómo determinar los grados actuales de rotación usando MediaInfo (excelente biblioteca, por cierto) pero ahora estoy atascado en FFmpeg.

Por lo que he leído, lo que necesitas usar es una opción vfilter . Según lo que veo, debería verse así:

ffmpeg -vfilters "rotate=90" -i input.mp4 output.mp4

Sin embargo, no puedo hacer que esto funcione. Primero, -vfilters ya no existe, ahora es solo -vf . Segundo, me sale este error:

No such filter: ''rotate'' Error opening filters!

Que yo sepa, tengo una compilación de todas las opciones de FFmpeg. Ejecutar ffmpeg -filters muestra esto:

Filters: anull Pass the source unchanged to the output. aspect Set the frame aspect ratio. crop Crop the input video to x:y:width:height. fifo Buffer input images and send them when they are requested. format Convert the input video to one of the specified pixel formats. hflip Horizontally flip the input video. noformat Force libavfilter not to use any of the specified pixel formats for the input to the next filter. null Pass the source unchanged to the output. pad Pad input image to width:height[:x:y[:color]] (default x and y: 0, default color: black). pixdesctest Test pixel format definitions. pixelaspect Set the pixel aspect ratio. scale Scale the input video to width:height size and/or convert the i mage format. slicify Pass the images of input video on to next video filter as multi ple slices. unsharp Sharpen or blur the input video. vflip Flip the input video vertically. buffer Buffer video frames, and make them accessible to the filterchai n. color Provide an uniformly colored input, syntax is: [color[:size[:ra te]]] nullsrc Null video source, never return images. nullsink Do absolutely nothing with the input video.

Tener las opciones para vflip y hflip es genial y todo, pero simplemente no me llevarán a donde necesito ir. Necesito la habilidad de rotar videos 90 grados como mínimo. 270 grados sería una excelente opción para tener también. ¿Dónde han ido las opciones de rotación?


Desafortunadamente, la versión de Ubuntu de ffmpeg soporta videofiltros.

Necesitas usar avidemux o algún otro editor para lograr el mismo efecto.

En la forma programática, mencoder ha sido recomendado.


Esta secuencia de comandos que generará los archivos con la estructura de directorios en "fixedFiles". En este momento está fijado en archivos MOV y ejecutará varias transformaciones según la "rotación" original del video. Funciona con videos capturados en iOS en una Mac que ejecuta Mavericks, pero debe ser fácilmente exportable. Se basa en haber instalado tanto exiftool como ffmpeg .

#!/bin/bash # rotation of 90 degrees. Will have to concatenate. #ffmpeg -i <originalfile> -metadata:s:v:0 rotate=0 -vf "transpose=1" <destinationfile> #/VLC -I dummy -vvv <originalfile> --sout=''#transcode{width=1280,vcodec=mp4v,vb=16384,vfilter={canvas{width=1280,height=1280}:rotate{angle=-90}}}:std{access=file,mux=mp4,dst=<outputfile>}/' vlc://quit #Allowing blanks in file names SAVEIFS=$IFS IFS=$(echo -en "/n/b") #Bit Rate BR=16384 #where to store fixed files FIXED_FILES_DIR="fixedFiles" #rm -rf $FIXED_FILES_DIR mkdir $FIXED_FILES_DIR # VLC VLC_START="/Applications/VLC.app/Contents/MacOS/VLC -I dummy -vvv" VLC_END="vlc://quit" ############################################# # Processing of MOV in the wrong orientation for f in `find . -regex ''/./.*/.MOV''` do ROTATION=`exiftool "$f" |grep Rotation|cut -c 35-38` SHORT_DIMENSION=`exiftool "$f" |grep "Image Size"|cut -c 39-43|sed ''s/x//''` BITRATE_INT=`exiftool "$f" |grep "Avg Bitrate"|cut -c 35-38|sed ''s//..*//''` echo Short dimension [$SHORT_DIMENSION] $BITRATE_INT if test "$ROTATION" != ""; then DEST=$(dirname ${f}) echo "Processing $f with rotation $ROTATION in directory $DEST" mkdir -p $FIXED_FILES_DIR/"$DEST" if test "$ROTATION" == "0"; then cp "$f" "$FIXED_FILES_DIR/$f" elif test "$ROTATION" == "180"; then # $(eval $VLC_START /"$f/" "--sout="/'"#transcode{vfilter={rotate{angle=-"$ROTATION"}},vcodec=mp4v,vb=$BR}:std{access=file,mux=mp4,dst=/""$FIXED_FILES_DIR/$f"/"}''" $VLC_END ) $(eval ffmpeg -i /"$f/" -vf hflip,vflip -r 30 -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy /"$FIXED_FILES_DIR/$f/") elif test "$ROTATION" == "270"; then $(eval ffmpeg -i /"$f/" -vf "scale=$SHORT_DIMENSION:-1,transpose=2,pad=$SHORT_DIMENSION:$SHORT_DIMENSION:/(ow-iw/)/2:0" -r 30 -s "$SHORT_DIMENSION"x"$SHORT_DIMENSION" -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy /"$FIXED_FILES_DIR/$f/" ) else # $(eval $VLC_START /"$f/" "--sout="/'"#transcode{scale=1,width=$SHORT_DIMENSION,vcodec=mp4v,vb=$BR,vfilter={canvas{width=$SHORT_DIMENSION,height=$SHORT_DIMENSION}:rotate{angle=-"$ROTATION"}}}:std{access=file,mux=mp4,dst=/""$FIXED_FILES_DIR/$f"/"}''" $VLC_END ) echo ffmpeg -i /"$f/" -vf "scale=$SHORT_DIMENSION:-1,transpose=1,pad=$SHORT_DIMENSION:$SHORT_DIMENSION:/(ow-iw/)/2:0" -r 30 -s "$SHORT_DIMENSION"x"$SHORT_DIMENSION" -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy /"$FIXED_FILES_DIR/$f/" $(eval ffmpeg -i /"$f/" -vf "scale=$SHORT_DIMENSION:-1,transpose=1,pad=$SHORT_DIMENSION:$SHORT_DIMENSION:/(ow-iw/)/2:0" -r 30 -s "$SHORT_DIMENSION"x"$SHORT_DIMENSION" -metadata:s:v:0 rotate=0 -b:v "$BITRATE_INT"M -vcodec libx264 -acodec copy /"$FIXED_FILES_DIR/$f/" ) fi fi echo echo ================================================================== sleep 1 done ############################################# # Processing of AVI files for my Panasonic TV # Use ffmpegX + QuickBatch. Bitrate at 16384. Camera res 640x424 for f in `find . -regex ''/./.*/.AVI''` do DEST=$(dirname ${f}) DEST_FILE=`echo "$f" | sed ''s/.AVI/.MOV/''` mkdir -p $FIXED_FILES_DIR/"$DEST" echo "Processing $f in directory $DEST" $(eval ffmpeg -i /"$f/" -r 20 -acodec libvo_aacenc -b:a 128k -vcodec mpeg4 -b:v 8M -flags +aic+mv4 /"$FIXED_FILES_DIR/$DEST_FILE/" ) echo echo ================================================================== done IFS=$SAVEIFS


Gire 90 en el sentido de las agujas del reloj:

ffmpeg -i in.mov -vf "transpose=1" out.mov

Para el parámetro de transposición puede pasar:

0 = 90CounterCLockwise and Vertical Flip (default) 1 = 90Clockwise 2 = 90CounterClockwise 3 = 90Clockwise and Vertical Flip

Use -vf "transpose=2,transpose=2" para 180 grados.

Asegúrese de usar una versión reciente de ffmpeg desde aquí (una compilación estática funcionará bien).

Tenga en cuenta que esto volverá a codificar las partes de audio y video. Por lo general, puede copiar el audio sin tocarlo, utilizando -c:a copy . Para cambiar la calidad del video, configure la tasa de bits (por ejemplo, con -b:v 1M ) o consulte la guía de codificación H.264 si desea las opciones de VBR.

Una solución también es utilizar este script de conveniencia .


La respuesta de Alexy casi funcionó para mí, excepto que estaba recibiendo este error:

La base de tiempo 1/90000 no es compatible con el estándar MPEG 4, el valor máximo admitido para el denominador de base de tiempo es 65535

Solo tuve que agregar un parámetro (-r 65535/2733) al comando y funcionó. El comando completo fue así:

ffmpeg -i in.mp4 -vf "transpose=1" -r 65535/2733 out.mp4


Me encontré con esta página mientras buscaba la misma respuesta. Ya han pasado seis meses desde que se solicitó originalmente y las compilaciones se han actualizado muchas veces desde entonces. Sin embargo, quería agregar una respuesta para cualquier otra persona que se encuentre aquí en busca de esta información.

Estoy usando la versión Debian Squeeze y FFmpeg de esos repositorios.

La página MAN para ffmpeg establece el siguiente uso

ffmpeg -i inputfile.mpg -vf "transpose=1" outputfile.mpg

La clave es que no debe usar una variable de grado, sino una variable de configuración predefinida de la página MAN.

0=90CounterCLockwise and Vertical Flip (default) 1=90Clockwise 2=90CounterClockwise 3=90Clockwise and Vertical Flip


Para rotar la imagen en el sentido de las agujas del reloj, puede usar el filtro de rotación, que indica un ángulo positivo en radianes. Con 90 grados equivalentes a PI / 2, puedes hacerlo así:

ffmpeg -i in.mp4 -vf "rotate=PI/2" out.mp4

para sentido contrario a las agujas del reloj el ángulo debe ser negativo

ffmpeg -i in.mp4 -vf "rotate=-PI/2" out.mp4

El filtro de transposición funcionará igualmente bien a 90 grados, pero para otros ángulos, esta es una opción más rápida o única.


Si no desea volver a codificar su video Y su reproductor puede manejar metadatos de rotación, simplemente puede cambiar la rotación en los metadatos usando ffmpeg:

ffmpeg -i input.m4v -metadata:s:v rotate="90" -codec copy output.m4v


Si obtiene un error "El códec es experimental, pero los códecs experimentales no están habilitados", use este error:

ffmpeg -i inputFile -vf "transpose=1" -c:a copy outputFile

Pasó conmigo para un archivo .mov con audio aac.


ffmpeg -vfilters "rotate=90" -i input.mp4 output.mp4

no funcionará, incluso con la última fuente ...

debe cambiar el orden:

ffmpeg -i input.mp4 -vf vflip output.mp4

funciona bien