Python ImageGrab Not Working With Input - python

In my program, I'm taking a screenshot of a part of my screen, which works. But when I add anything in front of calling the function it's in, it no longer gets past the ImageGrab part.
This works:
def takePictures():
print("3")
if __name__ == '__main__':
print("1")
im = ImageGrab.grab(bbox=(760, 250, 1160, 680)) # X1,Y1,X2,Y2
print("2")
im.save('ALL.png')
#im.show()
takePictures()
This doesn't:
def takePictures():
print("3")
if __name__ == '__main__':
print("1")
im = ImageGrab.grab(bbox=(760, 250, 1160, 680)) # X1,Y1,X2,Y2
#^^^ Doesnt get past this line
print("2")
im.save('ALL.png')
#im.show()
if input() == "":
takePictures()
I've also tried it with inputs from keys on a different window and it's the same.

Your program will pause at
if input() == "":
takePictures()
until you activate the python executing window and hit the enter key.
If you want to take screen shots, you can use, say
time.sleep(10)
giving yourself 10 seconds to activate the window you want to take a screen shot of.

Related

How to run 2 loops side by side in python?

I have tried both of these solutions
from multiprocessing import Process
def loop_a():
while 1:
print("a")
def loop_b():
while 1:
print("b")
if __name__ == '__main__':
Process(target=loop_a).start()
Process(target=loop_b).start()
and the second solution
import threading
import time
def infiniteloop1():
while True:
print('Loop 1')
time.sleep(1)
def infiniteloop2():
while True:
print('Loop 2')
time.sleep(1)
thread1 = threading.Thread(target=infiniteloop1)
thread1.start()
thread2 = threading.Thread(target=infiniteloop2)
thread2.start()
but both of these dont work whichever loop is above like in the second case infiniteloop1 is above so infiniteloop1 will run then after it ends infiniteloop2 will run and i want BOTH of them to run at the same time what i think that the problem is that both the loops will take input from user in some kind like in the first loop it will take voice input and in the second loop it will see if a mouse button is pressed. so while one loop is taking input the other wont run something like that is happening from what i think
this is the code of my loops
loop 1
def screen_display():
white = (255, 255, 255)
screen = pygame.display.set_mode((320, 600))
pygame.display.set_caption("Assistant")
screen.fill(white)
exit_button = pygame.image.load('cross.png').convert_alpha()
set_height = exit_button.get_height()
set_width = exit_button.get_width()
exit_button_rect = exit_button.get_rect(center=(230, 545))
settings_button = pygame.image.load('settings.png').convert_alpha()
pygame.transform.scale(settings_button, (set_height, set_width))
settings_button_rect = settings_button.get_rect(center=(67, 545))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
mousepos = pygame.mouse.get_pos()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if is_over(settings_button_rect, mousepos):
print(1)
if is_over(exit_button_rect, mousepos):
print(2)
loop 2
while True:
# Exception handling to handle
# exceptions at the runtime
try:
# use the microphone as source for input.
global source2
with sr.Microphone() as source2:
# wait for a second to let the recognizer
# adjust the energy threshold based on
# the surrounding noise level
settings()
print("say the command after the beep")
SpeakText("What do you want me to do?")
MyText = speech_text()
turn_text_to_sense(MyText)
if 'your name' in MyText:
print("You can change my name say 'help' for help")
except sr.RequestError as e:
SpeakText("Could not request results please check your internet connection; {0}".format(e))
except sr.UnknownValueError:
SpeakText("Couldn't understand what you said, say 'help' for info about commands")
there is some more code of other functions but i dont think that they are important
You'd better use threading
import threading
def loop_a():
while 1:
print("a")
def loop_b():
while 1:
print("b")
if __name__ == '__main__':
threadings = []
threadings.append(threading.Thread(target = loop_a))
threadings.append(threading.Thread(target = loop_b))
for thread_item in threadings:
thread_item.start()
for thread_item in threadings:
thread_item.join()

Why is cv2 showing a blank grey square?

