How to take multiple VLC snapshot into specific folder - python

This code is working well, but it keep replacing the previous snapshot in the location I dont want.
How can I keep taking the snapshot every second without replacing the previous shot, and how can I specify the folder for these png going to be saved?
player=vlc.MediaPlayer('rtsp://admin:888999#thesport.fujiko.biz:554/unicast/c3/s0/live')
player.play()
while 1:
time.sleep(1)
player.video_take_snapshot(0, '.snapshot.tmp.png', 0, 0)

It's easy, every time you get a frame, store it in different variable, like this

As the one comment says, you need to change the filename for each subsequent save. I would create a count in your loop and then format the value to the string that is the filename. For example:
player=vlc.MediaPlayer('rtsp://admin:888999#thesport.fujiko.biz:554/unicast/c3/s0/live')
player.play()
i = 0
while 1:
time.sleep(1)
player.video_take_snapshot(0, '.snapshot_{}.tmp.png'.format(i), 0, 0)
i += 1

If you simply specify a directory name, rather than a filename, vlc will create a unique file name for you, based on the date and time.
i.e.
file:///home/rolf/vlcsnap-2020-08-14-10h43m06s020.png
file:///home/rolf/vlcsnap-2020-08-14-10h43m08s936.png
#Video Snapshot
def OnSnapShot(self,evt):
media_state = self.player.get_state()
if media_state.value < 3 or media_state.value > 4:
return
if os.path.isfile(self.currentlyplaying):
dir_name = os.path.dirname(self.currentlyplaying)
else:
dir_name = self.home_dir
snapshot_size = self.player.video_get_size(0)
x=self.player.video_take_snapshot(0, dir_name,snapshot_size[0],snapshot_size[1])
if x == 0:
Notify(self,"Snapshot","Image saved in "+dir_name)

Related

how do i make jpg file's name starts with number automatically increase python

If there is same model name, it will be overwritten even if it's a different picture. So I want to name the image file in front of the name when it's made like 01, 02, 03...... but it doesn't work.
please help..
** text **is model name
** filename **is the original name of image file
this is using ocr and it supposed to make new image file name everytime when i use ocr one by one and this made me think for loop is not to use
mn = 0
File = open("modelImg/model.txt",'a')
print("result = {}".format(text))
File.write("result = {}\n".format(text))
File.close()
src = "../images/" + filename
mn += 1
dst = ("modelImg/"+"%i. "%mn+text +".jpg")
shutil.copy(src,dst)
return text
this is what i get...
Based on the code and output that you shared I am guessing that the error is because you have mn = 0 inside the loop. And on every iteration of loop you are incrementing mn by 1 and then reassigning it to 0 again. So you are only getting 1 as a prefix for every file name.
If my assumption is correct then moving mn=0 outside the loop should solve your issue.

How to copy one file into one folder accordingly?

I would like to make a program that can copy one file(e.g. images) to another directory which contains several folders. By just copying all the images to another directory is easy but I wanted it to be one image copies to one folder.
I looped every single element in both directory and globalized them. I tried copying one file into folder but got errors. I think the main problem I cannot do it is because I lack of the idea how to just copy one file to one folder while looping. I hope you can give me some advice on this matter.
import os
import shutil
path = os.listdir('C:\\Users\\User\\Desktop\\img')
#dst1 = os.path.abspath('C:\\Users\\User\\Desktop\\abc')
idst = os.listdir('C:\\Users\\User\\Desktop\\abc')
def allimgs():
counter = 0
for imgs in path:
if imgs.endswith('.JPG'):
counter += 1
#if hits the 24th images then stop and
#copy the first until 24 to another 24 folders one by one
if counter > 24:
break
else:
src = os.path.join('C:\\Users\\User\\Desktop\\img',imgs)
def allfolders():
for folders in idst:
if folders.endswith('.db'):
continue #to skip the file ends with .db
dst = os.path.join('C:\\Users\\User\\Desktop\\abc',folders)
shutil.copy(allimgs(),allfolders()) #here is where i stuck
First of all, make both functions return lists of strings which contain the full paths of the images which will be copied, and the directories to where they will be copied. Afterwards, save the results of allimgs() and allfolders() into variables and loop through them.
Here is how the first function should look like:
def allimgs():
ret = []
counter = 0
for imgs in path:
if imgs.endswith('.JPG'):
counter += 1
#if hits the 24th images then stop and
#copy the first until 24 to another 24 folders one by one
if counter > 24:
break
else:
src = os.path.join('C:\\Users\\User\\Desktop\\img',imgs)
ret.append(src)
return ret
(I left the other one for you as an exercise)
Then loop over them:
for image_path in allimgs():
for folder_path in allfolders():
shutil.copy(image_path, folder_path)

Time module and file changes

