2

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:

sample image

second sample image

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()
Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
GOODTOAD
  • 77
  • 1
  • 5
  • I don't understand about "crash" that you mentioned. is it Not Responding? or just infinitie loop? – Rizquuula Aug 03 '21 at 09:17
  • Rizquuula, when I run the program it shows the square, my cursor shows the loading symbol, then it says "python is not responding" and the console shows "program exited with code: -805306369" – GOODTOAD Aug 03 '21 at 09:31
  • 1
    The following link might help you https://stackoverflow.com/questions/22274789/cv2-imshow-function-is-opening-a-window-that-always-says-not-responding-pyth – Rinshan Kolayil Aug 03 '21 at 09:39
  • Try add `cv2.waitKey(0)` below your `cv2.imshow()`. It will show your image, but will begin `not responding` again. If you need to run both process, use threading. https://realpython.com/intro-to-python-threading/ – Rizquuula Aug 03 '21 at 09:55

2 Answers2

2

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.

iGian
  • 11,023
  • 3
  • 21
  • 36
1

I've had an error like this before where opencv would not open and have been successful in a few ways to solve it.

  1. 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()
    
  2. Install opencv-contrib-python.

    Try installing it with the command pip3 install opencv-contrib-python==4.4.0.46.

TerminalFlow
  • 230
  • 2
  • 11