I have a python program using the cv2 library, that chooses a random US state, pulls the image of the state from a folder and displays it. It was working fine, so I saved it, and suddenly, instead of showing the image, it shows a blank grey square and crashes. Why is it doing this, and how can I fix it? Heres the sample images:
and heres the code:
import cv2
import random
import time
#makes a list of the states
def states():
states = ['alabama','alaska','arizona','arkansas','california',
'colorado','connecticut','deleware','florida','georgia','hawaii',
'idaho','illinois','indiana','iowa','kansas','kentucky','louisiana',
'maine','maryland','massachussets','michigan','minnesota',
'mississipi','missouri','montana','nebraska','nevada',
'new_hampshire','new_jersey','new_mexico','new_york',
'north_carolina','north_dakota','ohio','oklahoma','oregon',
'pennsylvania','rhode_island','south_carolina','south_dakota',
'tennessee','texas','utah','vermont','virginia','washington',
'west_virginia','wisconsin','wyoming']
while True:
#choose a random state from the states list
state = random.choice(states)
#take a picture from the states folder, and display it
img = cv2.imread('picture_files/states/' + state + '.png')
cv2.imshow('guess the state!', img)
#checks if you typed the right state,
#and gives an appropriate response
guess = input("guess the state! (type stop to stop!)\n")
if guess.lower() == state:
print("Correct!")
time.sleep(2)
print("Lets do it again!")
elif guess.lower() == "stop":
break
else:
print("Nope! It was " + state + ". Keep trying!")
time.sleep(2)
if __name__ == '__main__':
states()
Basically you are missing some cv2.waitKey() function to show the image (see also here).
This is a possible example for a solution.
def pick_a_state():
states = ['a','b'] # replace with your list
return random.choice(states)
def show_state(state):
img = cv2.imread(state + '.png', cv2.IMREAD_UNCHANGED)
cv2.imshow('guess the state!', img)
cv2.waitKey(1000)
def get_the_answer(state):
guess = raw_input("guess the state! (type stop to stop!)\n")
if guess.lower() == state:
print(state)
print("Correct!")
time.sleep(2)
print("Lets do it again!")
return 1
elif guess.lower() == "stop":
return 0
else:
print("Nope! It was " + state + ". Keep trying!")
time.sleep(2)
return 1
if __name__ == '__main__':
while True:
state = pick_a_state()
show_state(state)
if get_the_answer(state) == 0:
cv2.destroyAllWindows()
break
Please analyze the code to understand how it works. Hope can help.
I've had an error like this before where opencv would not open and have been successful in a few ways to solve it.
Add cv2.waitKey(0) at the end of your function and then add
cv2.destroyAllWindows() underneath your calling of states()
like this:
if __name__ == '__main__':
states()
cv2.destroyAllWindows()
Install opencv-contrib-python.
Try installing it with the command pip3 install opencv-contrib-python==4.4.0.46.

Change value while program is runing

I need a program on raspberry pi, in which I can change the value of a variable delay while the program is running and is not interrupted by any input(). I came up with only one solution: read a value from a text file and change it using another program. But my solution doesn't work very well... When I overwrite a value in a text file, sometimes it happens that the program can't convert it to a float... sometimes it works well and sometimes it prints this error:
ValueError: could not convert string to float: ''
But the value in the text file seems to be fine...
So, this is main program:
def pause():
file = open('delay.txt', 'r')
pause = file.readline()
return pause
delay = float(pause())
while True:
GPIO.output(STEP, GPIO.HIGH)
delay = float(pause())
sleep(delay)
GPIO.output(STEP, GPIO.LOW)
delay = float(pause())
sleep(delay)
And this is the program, which is changing value in the text file:
while True:
rpm = float(input('RPM: '))
delay = (1/(rpm*60))/800
file = open('delay.txt', 'w')
file.write(str(delay))
file.close()
I really can't move with this... I'll be grateful for any advice and help in solving it.
You don't have to stick to my idea with a text file, maybe there is a better solution, but I couldn't think of anything better.
I'd suggest you use threading for this. I've made a small code example for you to get you started:
import threading
from time import sleep
import logging
logging.basicConfig(level=logging.DEBUG, filename="thread_output.txt", format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s')
running = True
delay = 1
def worker(delay, running):
while running():
logging.debug(1)
sleep(delay())
logging.debug(0)
sleep(delay())
x = threading.Thread(target=worker, args=(lambda: delay, lambda: running))
x.start()
while running:
code = input("""
Make a choice:
1) Set delay
2) quit
""")
code = int(code)
if code == 1:
try:
val = input("Give up the desired delay between 0 and 10 seconds:")
val = int(val)
assert val >= 0 and val <= 10
delay = val
except ValueError:
print("Invalid input! Returning to home menu")
continue
elif code == 2:
running = False
else:
print("invalid option! Returning to home menu")
continue
print("quiting...")
x.join()
The part that helps you here is the fact that you pass the value of delay (and in the example also of running) as a lambda function. This means that every time the value is used, the value refetched. If you then were to change the value of the variable, it would get passed on :)
Hit me up if you have more questions!

