How does FFMPEG working here?
import sys, os, pdb
import numpy as np
import subprocess
from tqdm import tqdm
def extract(vid_dir, frame_dir, start, end, redo=False):
class_list = sorted(os.listdir(vid_dir))[start:end]
print("Classes =", class_list)
for ic,cls in enumerate(class_list):
vlist = sorted(os.listdir(vid_dir + cls))
print("")
print(ic+1, len(class_list), cls, len(vlist))
print("")
for v in tqdm(vlist):
outdir = os.path.join(frame_dir, cls, v[:-4])
# Checking if frames already extracted
if os.path.isfile( os.path.join(outdir, 'done') ) and not redo: continue
try:
os.system('mkdir -p "%s"'%(outdir))
# check if horizontal or vertical scaling factor
o = subprocess.check_output('ffprobe -v error -show_entries stream=width,height -of default=noprint_wrappers=1 "%s"'%(os.path.join(vid_dir, cls, v)), shell=True).decode('utf-8')
lines = o.splitlines()
width = int(lines[0].split('=')[1])
height = int(lines[1].split('=')[1])
resize_str = '-1:256' if width>height else '256:-1'
# extract frames
os.system('ffmpeg -i "%s" -r 25 -q:v 2 -vf "scale=%s" "%s" > /dev/null 2>&1'%( os.path.join(vid_dir, cls, v), resize_str, os.path.join(outdir, '%05d.jpg')))
nframes = len([ fname for fname in os.listdir(outdir) if fname.endswith('.jpg') and len(fname)==9])
if nframes==0: raise Exception
os.system('touch "%s"'%(os.path.join(outdir, 'done') ))
except:
print("ERROR", cls, v)
if __name__ == '__main__':
vid_dir = sys.argv[1]
frame_dir = sys.argv[2]
start = int(sys.argv[3])
end = int(sys.argv[4])
extract(vid_dir, frame_dir, start, end, redo=True)
os.system('ffmpeg -i "%s" -r 25 -q:v 2 -vf "scale=%s" "%s" > /dev/null 2>&1'%( os.path.join(vid_dir, cls, v), resize_str, os.path.join(outdir, '%05d.jpg')))
-i --> Input_file (320x240)
-r --> frame rate (it will extract 25 frame of every video)
-q --> what does this mean?
"scale=%s --> Unable to understand this? how does this work for -1:256 ratio [will it resize the video to 256x256 dimension]?
Can anyone explain me this?
Related
This is my final.py file.
#!/usr/bin/python
import sys
import os
sys.path.insert(0, './src/')
import lexRule
import parser
import ply.lex as lex
import ply.yacc as yacc
import node_file
import genAssembly as ga
import getopt
import pydot
def main(argv):
to_parse = ''
try:
opts, args = getopt.getopt(argv,"o:f:h",["opt=","file=","help"])
except getopt.GetoptError:
print 'Usage : ./bin/final.py [options][-f/-h/-o] [string]'
sys.exit(2)
parse = parser.Parser()
optjump = 0
for opt, arg in opts:
if opt in ("-o", "--opt"):
if arg == "1":
optjump = 1
elif opt in ("-f", "--file"):
tree = parse.parse_file(file(arg))
t = parser.tac.code
q = []
if optjump == 1:
for x in range(0,len(t)-1):
if t[x][0] == "goto" and t[x+1][3] == t[x][3]:
q.append(x)
for qw in reversed(q):
del t[qw]
parser.tac.code = t
old_target = sys.stdout
ga.generate()
sys.stdout = open('output.s', 'w')
ga.generate()
sys.stdout = old_target
print("Run ./a.out for execution")
# os.system("nasm -f elf32 inout.s")
# os.system("nasm -f elf32 fileio.s")
os.system("nasm -f elf32 output.s")
# os.system("nasm -f elf32 val1.s")
# os.system("nasm -f elf32 next1.s")
# os.system("nasm -f elf32 append2.s")
os.system("gcc -m32 output.o ./bin/inout.o ./bin/fileio.o ./bin/val1.o ./bin/next1.o ./bin/append2.o")
elif opt in ("-h", "--help"):
_file = open("./README.txt")
content = _file.read()
print(content)
else:
print 'Usage : ./bin/final.py [options][-f/-h/-o] [string]'
sys.exit(2)
if not opts:
print 'Usage : ./bin/final.py [options][-f/-h/-o] [string]'
sys.exit(2)
if __name__ == "__main__":
main(sys.argv[1:])
when i ran it on cmd this is the error i got.error
I am using python2 and running these commands:
python bin/final.py -f test/ackermann.java
python bin/final.py -o 1 -f test/ackermann.java
the project i am trying to run is :https://github.com/abhigarg-iitk/java_compiler
Since you are using your own parser module (named the same as the standard library) located in another location than the standard library packages you need to import it using the from ... import ... syntax and an __init.py__ file in your parser package directory.
For further reading you can have a look at the python documentation at https://docs.python.org/3/reference/import.html
I created a script to download a youtube video and extract an images from it for each period
screenshotvideo
def screenshotvideo(url, interval, id, fullduration, title, quality):
interval = int(interval)
parsed_t = isodate.parse_duration(fullduration)
durationseconds=parsed_t.total_seconds()
iterat=int(durationseconds/int(interval))
for i in range(0, iterat):
print(str(id))
print(str(i))
print(str(i*interval))
part(url, time.strftime('%H:%M:%S', time.gmtime(int(i*interval))), "00:00:01", title+"-"+str(id), quality)
part
def part(url, starttime, duration, name, quality):
f = os.popen("ffmpeg $(youtube-dl -f "+quality+" -g '"+url+"' | sed 's/.*/-ss "+starttime+" -i &/') -t "+duration+" -c copy "+name+".mp4")
now = f.read()
print(now)
f = os.popen("ffmpeg -i "+name+".mp4 -ss 00:00:00 -vframes 1 "+name+".jpg")
now = f.read()
print(now)
f = os.popen("rm -rf "+name+".mp4")
now = f.read()
print(now)
so i got the folowing error in the first ffmpeg command
[mp4 # 0x55d537f64240] Could not find tag for codec vp8 in stream #0, codec not currently supported in container.
Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument
The error is pretty clear:
codec not currently supported in container.
Use a different container that supports vp8, like webm or mkv.
The answer is close to szatmary answer but i need to download video in mp4 format, so all i neet to do is to edit the first command
ffmpeg $(youtube-dl -f "+quality+" -g '"+url+"' | sed 's/.*/-ss "+starttime+" -i &/') -t "+duration+" -c:v libx264 "+name+".mp4
after that i got other error for the images file name that i want to saved each time from the video.
So this is the final solution i found:
def screenshotvideo(url, interval, id, fullduration, title, quality):
interval = int(interval)
parsed_t = isodate.parse_duration(fullduration)
durationseconds=parsed_t.total_seconds()
iterat=int(durationseconds/int(interval))
for i in range(0, iterat):
print(str(id))
print(str(i))
print(str(i*interval))
part(url, time.strftime('%H:%M:%S', time.gmtime(int(i*interval))), "00:00:01", title+"-"+str(id), quality, i)
def part(url, starttime, duration, name, quality, i):
f = os.popen("ffmpeg $(youtube-dl -f "+quality+" -g '"+url+"' | sed 's/.*/-ss "+starttime+" -i &/') -t "+duration+" -c:v libx264 "+name+".mp4")
now = f.read()
print(now)
f = os.popen("ffmpeg -i "+name+".mp4 -ss 00:00:00 -vframes 1 "+name+"_"+str(i)+".jpg")
now = f.read()
print(now)
f = os.popen("rm -rf "+name+".mp4")
now = f.read()
print(now)
It could be I'm completely misunderstanding the getopt module
I am trying to parse [--magic-m] to my program, but it does not set the correct field.
Part of Encrypt Function
def encrypt(filename, text, magic):
if not magic is None:
hash = pbkdf2_sha256.encrypt(magic, rounds=10000, salt_size=16)
print pbkdf2_sha256.verify(magic, hash)
try:
d = load_image( filename )
except Exception,e:
print str(e)
Part of Load function
def load_image( filename ) :
img = Image.open( os.path.join(__location__, filename) )
img.load()
data = np.asarray( img, dtype="int32" )
return data
Main
if __name__ == "__main__":
if not len(sys.argv[1:]):
usage()
try:
opts,args = getopt.getopt(sys.argv[1:],"hedm:",["help", "encrypt", "decrypt", "magic="])
except getopt.GetoptError as err:
print str(err)
usage()
magic = None
for o,a in opts:
if o in ("-h","--help"):
usage()
elif o in ("-e","--encrypt"):
to_encrypt = True
elif o in ("-d","--decrypt"):
to_encrypt = False
elif o in ("-m", "--magic"):
magic = a
else:
assert False,"Unhandled Option"
print magic
if not to_encrypt:
filename = sys.argv[2]
decrypt(filename, magic)
else:
filename = sys.argv[2]
text = sys.argv[3]
encrypt(filename, text, magic)
I tried calling the program above like this:
[1] python stego.py -e test.jpeg lol -m h
or like this:
[2] python stego.py -e -m h test.jpeg lol
Output becomes:
[1] None
[2] lol
[2] True
[2] [Errno 2] No such file or directory: 'C:\\Users\\Educontract\\Steganography\\-m'
Whitout the option -m everything works fine
The colon should come after m to indicate that it requires an argument. You should also include an equals sign after the long option magic to indicate that it requires an argument.
getopt.getopt(sys.argv[1:],"hedm:",["help", "encrypt", "decrypt", "magic="])
You should put all your options before the arguments, as in your second example.
python stego.py -e -m h test.jpeg lol
If you print sys.argv, I think you'll find that sys.argv[2] and sys.argv[3] are not what you expect. I would fetch the arguments from args, rather than sys.argv.
filename = args[0]
text = args[1]
Note that you may find it easier to use the argparse library instead of getopt. It isn't as strict about requiring options before arguments.
I'm trying to run a python script that is optimized to work with python 2.7:
#!/usr/bin/env python
import sys,getopt,os
SplitInput_string = """#!/bin/bash
#BSUB -J SplitInput[1-%numSamples%]
#BSUB -o Logs/SplitInput-Out-%I.out
#BSUB -e Logs/SplitInput-Err-%I.err
#BSUB -q week
#BSUB -W 23:58
echo Date: `date`
t1=`date +%s`
sleep ${LSB_JOBINDEX}
python LSFScripts/array_merge.py -r ${LSB_JOBINDEX} -i %input% -o original_reads/
[ $? -eq 0 ] || echo 'JOB FAILURE: $?'
echo Date: `date`
t2=`date +%s`
tdiff=`echo 'scale=3;('$t2'-'$t1')/3600' | bc`
echo 'Total time: '$tdiff' hours'
"""
help_message = "usage example: python setupDirs.py -i /path/to/reads/ -n numberOfSamples"
if __name__ == "__main__":
try:
opts, args = getopt.getopt(sys.argv[1:], 'hi:n:', ["inputdir="])
except:
print help_message
sys.exit(2)
for opt, arg in opts:
if opt in ('-h', '--help'):
print help_message
sys.exit()
elif opt in ('-i', '--inputdir'):
inputdir = arg
if inputdir[-1] != '/':
inputdir += '/'
elif opt in ('-n'):
n = arg
for dir in ['Logs', 'original_reads', 'hashed_reads', 'cluster_vectors', 'read_partitions']:
os.system('mkdir %s' % (dir))
f = open('LSFScripts/SplitInput_ArrayJob.q', 'w')
f.write(SplitInput_string.replace('%numSamples%', n).replace('%input%', inputdir))
f.close()
But I keep getting this error message:
line 42, in <module>
f.write(SplitInput_string.replace('%numSamples%', n).replace('%input%', inputdir))
NameError: name 'n' is not defined
Any advice would be appreciated!
You must assign a value to n before entering the loop.
if __name__ == "__main__":
try:
opts, args = getopt.getopt(sys.argv[1:],'hi:n:',["inputdir="])
except:
print help_message
sys.exit(2)
n = ""
for opt, arg in opts:
etc...
n is not defined in all code paths. It is only defined if you follow the path:
elif opt in ('-n'):
Define m at a higher scope (i.e. before the for loop) with a default value if you want to use it afterwards.
n = #default value
for opt, arg in opts:
# ...
If you want to parse arguments, I highly recommend using the argparse package. There is a little bit of a learning curve, but you can very robustly generate the necessary usage.
I record a video with no sound. I save a snapshots and then I compile them to .avi with 25FPS. Now I want to record audio (instead time.sleep(0.04) between following snapshots I will record audio in this time) and compile it wits video. Now I have avi file, and wave file, and I find a solution to mix them.
Python, Win32
It is my "video recorder" which use 'mencoder':
import os
import re
from VideoCapture import *
import time
def makeVideo(device, ftime):
folder = 'foto/forVideo/'
mencoder = "C:\mencoder.exe"
for i in range(ftime * 25) :
FN = "foto\\forVideo\\ola-%(#)04d.jpg" % {"#" : i}
device.saveSnapshot(FN, quality=100, timestamp=0, boldfont=0)
time.sleep(0.04)
# Set up regular expressions for later
RE = re.compile('.*-(\d*)\.jpg')
fbRE = re.compile('(.*)-.*\.jpg')
# How many frames to use per movie
framestep = 2000
print '\n\n\tlisting contents of %s . . .'%folder
files = os.listdir(folder)
print '%s files found.\n\n' % len(files)
# If a file is called "asdf-003.jpg", the basename will be 'asdf'.
basenames = [fbRE.match(i).groups()[0] for i in files if fbRE.match(i)]
# Get the set of unique basenames. In the
basenames = list(set(basenames))
print '\t***There are %s different runs here.***' % len(basenames)
# This loop will only execute once if there was only a single experiment
# in the folder.
for j,bn in enumerate(basenames):
these_files = [i for i in files if bn in i]
# Sort using the "decorate-sort-undecorate" approach
these_sorted_files = [(int(RE.match(i).groups()[0]),i) for i in these_files if RE.match(i)]
these_sorted_files.sort()
these_sorted_files = [i[1] for i in these_sorted_files]
# these_sorted_files is now a list of the filenames a_001.jpg, a_002.jpg, etc.
for k in range(0, len(these_sorted_files), framestep):
frame1 = k
frame2 = k+framestep
this_output_name = 'C:\_%s_%s_%s-%s.avi' % (bn,j,frame1,frame2)
print '\n\n\toutput will be %s.' % this_output_name
f = open('temp.txt','w')
filenames = [os.path.join(folder,i)+'\n' \
for i in these_sorted_files[frame1:frame2]]
f.writelines(filenames)
f.close()
# Finally! Now execute the command to create the video.
cmd = '%s "mf://#temp.txt" -mf fps=25 -o %s -ovc lavc\
-lavcopts vcodec=mpeg4' % (mencoder,this_output_name)
os.system(cmd)
print '\n\nDONE with %s' % this_output_name
print 'Done with all marked folders.'
I think the best bet would be to use an external program to mux them. ffmpeg is a perennial favorite -- quality Windows builds are available at http://ffmpeg.arrozcru.org/autobuilds/ . With ffmpeg, just do ffmpeg -i your_video_file.avi -i your_audio_file.wav -vcodec copy -acodec copy muxed_file.avi and you're done.