I need to write a script that does the following
Write a python script to list all of the files and directories in the current directory and all subdirectories that have been modified in the last X minutes.
X should be taken in as a command-line argument.
Check that this argument exists, and exit with a suitable error message if it doesn’t.
X should be an int which is less than or equal to 120. If not, exit with a suitable error message.
For each of these files and directories, list the time of modification, whether it is a file or directory,
and its size.
I have come up with this
#!/usr/bin/python
import os,sys,time
total = len(sys.argv)
if total < 2:
print "You need to enter a value in minutes"
sys.exit()
var = int(sys.argv[1])
if var < 1 or var > 120 :
print "The value has to be between 1 and 120"
sys.exit()
past = time.time() - var * 60
result = []
dir = os.getcwd()
for p, ds, fs in os.walk(dir):
for fn in fs:
filepath = os.path.join(p, fn)
status = os.stat(filepath).st_mtime
if os.path.getmtime(filepath) >= past:
size = os.path.getsize(filepath)
result.append(filepath)
created = os.stat(fn).st_mtime
asciiTime = time.asctime( time.gmtime( created ) )
print "Files that have changed are %s"%(result)
print "Size of file is %s"%(size)
So it reports back with something like this
Files that have changed are ['/home/admin/Python/osglob2.py']
Size of file is 729
Files that have changed are ['/home/admin/Python/osglob2.py', '/home/admin/Python/endswith.py']
Size of file is 285
Files that have changed are ['/home/admin/Python/osglob2.py', '/home/admin/Python/endswith.py', '/home/admin/Python/glob3.py']
Size of file is 633
How can i get this to stop reepeating the files ?
The reason your code builds a list of all the files it's encountered is
result.append(filepath)
and the reason it prints out that whole list every time is
print "Files that have changed are %s"%(result)
So you will need to change one of those lines: either replace the list, rather than appending to it, or (much more sensible IMO) just print out the one latest filename found, rather than the whole list.
You aren't clearing your result list at the end of each iteration. Try something like result.clear() after your second print statement. Make sure it is on the same indent as the for though, not the print.

how to skip the rest of a sequence

I have a couple of functions that are being called recursively inside nested loops. The ultimate objective of my program is to:
a) loop through each year,
b) within each each year, loop through each month (12 total),
c) within each month, loop through each day (using a self generated day counter),
d) and read 2 files and merge them together into a another file.
In each instance, I am going down into the directory only if exists. Otherwise, I'm to just skip it and go to the next one. My code does a pretty good job when all the files are present, but when one of the files is missing, I would like to just simply skip the whole process of creating a merged file and continue the loops. The problem I am getting is a syntax error that states that continue is not properly in the loop. I am only getting this error in the function definitions, and not outside of them.
Can someone explain why I'm getting this error?
import os, calendar
file01 = 'myfile1.txt'
file02 = 'myfile2.txt'
output = 'mybigfile.txt'
def main():
#ROOT DIRECTORY
top_path = r'C:\directory'
processTop(top_path)
def processTop(path):
year_list = ['2013', '2014', '2015']
for year in year_list:
year_path = os.path.join(path, year)
if not os.path.isdir(year_path):
continue
else:
for month in range(1, 13):
month_path = os.path.join(year_path, month)
if not os.path.isdir(month_path):
continue
else:
numDaysInMth = calendar.monthrange(int(year), month)[1]
for day in range(1, numDaysInMth+1):
processDay(day, month_path)
print('Done!')
def processDay(day, path):
day_path = os.path.join(path, day)
if not os.path.isdir(day_path):
continue
else:
createDailyFile(day_path, output)
def createDailyFile(path, dailyFile):
data01 = openFile(file01, path)
data02 = openFile(file02, path)
if len(data01) == 0 or len(data02) == 0:
# either file is missing
continue
else:
# merge the two datalists into a single list
# create a file with the merged list
pass
def openFile(filename, path):
# return a list of contents of filename
# returns an empty list if file is missing
pass
if __name__ == "__main__": main()
You can use continue only plainly inside a loop (otherwise, what guarantee you have that the function was called in a loop in the first place?) If you need stack unwinding, consider using exceptions (Python exception handling).
I think you can get away with having your functions return a value that would say if operation was completed successfully:
def processDay(day, path):
do_some_job()
if should_continue:
return False
return True
And then in your main code simply say
if not processDay(day, path):
continue
You are probably getting that error in processDay and createDailyFile, right? That's because there is no loop in these functions, and yet you use continue. I'd recommend using return or pass in them.
The continue statement only applies in loops as the error message implies if your functions are structured as you show you can just use pass.
continue can only appear in a loop since it tells python not to execute the lines below and go to the next iteration. Hence, this syntax here is not valid :
def processDay(day, path):
day_path = os.path.join(path, day)
if not os.path.isdir(day_path):
continue # <============ this continue is not inside a loop !
else:
createDailyFile(day_path, output)enter code here
Same for your createDailyFile function.
You may want to replace it with a return ?

Making a variable name to check if it's defined in Python

I have a form where you have the option to add upload inputs. I want the images that will be uploaded with every input to be grouped together (there will be text in between). Every time an upload button is added it get's the name "upload_image1", "upload_image2", ...
I want to check if these names are defined so i can then loop through them later. I am trying to combine upload_image and an integer that is counting up together but it looks like he is trying to add that integer to the value of upload_image which is not defined.
if len(form["upload_image1"]) > 0:
while 1:
field_count = 1
if len(form["upload_image" + str(field_count)]) == 0: break
upload_field = form["upload_image" + str(field_count)]
upload_image += upload_field
article_content += """
<p>%s</p>
""" % (description[field_count].value)
for item in upload_field:
article_content += '<img src="http://www.******.com/images/%s/%s">' % (link_title, item.filename)
field_count = field_count + 1
Here is how to avoid the KeyError:
If form["upload_image1"] is a string, then use form.get("upload_image1", "") instead.
If form["upload_image1"] is a sequence (e.g. list or tuple), then use form.get("upload_image1", ()) instead.
I fixed the Memory Error. I accidentally put field_count = 1 inside my loop so it kept resetting itself.
The rest apparently works just fine. Thanks for the help!

Categories