open cv python drawing with the mouse

I keep getting an invalid syntax error with this. So, how can I resolve this and where can I find related documentation in the future.
import cv2
import numpy as np
drawing = False # true if mouse is pressed
mode = True # if True, draw rectangle. Press 'm' to toggle to curve
ix,iy = -1,-1
class DessinerLigne:
def dessinerLigne(self):
# Create a black image
self.img=np.zeros((512,512,3),np.uint8)
def draw_circle(event,x,y,flags,param):
global ix,iy,drawing,mode
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix,iy = x,y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
if mode == True:
cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
else:
cv2.circle(img,(x,y),5,(0,0,255),-1)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
if mode == True:
cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
else:
cv2.circle(img,(x,y),5,(0,0,255),-
img = np.zeros((512,512,3), np.uint8)
cv2.imshow("Image", self.img)
# If q is pressed then exit program
self.k=cv2.waitKey(0)
if self.k==ord('q'):
cv2.destroyAllWindows()
if __name__=="__main__":
DL=DessinerLigne()
DL.dessinerLigne()
There clearly are multiple issues with this script. Ones that need immediate attention are:
There's an indentation error in the definition of dessinerLigne class.
Change:
class DessinerLigne:
def dessinerLigne(self):
# Create a black image
self.img=np.zeros((512,512,3),np.uint8)
to:
class DessinerLigne:
def dessinerLigne(self):
# Create a black image
self.img=np.zeros((512,512,3),np.uint8)
and the indentation error should be fixed.
There's an incomplete line of code in line 32.
Is line 33 a part of the method draw_circle()? If so, it has be properly indented. Add 4 whitespaces in front of it.
You seem to have pasted the code from somewhere. During this process, it is very likely that some invisible control characters that might break the syntax may have arrived. Use an editor that has 'show invisible' features to resolve this issue.

Python curses menu not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Trying to get a really basic curses menu to work. I've been following a tutorial but I've kinda split off to doing my own thing. I tried to touch on everything with comments. I just want to figure out how to get the selections to work.
import sys
import curses
import time
def menu(window, dims):
window.nodelay(0) # not sure what this does, lol
window.clear() # clear window
selection = -1 # the menu code is from the tutorial
option = 0 # so most of this is foreign to me
while selection < 0: # loop
graphics = [0]*2 # point to list
graphics[option] = curses.A_REVERSE # set graphic, reverse BKGND color
window.border() # border
window.addstr(1, dims[1]/2-2, "Menu")
window.addstr(3, dims[1]/2-2, "Play", graphics[0])
window.addstr(4, dims[1]/2-2, "Exit", graphics[1])
window.refresh() # refresh the window
action = window.getch() # get input
if action == curses.KEY_UP: # if key is up
option = (option - 1) # go up?
elif action == curses.KEY_DOWN: # key is down
option = (option + 1) # go down?
elif action == ord('\n'): # if RETURN
selection = option # make selection
window.clear() # clear all
if selection == 0: # if is 0, do nothing right now.
return # it's not changing selection
elif selection == 1: # so waiting for that to add here
return
def main(): # main function // ran first
window = curses.initscr() # making new window
dims = window.getmaxyx() # getting window dimensions
if not curses.has_colors(): # color test
curses.endwin() # color test
print "no colors" # color test
sys.exit() # color test
else: # color test
curses.start_color() # color test
curses.noecho() # don't echo the keys on the screen
curses.cbreak() # don't wait enter for input
curses.curs_set(0) # don't show cursor
main_loop(window, dims) # go into main loop
def main_loop(window, dims):
while menu(window, dims):
pass
window.clear()
window.addstr(dims[0]/2, (dims[1]-4)/2, "Exiting...")
window.refresh()
time.sleep(1)
curses.noecho()
curses.cbreak()
curses.curs_set(1)
curses.endwin()
if __name__ == '__main__':
main()
I was missing window.keypad(1) to actually activate the input.
I added it just before the main_loop().

Categories

Resources