Why is cv2 showing a blank grey square? - python

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.

Related

Using Python for default parameters

I am currently learning python and stuck on a coding exercise. I am trying to achieve the result as shown on the image1. I am stuck on the overall code. I also not sure how to incorporate the "quit", so that the program terminates.
Image1
def tester(result):
while tester:
if len(result)< 10:
return print(givenstring)
else:
return print(result)
def main():
givenstring = "too short"
result=input("Write something (quit ends): ")
if __name__ == "__main__":
main()
For your problem, you need to have a variable that is your Boolean (true/false) value and have your while loop reference that. currently your while loop is referencing your function. inside your main function when you get your user input you can have a check that if the input is "quit" or "end" and set you variable that is controlling your loop to false to get out of it.
you also are not calling your tester function from your main function.
You missed into main() function to call your function, like tester(result). But such basics should not be asked here.
def tester(result):
if len(result)< 10 and result != 'quit':
givenstring = "too short"
return print(givenstring)
else:
return print(result)
def main():
result=None
while True:
if result == 'quit':
print("Program ended")
break
else:
result=input("Write something (quit ends): ")
if result.lower() == 'quit':
result = result.lower()
tester(result.lower())
if __name__ == "__main__":
main()

Code is working only in Jupyter, but the script keeps on crashing when I run it directly from the desktop

