I want to put different wallpaper on different Display(Monitor).
I'm starting a little project to change the windows wallpaper a little easier and with more features, but it doesn't work properly with two monitors. It changes the wallpaper of the two Monitors.
I didn't find any way to solve the problem with this method of changing the wallpaper. I wonder if there is any way
import os, ctypes
import tempfile , time
path = os.path.expanduser("~\Pictures")
count = 0
extAcept = [".jpg", ".png", ".bmp", ".jpge"]
def mudaImage(path):
pathT = path
SPI_SETDESKWALLPAPER = 20
for file in os.listdir(pathT):
tempN = 0
for ext in extAcept:
if file.endswith(ext):
way = pathT+"\\"+file
neway = my_replace(way,"\\","/")
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, neway, 0x3)
tempN += 1
#print(neway)
time.sleep(2)
count = tempN
if count == 0:
print("Nenhum arquivo foi encontrado")
def my_replace(arg1,chrt1,chrt2):
caminho = arg1.replace(chrt1,chrt2)
return caminho
mudaImage(pasta)
Related
I am trying to program something with win32gui and now I need to know how I can get the filelocation of the file I am running in Visual Studio Code, Word or Wordpad. I used win32gui.GetOpenFileName, but it doesn't work anymore after I checked the type of variable I get. My question is: Is it the best way to get the filelocation or is there a better way. If it is the best way does someone know why it's not working anymore?
My Second question is regarding the running of the script. I want to run the script automatically as soon as I start Word, Visual Studio Code or Wordpad. What is the best way to do this?
I tried finding solutions online but at the moment I am lacking inspiration. Thank you for your help.
Update>
I got this far with the code. I want to change it so that I can get the file automatically and I want to start is with Visual Studio Code instead of starting it manuely every time.
import win32gui
import math
e = math.e
maxwidth = 1874
maxheight = 950
x =450
y = 1500 + round(maxwidth/(1+e**(-0.009*(0-57.45))))
#minwidth = 700
#minheight = 505
k = 0
l = 0
def main():
win32gui.EnumWindows(callback, None)
def callback(hwnd, extra):
windowopen = False
name = win32gui.GetWindowText(hwnd)
if name.endswith('Visual Studio Code') and name.startswith('_test.py'):
windowopen = True
print(name)
while windowopen:
j = 0
for i in open('D:\_test.py', 'r'):
j += 1
k = round(maxwidth/(1+e**(-0.009*(j-57.45))))
l = round(maxheight/(1+e**(-0.009*(j-57.45))))
yuse = y - k
win32gui.MoveWindow(hwnd, yuse, x, k, l, True)
print(name)
file = win32gui.GetOpenFileName
print(file)
if __name__ == '__main__':
main()
Update>
I imported os and than used the .path.dirname function to get my file location:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
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
I am using this library midi2img to generate midi from images
From this library, this is the file am using:
from PIL import Image
import numpy as np
from music21 import instrument, note, chord, stream
lowerBoundNote = 21
def column2notes(column):
notes = []
for i in range(len(column)):
if column[i] > 255/2:
notes.append(i+lowerBoundNote)
return notes
resolution = 0.25
def updateNotes(newNotes,prevNotes):
res = {}
for note in newNotes:
if note in prevNotes:
res[note] = prevNotes[note] + resolution
else:
res[note] = resolution
return res
def image2midi(image_path):
with Image.open(image_path) as image:
im_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
try:
im_arr = im_arr.reshape((image.size[1], image.size[0]))
except:
im_arr = im_arr.reshape((image.size[1], image.size[0],3))
im_arr = np.dot(im_arr, [0.33, 0.33, 0.33])
""" convert the output from the prediction to notes and create a midi file
from the notes """
offset = 0
output_notes = []
# create note and chord objects based on the values generated by the model
prev_notes = updateNotes(im_arr.T[0,:],{})
for column in im_arr.T[1:,:]:
notes = column2notes(column)
# pattern is a chord
notes_in_chord = notes
old_notes = prev_notes.keys()
for old_note in old_notes:
if not old_note in notes_in_chord:
new_note = note.Note(old_note,quarterLength=prev_notes[old_note])
new_note.storedInstrument = instrument.Piano()
if offset - prev_notes[old_note] >= 0:
new_note.offset = offset - prev_notes[old_note]
output_notes.append(new_note)
elif offset == 0:
new_note.offset = offset
output_notes.append(new_note)
else:
print(offset,prev_notes[old_note],old_note)
prev_notes = updateNotes(notes_in_chord,prev_notes)
# increase offset each iteration so that notes do not stack
offset += resolution
for old_note in prev_notes.keys():
new_note = note.Note(old_note,quarterLength=prev_notes[old_note])
new_note.storedInstrument = instrument.Piano()
new_note.offset = offset - prev_notes[old_note]
output_notes.append(new_note)
prev_notes = updateNotes(notes_in_chord,prev_notes)
midi_stream = stream.Stream(output_notes)
midi_stream.write('midi', fp=image_path.split("/")[-1].replace(".jpeg",".mid"))
import sys
image_path = sys.argv[1]
image2midi(image_path)
and this is the code I execute in terminal to geneate midi from image:
python img2midi.py samples/image.png
I need to make the above code to loop over all input images I put inside samples folder and generate midi for each, not just one file at a time.
Any help would be much appreciated.
You can do this by getting list of images from directory and iterate over them.
import sys
import os
sample_folder_path = sys.argv[1]
images = os.listdir(sample_folder_path) # getting all images stored in sample folder
images_path = [os.path.abspath(f"{sample_folder_path}/{image}") for image in images] # gets absolute path for all images
for image_path in images_path:
image2midi(image_path)
Usage:
python img2midi.py folder_path
Here folder_path is the path of folder that contains images. It can
I have a program that is supposed to take screenshots...
#imports pyqt
from PyQt4.QtGui import QPixmap, QApplication
#declares variables
date = datetime.datetime.now()
counter = 0
#sets directory to be used to save screenshots
directorydate = str(date.year) + str(date.month) + str(date.day) + str(date.hour) +str(date.minute) + str(date.second)
directory = os.path.abspath('Photos%s' % directorydate)
#some weird PyQt thing I don't understand
app = QApplication(sys.argv)
#game loop
while True
counter += 1
#declarations
picdate = str(date.year) + str(date.month) + str(date.day) + str(date.hour) +str(date.minute) + str(date.second) + str(counter) + '.png'
pic = QPixmap.grabWindow(QApplication.desktop().winId())
#saves screenshots to a custom directory
pic.save('Photos%s/' % directorydate + picdate)
#adds screenshots to list and deletes them once 150 have been collected
if counter == 1:
pics = [picdate]
picfirst = pics[0]
if not os.path.exists(directory):
os.makedirs(directory)
else:
pics.append(picdate)
if counter == 150:
os.remove(picfirst)
pics.remove(picfirst)
counter = 0
...then animates them to the pygame window
background = pygame.image.load('Photos%s/' % directorydate + picdate)
displaysurf.blit(background)
#pygame event handling
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
When I try to run it, the shell gives me "error: Couldn't open Photos_____/____.png
I am not sure what the problem is as regardless of compatibility between PyGame and PyQt, once the image is saved as a .png, it should be able to be loaded like any other image. Is it just because it's open already while the code is running?
Any explanations and/or solutions would be appreciated, thank you.
Problem is that you first save pic with counter=1 without checking if directory exists so it's not saved at all.
After that you create directory if the pic counter == 1, so directory is created and all other pics will be saved in it but not first one.
You get error when you try to open that first pic which is not in the directory since it was not saved because directory has not existed.
Solution is to move this code:
if not os.path.exists(directory):
os.makedirs(directory)
here:
#sets directory to be used to save screenshots
directorydate = str(date.year) + str(date.month) + str(date.day) + str(date.hour) +str(date.minute) + str(date.second)
directory = os.path.abspath('Photos%s' % directorydate)
if not os.path.exists(directory):
os.makedirs(directory)
I would like to be able to save my session state within the PythonWin editor (e.g. these three files are opened and positioned in these particular locations within the PythonWin window). I can get handles to each of the child windows within PythonWin using win32gui, as well as the titles of each of the files and the positions/sizes of the windows. I'm unclear though in how to get the full path for the file listed as the child window name (i.e. if child window name is test.py and test.py lives at c:\python\test.py, I don't know how to get c:\python). I was thinking I would write out which files were opened plus their window positions to a small file that I would then call at PythonWin start time for loading.
Any ideas on how to get the full paths to the child window names?
Alternatively if someone already has a more elegant solution for saving session state in PythonWin please pass it along.
Below is the code I'm using right now (thanks to Michal Niklas for the starter code for using win32gui).
import win32gui
import re
MAIN_HWND = 0
def is_win_ok(hwnd, starttext):
s = win32gui.GetWindowText(hwnd)
if s.startswith(starttext):
global MAIN_HWND
MAIN_HWND = hwnd
return None
return 1
def find_main_window(starttxt):
global MAIN_HWND
win32gui.EnumChildWindows(0, is_win_ok, starttxt)
return MAIN_HWND
def winPos(hwnd):
if type(hwnd) == type(1): ( left, top, right, bottom ) = win32gui.GetWindowRect(hwnd)
return "%i, %i, %i, %i" % (left, right, top, bottom)
def winName(hwnd, children):
s = win32gui.GetWindowText(hwnd)
rePy = re.compile(r'[a-zA-Z1-9_ ]*.py')
rePySearch = rePy.search(s)
if rePySearch is not None:
if rePySearch.group()[0:7] != "Running":
s = s + ',' + winPos(hwnd) + '\n'
children.append(s)
return 1
def main():
children = []
main_app = 'PythonWin'
hwnd = win32gui.FindWindow(None, main_app)
if hwnd < 1:
hwnd = find_main_window(main_app)
if hwnd:
win32gui.EnumChildWindows(hwnd, winName, children)
filename = "sessionInfo.txt"
sessionFile = os.path.join(sys.path[0],filename)
fp=open(sessionFile, 'wb')
for i in range(len(children)):
fp.write(children[i])
fp.close()
main()
I could be wrong, but isn't PythonWin written in Python?
Have you tried reading the source to the "Save" command to figure out where it stores its full paths?
(I'd take a look myself, but I haven't used Windows in half a decade)