Screenshot script can't save the .png image with the actual date - python

I'm writing a python script to screenshot every 30 seconds and save the output image with the actual date.
The problem is that the script is saving each image with each letter of the time.ctime() output (Tue Jan 3 01:30:53 2017):
T.png
u.png
e.png
...
How can i save each image output with the actual complete date ?
import pyscreenshot as ImageGrab
import time
max_prints = 10
counter = 0
timer = time.ctime()
while counter < max_prints:
for mark in timer:
im=ImageGrab.grab()
#im.show()
im=ImageGrab.grab(bbox=(10,10,500,500))
#im.show()
ImageGrab.grab_to_file(str(mark) + ".png")
time.sleep(30)

This loop may help:
while counter < max_prints:
im = ImageGrab.grab(bbox=(10, 10, 500, 500))
filename = str(dt.datetime.now()).replace(' ', 'T').split('.')[0] + ".png"
ImageGrab.grab_to_file(filename)
time.sleep(5)

Can you try with something like thisĀ ?
import pyscreenshot as ImageGrab
import time
max_prints = 10
counter = 0
while counter < max_prints:
im=ImageGrab.grab()
#im.show()
im=ImageGrab.grab(bbox=(10,10,500,500))
#im.show()
timer = time.ctime()
ImageGrab.grab_to_file(timer + ".png")
time.sleep(30)
counter += 1
If you want to you could have filenames that will be easier to handle afterward by changing these lines:
timer = time.ctime()
ImageGrab.grab_to_file(timer + ".png")
To this:
timer = time.ctime()
timestamp = timer.replace(' ', '_')
timestamp = timestamp.replace(':', '_')
filename = "{}.png".format(timestamp)
ImageGrab.grab_to_file(filename)
But it depends on how you want your files to be named.

Related

Python : how to have preview of DSLR camera

