In trying to learn a little about MoviePy, I copied some sample code (which I modified slightly) that cuts a 10 second section out of a movie file, overlays text on it, and writes it as a different file. The code works perfectly...only for certain files. I have two video files that I wanted to use the code on (just for practice). Both are .mov files, both are on the same drive and both of the paths are correct (I have verified them multiple times). The problem is I'm getting a TypeError on one of the files while it works perfectly on the other. Here's the code:
from moviepy.editor import *
x = int(input("When do you want the cut to start? "))
y = int(input("When do you want the cut to end? "))
video = VideoFileClip("D:\Videos\Gatlinburgh Drone River 2.MOV").subclip(x,y)
##video = VideoFileClip("D:\SF_ep\T_R_D.mov").subclip(x,y) #Path is correct
txt_clip = ( TextClip("The Red Dot episode",fontsize=70,color='white')
.set_position('center')
.set_duration(10) )
result = CompositeVideoClip([video, txt_clip])
result.write_videofile("Text on Screen.webm",fps=25)
The above example works perfectly. However, when I comment it out and uncomment the video right below it, I get the following error:
Traceback (most recent call last):
File "C:\Users\Sam\Python Projects\MoviePy\Example3c.py", line 15, in <module>
video = VideoFileClip("D:\\Seinfeld_All_Episodes\\The_Red_Dot.mov").subclip(x,y)
File "C:\Python34\lib\site-packages\moviepy\video\io\VideoFileClip.py", line 82, in __init__
nbytes = audio_nbytes)
File "C:\Python34\lib\site-packages\moviepy\audio\io\AudioFileClip.py", line 63, in __init__
buffersize=buffersize)
File "C:\Python34\lib\site-packages\moviepy\audio\io\readers.py", line 70, in __init__
self.buffer_around(1)
File "C:\Python34\lib\site-packages\moviepy\audio\io\readers.py", line 234, in buffer_around
self.buffer = self.read_chunk(self.buffersize)
File "C:\Python34\lib\site-packages\moviepy\audio\io\readers.py", line 123, in read_chunk
self.nchannels))
TypeError: 'float' object cannot be interpreted as an integer
I'm not changing any code, I'm just pointing to a different file. I've tried the same with different files and gotten the same error. Why would it work on one and not the other? Any thoughts?
A similar question has been asked Stack Overflow before but there weren't any solid answers (at least none that applied to my particular situation).
Any help would be great. Thanks!
After searching around a bit more, I found a solution here. Line 122 of code in Readers.py was returning a float instead of an integer because it was using a single "/" instead of the double "//". I changed that line and it seems to have solved the problem. Details are at the link.
For the record, I still don't understand why it happened on certain files and not others. Nevertheless, the fix was simple.
Related
I'm trying to write a program that takes a bunch of videos from a folder, compiles them, and then takes another bunch of audio files from a folder and concatenates them to then overlay the combined audio on top of the final video (hope that makes sense). I'm able to process the videos into one final output video, but I keep running into trouble combining the audio. Below I've provided two small sections of code pertaining to audio comp, I'm using moviepy to process the videos and attempting to use it for audio as well.
songDirectory = './songs/'
songList = []
songs = []
audioclip=''
def makeCompilation():
for filename in os.listdir(songDirectory):
f = os.path.join(songDirectory, filename)
if os.path.isfile(f) and filename.endswith(".mp3"):
audioclip = moviepy.editor.AudioFileClip(f)
songList.append(filename)
for song in os.listdir(songDirectory):
c = os.path.join(songDirectory, song)
audio_clips = moviepy.editor.AudioFileClip(c)
audio_output = moviepy.editor.concatenate_audioclips(audio_clips)
finalClip = concatenate_videoclips(videos, method="compose")
final_duration = finalClip.duration
final_audio_output = audio_output.set_duration(final_duration)
final_output= finalClip.set_audio(final_audio_output).fx(afx.audio_fadein, 3.0)
audio_path = "./songs/tempaudiofile.m4a"
#print(description)
# Create compilation
final_output.write_videofile(outputFile, threads=8, temp_audiofile=audio_path, remove_temp=True, codec="libx264", audio_codec="aac")
return description
The program appeared to be able to find the audio directory, but I needed to be able to use os.path.join(songDirectory, filename) to point directly to each mp3 file so I messed around with it until I got the above code. And when I attempted to iterate through songList, I, as expected, got an error saying that 'str' wasn't iterable, and other errors saying that 'str' has no attribute 'duration'. Essentially, all I need it to do is iterate though the input folder and combine the files by whatever means. Code currently returns the output:
🌲Free Fredobagz x Aflacko x Flint type beat - 'Default_Dance' [prod. kah]-jro0v6ogZ0Y.mp4
225.05
Total Length: 225.05
225.05
Traceback (most recent call last):
File "/Users/daddyK/Desktop/comp_ bot/make_compilation3.py", line 127, in <module>
makeCompilation(path = "./videos/",
File "/Users/daddyK/Desktop/comp_ bot/make_compilation3.py", line 110, in makeCompilation
audio_output = moviepy.editor.concatenate_audioclips(audio_clips)
File "/Users/daddyK/Library/Python/3.10/lib/python/site-packages/moviepy/audio/AudioClip.py", line 315, in concatenate_audioclips
durations = [c.duration for c in clips]
TypeError: 'AudioFileClip' object is not iterable
At this point I'm a bit stumped, so if anybody could offer some insight as to what I should do to resolve the error and/or if I'm headed in the right direction code-wise I'd greatly appreciate it! Sorry if the code doesn't make any sense I'll post the whole .py file if needed
As per the comment by #kesh, you need to replace
songList.append(filename)
with
songList.append(audioclip)
I tried to run python Faster-RCNN based on tensorflow, which clone from https://github.com/smallcorgi/Faster-RCNN_TF
I built a dataset by myself and re-write data API to make dataset fit. The images in the dataset are all composed of meaningless background and text.
I got a .txt file to record the text location in a image, such as
ID_card/train/3.jpg 1 209 39 261 89
And my goal is to find text from a new image.
But when I run
python ./tools/train_net.py --device cpu --device_id 1 --solver VGG_CNN_M_1024 --weight ./data/pretrain_model/VGG_imagenet.npy --imdb ID_card_train --network IDcard_train
I got this KeyError: 'max_overlaps'
and here is the terminal record and error traceback.
Traceback (most recent call last):
File "./tools/train_net.py", line 97, in <module>
max_iters=args.max_iters)
File"/Users/jay_fu/tasks/catpatch/ClickCatpatch/tools/../lib/fast_rcnn/train.py", line 259, in train_net
roidb = filter_roidb(roidb)
File"/Users/jay_fu/tasks/catpatch/ClickCatpatch/tools/../lib/fast_rcnn/train.py", line 250, in filter_roidb
filtered_roidb = [entry for entry in roidb if is_valid(entry)]
File"/Users/jay_fu/tasks/catpatch/ClickCatpatch/tools/../lib/fast_rcnn/train.py", line 239, in is_valid
overlaps = entry['max_overlaps']
KeyError: 'max_overlaps'
I did googled and tried to delete /cache folder, and it didn't work. Next time i run the code the folder and .pkl file would be created again and then the same error came out.
some other answer said delete another folder lib/datasets/VOCdevkit-matlab-wrapper
however smallcorgi/Faster-RCNN_TF do not contain this folder, so i have no way to go.
I wonder what happened to my code and what would cause this error. I have no idea about what to do.
Anyone can give me some help, solution or whatever a piece of idea?
edit:
I run the demo on #VegardKT 's idea, the demo works good.
terminal shows succeed and figure 1-5 shows up.
I have tried several ways to load my .mat file into python. I eventually want the structure in the mat file to be a numpy array. I am not sure how best to post this question, because I think I might need to upload my .mat file, as it seems there is a problem with that since the steps I am trying seemed to work for everyone else.
First, I tried:
import scipy.io as sio
mat_contents = sio.loadmat('filename.mat')
Which gave the same error message (listed below) as when I installed hdf5storage and h5py. I have matlab version 9.3. and python 3.5.3.
This also gave the same error message as below:
import hdf5storage
mat = hdf5storage.loadmat('filename.mat')
The error from both those tries is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/u1/usr/.conda/envs/mypython/lib/python3.5/site-packages/hdf5storage/__init__.py", line 1801, in loadmat
**keywords)
File "/u1/usr/.conda/envs/mypython/lib/python3.5/site-packages/scipy/io/matlab/mio.py", line 135, in loadmat
MR = mat_reader_factory(file_name, appendmat, **kwargs)
File "/u1/usr/.conda/envs/mypython/lib/python3.5/site-packages/scipy/io/matlab/mio.py", line 59, in mat_reader_factory
mjv, mnv = get_matfile_version(byte_stream)
File "/u1/usr/.conda/envs/mypython/lib/python3.5/site-packages/scipy/io/matlab/miobase.py", line 235, in get_matfile_version
maj_ind = int(tst_str[2] == b'I'[0])
IndexError: index out of range
>>>
My .mat file contains a structure 1x1 which has several fields of different sizes. I am mostly a python person, and am only using matlab to output files which I intend to analyze in python.
#hpaulj thanks, your comment made me reload the file as I think it was somehow corrupted . I cannot trace what happened to it but the solution to this question was to check the file. The steps listed above in the question are correct. (I'm new to Stackoverflow and I'm pretty sure you cannot accept a comment as an answer so hopefully you will get credit here because I tagged your name?)
I'm currently working on building an experiment in PsychoPy (v1.82.01 stand-alone). I started on the project several months ago with an older version of PsychoPy.
It worked great and I ran some pilot subjects. We have since adjusted the stimuli sounds and it won’t run.
It looks like there is an issue with referencing the sound file, but I can’t figure out what’s going on.
I recreated the first part of the experiment with a single file rather than a loop so that it would be easier to debug. The sound file is referenced using:
study_sound = sound.Sound(u‘2001-1.ogg’, secs=-1)
When I run it, I get this output:
or see below
Running: /Users/dkbjornn/Desktop/Test/test.py
2016-04-29 14:05:43.164 python[65267:66229207] ApplePersistenceIgnoreState: Existing state will not be touched. New state will be written to /var/folders/9f/3kr6zwgd7rz95bcsfw41ynw40000gp/T/org.psychopy.PsychoPy2.savedState
0.3022 WARNING Movie2 stim could not be imported and won't be available
sndinfo: failed to open the file.
Traceback (most recent call last):
File "/Users/dkbjornn/Desktop/Test/test.py", line 84, in <module>
study_sound = sound.Sound(u'2001-1.ogg', secs=-1)
File "/Applications/PsychoPy2.app/Contents/Resources/lib/python2.7/psychopy/sound.py", line 380, in __init__
self.setSound(value=value, secs=secs, octave=octave, hamming=hamming)
File "/Applications/PsychoPy2.app/Contents/Resources/lib/python2.7/psychopy/sound.py", line 148, in setSound
self._setSndFromFile(value)
File "/Applications/PsychoPy2.app/Contents/Resources/lib/python2.7/psychopy/sound.py", line 472, in _setSndFromFile
start=self.startTime, stop=self.stopTime)
File "/Applications/PsychoPy2.app/Contents/Resources/lib/python2.7/pyolib/tables.py", line 1420, in setSound
saved data to u'/Users/dkbjornn/Desktop/Test/data/99_test_2016_Apr_29_1405_1.csv'
_size, _dur, _snd_sr, _snd_chnls, _format, _type = sndinfo(path)
TypeError: 'NoneType' object is not iterable
The important thing here is the sndinfo: failed to open the file. message. Most likely, it cannot find your file on the disk. Check the following:
Is the file 2001-1.ogg in the same folder as your experiment? Not in a subfolder? Or have you accidentially changed your path, e.g. using os.chdir?
Is it actually called 2001-1.ogg? Any differences in uppercase/lowercase, spaces, etc. all count.
Alternatively, there's something in the particular way the .ogg was saved that causes the problem, even though the Sound class can read a large set of different sound codecs. Try exporting the sound file in other formats, e.g. .mp3 or .wav.
I am working with mulipulse lidar data that collects points along a number of lines within the flight path. I am trying to determine the name and number of individual lines within the las file. I am using liblas module in python.
I found this documentation that explains the different fields stored in an las file. It mentions a data field (get_data and set_data) at the very bottom of the page.
The 'point data format' and 'point data record length' in the header set aside space for this 'data' field. My header says I have 28 bytes set aside for the data field, and there are 28 values stored in the data field. The 19th value (at least in two datasets from two different sensors) refers to the line number. I have a single value in single pulse data and 4 in multi-pulse data.
I was wondering if there is a standard for what is stored in this field or if it is proprietary.
Also, as a way to get the name of each scan line, I wrote the following code:
import liblas
from liblas import file as lasfile
# Get parameters
las_file = r"E:\Testing\00101.las"
f = lasfile.File(las_file, mode='r')
line_list = []
counter = 0
for p in f:
line_num = p.data[18]
if line_num not in line_list:
line_list.append(line_num)
counter += 1
print line_list
It results with the following error:
Traceback (most recent call last):
File "D:\Tools\Python_Scripts\point_info.py", line 46, in <module>
line_num = p.data[18]
File "C:\Python27\ArcGIS10.1\lib\site-packages\liblas\point.py", line 560, in get_data
length = self.header.data_record_length
File "C:\Python27\ArcGIS10.1\lib\site-packages\liblas\point.py", line 546, in get_header
return header.Header(handle=core.las.LASPoint_GetHeader(self.handle))
WindowsError: [Error -529697949] Windows Error 0xE06D7363
Does anyone know more about the line numbers stored in the las point/header? Can anyone explain the error? It seems to allocate nearly 2gb of ram before I get the error. I am on win xp, so I'm guessing its a memory error, but I don't understand why accessing this 'data' field hogs memory. Any help is greatly appreciated.
I don't pretend to be an expert in any of this, but I'm intrigued by GIS data so this caught my interest. I installed liblas and its dependencies on my Fedora 19 system and played with the example data files that came with liblas.
Using your code I ran into the same problem of watching all my memory get eaten up. I don't know why that should happen - perhaps unwanted references hanging around preventing the garbage collector from working as we'd hope. This could probably be fixed, but I won't try it.
I did notice some interesting features of the liblas module and decided to try them. I believe you can get the data you seek.
After opening your file, have a look at the XML description from the header.
h = f.get_header()
print(h.get_xml())
It's hard to look at (feel free to play with xml.dom.minidom or lxml.etree), but in my example files it showed the byte layout of the point data (mine had 28 bytes too). In mine, offset 18 was a single short (2 bytes) assigned to Point Source ID. You should be able to retrieve this with p.data[18:19], p.get_data()[18:19], p.point_source_id, or p.get_point_source_id(). Unfortunately the data references chew up memory and p.point_source_id has a bug (bug fix pull request submitted to developers). If we change your code to use the last access method, everything seems to work fine. So, try this in your for loop instead:
for p in f:
line_num = p.get_point_source_id()
if line_num not in line_list:
line_list.append(line_num)
counter += 1
Note that
counter == h.get_count()
If you just want the set of unique Point Source ID values ...
line_set = set(p.get_point_source_id() for p in f)
Hopefully your data value is also available as p.get_point_source_id(). Let me know how it works for you in the comments. Cheers!