First submission here, please don't be too judgemental. So I've written this piece of code to make a "guess a word" game and it works in Jupyter, though it still has some points to be improved. However, I tried to save it as a ".py" file and run it directly from my desktop, but it keeps on crashing. I tried to add some troubleshooting via "pdb", but the application still kept on crashing. Could you please help me on resolving this problem? Any other suggestions on improving the code are appreciated.
P.s.: I'm from Russia, so the game runs using Russian vocabulary, but it shouldn't affect the code... does it?
import random
import io
from __future__ import print_function
class Random_word():
def __init__(self):
self.word = self.new_word()
self.tries = int(6)
self.used_letters = []
def new_word(self):
with io.open('C:\\Users\\mi\\Documents\\Jupyter\\WordsStockRus.txt', 'r', encoding='utf8') as f:
words = (f.read())
words = words.splitlines()
number = random.randint(0, len(words))
word = words[number]
self.word = list(i for i in word)
def string(self):
for i in self.word:
if i not in self.used_letters:
print('_', end=' ')
elif i in self.used_letters:
print(i, end=' ')
def game_over(self):
return set(self.word) <= set(self.used_letters) or self.tries < int(1)
def new_game(self):
self.used_letters.clear()
self.new_word()
self.tries = int(input('How many tries do you want to have?'))
Game = Random_word()
Game.new_game()
print(f'Hello, My dear friends. I\'d like to offer you to play a game of hangman
menu = str('New game / Exit')
while Game.game_over() == False:
print(f'You have {Game.tries} tries to guess the word.')
Game.string()
try:
player_input = input('Enter a letter:')
if player_input in Game.used_letters:
raise Exception
except Exception:
print('Na-ah, already used it')
if player_input in Game.word:
print('Good one!')
Game.used_letters.append(player_input)
elif player_input not in Game.word:
print('Bad luck!')
Game.used_letters.append(player_input)
Game.tries -= 1
else:
print('Game over.')
print(Game.word)
player_input = input(f'Please enter your choice:{menu}')
if player_input == 'New game':
Game.new_game()
elif player_input == 'Exit':
print('Thank you for the game.')

Python ImageGrab Not Working With Input

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.

Python try and except bug (probably)

I've worked with little personal assistant project lately and now I'm facing this problem/bug and I can't get over it.
Here's part of my code:
import os
import sys
from colorama import Fore, Back, Style
import random
from os import system
from src import commands
system("title Assistant")
actions = {
"open":["pubg", "dota", "origins", "spotify", "dogs"],#"open":{["o"]:["pubg", "dota", "origins", "spotify", "dogs"]},
"hue":["1"],
"clear":"",
"hiber":"",
"shutdown":""
}
class MainClass:
#
logo1 = Fore.CYAN + """Not essential"""
logo2 = Fore.CYAN + """Not essential"""
errorcode = "Something went wrong :("
def getCommand(self):
cmd = input(Fore.MAGENTA + "Assistant > " + Fore.CYAN)
print("cmd: " + cmd)
self.checkCommand(cmd)
def checkCommand(self, cmd):
actions = commands.Commands().actions
words = cmd.lower().split()
print("Words: " + ' '.join(words))
found = False
ekasana = ""
par = ""
print("running if " + words[0] + str(words[0] == "q"))
#Here's the problem. After I imput 'clear', which clear's the screen and runs mainInterface(2.0, randomthing), this if does not work.
# Here's the output
# Not essentialv 2.0
# By Dudecorn
# Assistant > q
# cmd: q
# Words: q
# running if qTrue
# self.errorcode
# clear
# ['clear']
# Assistant >
# Why is is that clear command staying there? I am so confused right now.
# Read line 68
if words[0] == "q":
quit()
sys.exit()
for word in words:
word = ''.join(word)# Sorry about the mess
print(word)
# Check for action without parameters
if word in actions and actions[word] == "" and found == False:
try: # I'm pretty sure that this part of code is causing the problem
# If you remove try and except, and leave just lines 70 and 71, code works as line 58 if statement's value is true.
# This is in the another file -> getattr(commands.Commands, word)(self)
self.mainInterface(2.0, random.randint(1, 2))
break
except:
print("self.errorcode")
print(word)
print(words)
# Check for action that has parameters
elif word in actions and not actions[word] == "" and found == False:
ekasana = word
found = True
# Check for parameters
elif not ekasana == "" and found == True:
for n in actions[ekasana]:
if n == word:
par = word
try:
getattr(commands.Commands, ekasana)(self, par)
except:
print(self.errorcode)
else:
print("Command not found")
self.getCommand()
def mainInterface(self, v, logo):
os.system('cls' if os.name == 'nt' else 'clear')
if logo == 1:
print(self.logo1+"v "+str(v)+"\n By Dudecorn")
else:
print(self.logo2+"v "+str(v)+"\n By Dudecorn")
self.getCommand()
And here's the main file
import test
import random
def main():
m = test.MainClass()
m.mainInterface(2.0, random.randint(1,2))
main()
So, when you run the code and first input 'clear' and then q the if statement won't execute. And I wonder why. I also noticed that if you remove try and except from first if statement after loop the code works perfectly. I could remove them but it wouldn't answer my question, why isn't the code working. Also removing try and except from the file should not have any effect on how the first if statement executes, as it comes up later in the code.
Sorry about bad english as it isn't my main language, and thank you for your answers. Also I want to apologize for that huge mess in the code.
I am not sure if this is the answer that you are looking for, but it may be useful to check.
From the code below,
def main():
m = test.MainClass()
m.mainInterface(2.0, random.randint(1,2))
main()
, I see that by running main(), you also run the m.mainInterface function.
Now..you may want to check this :
The method mainInterface will eventually call the method getCommand, which will eventually call checkCommand, which..will encounter the try block in the for word in actions loop, and inside this try block..there is a calling of mainInterface again..so this process will be keep repeating.

jupyter notebook not executing codes

I starting learning python recently and so far no problem. Yesterday, the jupyter notebook stopped executing code. I have searched online,restarted the kernel, restarted my windows machine and tried to find a way to understand what it is doing so that I can continue, but I have not found a the solution or the reason that my code is not being executed anymore. I am running my code on a windows machine,chrome on windows. I did not intall the jupyter on my machine. I running it off the azure network.
Please help.
Thanks,
David
The program was an is still in 'code' mode. To execute, we are told to execute via "ctrl + enter". I had done that for the last 3 weeks without problem till now.
import os
string_container = ""
add_container = 0
def adding_report(integerToAdd):
Total = 0
Total = Total + integerToadd
# add_container = 0
while True:
a = input("Input a number: ")
if a.digit():
string_container += a + "\n"
add_container += int(a)
else:
if a == 'A':
print(Add_container)
else:
if a == 'T':
print(string_container)
else:
if a=="q":
os._exit(0)
else:
print("invalid input")
I think i got it. If you write like this, then you can run it for the first time. But from the second time it will not be executed. Because jupyter only clear that code block output, but do not release the while loop.
while True:
a = input("Input a number: ")
if a.isdigit():
string_container += a + "\n"
add_container += int(a)
else:
if a == 'A':
print(Add_container)
else:
if a == 'T':
print(string_container)
else:
if a=="q":
os._exit(0)
else:
print("invalid input")
You should put your code in a try-catch block, like this.
try:
while True:
a = input("Input a number: ")
if a.isdigit():
string_container += a + "\n"
add_container += int(a)
else:
if a == 'A':
print(Add_container)
else:
if a == 'T':
print(string_container)
else:
if a=="q":
os._exit(0)
else:
print("invalid input")
except KeyboardInterrupt:
pass
So you have to
1. Select restart the kernel and clear output
2. Add try-catch so you can use "kernel interrupt" to kill the while loop
3. Whenever you finish using this while loop, select "kernel" -> "interrupt" to kill it completely
Hope that help

Categories

Resources