I came here as I am lost.
I have a code which basically provides a preview on screen before a picture is taken. The code runs on 2 camera (it doesn't make sense I know).
Pi camera : for preview
DSLR camera : for taking the pictures
The scripts works as expected. The issue is that the PIcamera zoom is not aligned with the DSLR.
I know it is possible to get the DSLR preview on screen which would be better. However I don't know how to do it. As I am new to python, I read as much as I could. I read solution with VLC but I didn't understand the specificities. I read the gphoto2 help but got lost in the technical parts. Hence I'd highly appreciate if someone can help me out or point me to the correct direction.
The DSLR camera is a Canon EOS D60 which should be compatible for screen preview.
I attached below the code
from picamera import PiCamera
import time
from time import sleep
import logging
import sys
import gphoto2 as gp
import locale
photonr = 1
countdown = 5
FolderRaw='/home/pi/'
def TakePicture():
global rafale
try:
rafale +=1
except Exception as e:
rafale =1
camera1 = PiCamera()
locale.setlocale(locale.LC_ALL, '')
logging.basicConfig(
format='%(levelname)s: %(name)s: %(message)s', level=logging.WARNING)
callback_obj = gp.check_result(gp.use_python_logging())
camera2 = gp.Camera()
camera2.init()
i = 1
while i < photonr+1:
preview = camera1.start_preview()
preview.fullscreen = True
picture_time = time.strftime("%Y-%m-%d")
global image
image = picture_time+ '_' + str(rafale) + '_' + str(i)
if i == 1 :
countdown2 = countdown +1
else :
countdown2 = 3
for counter in range(countdown2, 0, -1):
camera1.annotate_text = str(counter)
camera1.annotate_text_size = 120
sleep(1)
camera1.annotate_text = ''
print('Capturing image')
file_path = camera2.capture(gp.GP_CAPTURE_IMAGE)
print('Camera file path: {0}/{1}'.format(file_path.folder, file_path.name))
target = FolderRaw+image +'.jpg'
print('Copying image to', target)
camera_file = camera2.file_get(
file_path.folder, file_path.name, gp.GP_FILE_TYPE_NORMAL)
camera_file.save(target)
#camera.capture(FolderRaw+image +'.jpg')
camera1.stop_preview()
print ("Raw picture taken and saved on " + image )
i += 1
camera1.close()
camera2.exit()
TakePicture()
Thank you beforehand for any tips/direction/help

How to add seconds of silence at the end of a .wav file?

I have 1,440 audio files to feed into a neural network. The problem is that they are not all the same length. I used the answer posted on:
Adding silent frame to wav file using python
but it doesn't seem to work. I wanted to add a few seconds of silence to the end of my files, and then trim them to all be 5 seconds long. Can someone please help me with this?
(I also tried using pysox, but that gives me the This install of SoX cannot process .wav files. error.)
I am using Google Colab for this. The code is:
import wave, os, glob
from pydub import AudioSegment
from pydub.playback import play
path = 'drive/MyDrive/Ravdess/Sad' #This is the folder from my Google Drive which has the audio files
count = 0
for filename in glob.glob(os.path.join(path, '*.wav')):
w = wave.open(filename, 'r')
d = w.readframes(w.getnframes())
frames = w.getnframes()
rate = w.getframerate()
duration = frames/float(rate)
count+=1
print(filename, "count =", count, "duration = ", duration)
audio_in_file = filename
audio_out_file = "out.wav"
new_duration = duration
#Only append silence until time = 5 seconds.
one_sec = AudioSegment.silent(duration=2000) #duration in milliseconds
song = AudioSegment.from_wav(audio_in_file)
final_song = one_sec + song
new_frames = w.getnframes()
new_rate = w.getframerate()
new_duration = new_frames/float(rate)
final_song.export(audio_out_file, format="wav")
print(final_song, "count =", count, "new duration = ", new_duration)
w.close()
This gives the output:
drive/MyDrive/Ravdess/Sad/03-01-04-01-02-01-01.wav count = 1 duration = 3.5035
<pydub.audio_segment.AudioSegment object at 0x7fd5b7ca06a0> count = 1 new duration = 3.5035
drive/MyDrive/Ravdess/Sad/03-01-04-01-02-02-01.wav count = 2 duration = 3.370041666666667
<pydub.audio_segment.AudioSegment object at 0x7fd5b7cbc860> count = 2 new duration = 3.370041666666667
... (and so on for all the files)
Since you are already using pydub, I'd do something like this:
from pydub import AudioSegment
from pydub.playback import play
input_wav_file = "/path/to/input.wav"
output_wav_file = "/path/to/output.wav"
target_wav_time = 5 * 1000 # 5 seconds (or 5000 milliseconds)
original_segment = AudioSegment.from_wav(input_wav_file)
silence_duration = target_wav_time - len(original_segment)
silenced_segment = AudioSegment.silent(duration=silence_duration)
combined_segment = original_segment + silenced_segment
combined_segment.export(output_wav_file, format="wav")

How to make python script to run at specific time?

This is my script, it takes screenshots after 5 seconds and stores it into a png file with timestamp as its name.
I want this script to run between 9am to 5pm everyday so i could get screenshot f every activity done between 9 to 5 every day.
import pyautogui
import time
for i in range(4):
# Take screensot
pic = pyautogui.screenshot()
#Name the file with data and time
ts = time.strftime("%Y%m%d-%H%M%S")
filename = "screenshot"
filename += str(ts)
filename += ".png"
# Save the image
pic.save('C:\\Users\\DELL\\Desktop\\Frankiii\{}'.format(filename))
time.sleep(5)
Here is how you could do it.
import schedule
def start():
print("{} Start the job".format(datetime.datetime.now()))
def stop():
print("{} Time's up!!!".format(datetime.datetime.now()))
sys.exit()
schedule.every().day.at("09:00").do(start)
schedule.every().day.at("17:00").do(stop)

Python-OpenCV --F Function error--not finding right dir

Am trying to put a timelapse on my OpenCV code but it seems i am doing something that is not right and i don't know why i have the error.
The erorr i got is for this line: filename = f"{timelapse_img_dir}/{i}.jpg" What should i do in order not to have an error?
This is the error i have from my IDE:
File "/Users/Dropbox/OpenCV/src/timelapse.py", line 34
filename = f"{timelapse}/{i}.jpg"
^
SyntaxError: invalid syntax
[Finished in 0.1s with exit code 1]
[shell_cmd: python -u "/Users/Dropbox/OpenCV/src/timelapse.py"]
[dir: /Users/Dropbox/OpenCV/src]
[path: /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin]
My code:
import os
import numpy as np
import cv2
import time
import datetime
from utils import CFEVideoConf, image_resize
import glob
cap = cv2.VideoCapture(0)
frames_per_seconds = 20
save_path='saved-media/timelapse.mp4'
config = CFEVideoConf(cap, filepath=save_path, res='720p')
out = cv2.VideoWriter(save_path, config.video_type, frames_per_seconds, config.dims)
timelapse_img_dir = '/Users/Dropbox/OpenCV/src/images/timelapse/'
seconds_duration = 20
seconds_between_shots = .25
if not os.path.exists(timelapse_img_dir):
os.mkdir(timelapse_img_dir)
now = datetime.datetime.now()
finish_time = now + datetime.timedelta(seconds=seconds_duration)
i = 0
while datetime.datetime.now() < finish_time:
'''
Ensure that the current time is still less
than the preset finish time
'''
ret, frame = cap.read()
# filename = f"{timelapse_img_dir}/{i}.jpg"
filename = f"{timelapse_img_dir}/{i}.jpg"
i += 1
cv2.imwrite(filename, frame)
time.sleep(seconds_between_shots)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
def images_to_video(out, image_dir, clear_images=True):
image_list = glob.glob(f"{image_dir}/*.jpg")
sorted_images = sorted(image_list, key=os.path.getmtime)
for file in sorted_images:
image_frame = cv2.imread(file)
out.write(image_frame)
if clear_images:
'''
Remove stored timelapse images
'''
for file in image_list:
os.remove(file)
images_to_video(out, timelapse_img_dir)
# When everything done, release the capture
cap.release()
out.release()
cv2.destroyAllWindows()
I believe the format you are using is only supported on python 3.6 "Literal String Interpolation":
https://www.python.org/dev/peps/pep-0498/#raw-f-strings
filename = f"{timelapse_img_dir}/{i}.jpg"
here are 2 other options depends on what python you are using:
python 2.7:
filename = '%(timelapse_img_dir)s %(i)s' % locals()
python 3+
filename = '{timelapse_img_dir} {i}'.format(**locals())
Based on:
https://pyformat.info/
I dont know why i was not able to use the f function. I had to do another concatenation to work.
filename = timelapse_img_dir +str(i) +file_format
and for the rest i used the wild card
filetomake = image_dir + "/*.jpg"
image_list = glob.glob(filetomake)

Python: Need to download images from URL in a loop (JPG and PNG)

my school has digital books, but to access those I need to go through several logins and that way it takes a long time to get to my school book. On top of that I need an internet connection to see them.
I have however found out that the books are on the publishers server as separate images (both jpg's and png's), now I'd like to download those images and combine them into a PDF file.
The problem I'm running into is that the files are not generally accessible so I need to give the script the exact URL, and I can't get it to go to the next file.
This is what I've got so far: Pastebin link
import os
import urllib
import requests
import sys
from time import sleep
from PIL import Image
from reportlab.lib.utils import ImageReader
from reportlab.lib import utils
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm
from subprocess import Popen, PIPE
import shutil
import nltk
from urllib import urlopen
#Change those variables:
URL = "http://cdpcontent.toegang.nu/c436b908-7a8d-49ce-ae5e-24892fa06fd7/20140808123622/extract/assets/img/layout/page-00"
#_____________________________________________________
FILE_END_JPG = ".jpg"
FILE_END_PNG = ".png"
SAVE_TO_DIRECTORY = "images"
NUM = 1 # Default 1
MAX_NUM = 500
builded_link_jpg = URL + str(NUM) + FILE_END_JPG
builded_link_png = URL + str(NUM) + FILE_END_PNG
def link_alive(some_url):
try:
html = urlopen(some_url).read()
four_zero_four = "De door u gevraagde pagina of resource kan helaas niet worden gevonden."
if four_zero_four in html:
#print "Link dead."
return 0
else:
#print "Link alive."
return 1
except Exception as Error:
print Error
print "\nError in check_dead_link function.\n"
def save(NUM, MAX_NUM, SAVE_TO_DIRECTORY, FILE_END_PNG, FILE_END_JPG, URL):
save_name = 0
try:
if not os.path.exists(SAVE_TO_DIRECTORY):
os.makedirs(SAVE_TO_DIRECTORY)
print SAVE_TO_DIRECTORY + " created."
print "All images will be saved to the folder:", SAVE_TO_DIRECTORY + "\n"
while NUM <= MAX_NUM:
if link_alive(builded_link_jpg) == 1:
print "This is a JPG page\n"
save_name = "%04d" % save_name
image = str(save_name) + FILE_END_JPG
save_name = int(save_name)
save_name += 1
urllib.urlretrieve(builded_link_jpg, SAVE_TO_DIRECTORY + "//" + image)
NUM += 1
print builded_link_jpg + " saved.\n"
else:
print "This is a PNG page\n"
save_name = "%04d"% save_name
image = str(save_name) + FILE_END_PNG
save_name = int(save_name)
save_name += 1
urllib.urlretrieve(builded_link_jpg, SAVE_TO_DIRECTORY + "//" + image)
NUM += 1
print builded_link_jpg + " saved.\n"
print "Done saving all the images!"
except Exception as Error:
print Error
print "\nFail in save function.\n"
save(NUM, MAX_NUM, SAVE_TO_DIRECTORY, FILE_END_PNG, FILE_END_JPG, URL)
The part where I'm stuck is the last while, it keeps downloading the same picture but with a incremented name ;/
Could someone help me out here?
You may want to update the value of builded_link_jpg inside the loop!

Categories

Resources