How do I display an image according to a given Number and this number is by Random in python?

Asked

Viewed 83 times

0

import numpy as np 
import matplotlib.pyplot as plt
from PIL import Image
import cv2

def showfig(image, ucmap):
    imgplot=plt.imshow(image, ucmap)
img0 = cv2.imread("zero.jpg",0)
img1 = cv2.imread("um.jpg",0)

from random import randint  #gerar número aleatório, ou seja, randomizar número inteiro
from time import sleep 

computador = randint(0,9) #Faz o computador pensar
print('-=-' * 20) #Para definição de começo da pergunta do computador
print('Vou pensar em um número entre 0 e 9. Tente adivinhar...')
print('-=-' * 20) #Para definição de começo da pergunta do computador
jogador = int(input('Em que número eu pensei?')) #jogador tenta adivinhar
print('Processando...')
sleep(3) 

jogador = 0 
computador = 0

if jogador == computador:

    plt.figure(figsize=(5,5))
    plt.title('Imagem de Entrada')
    showfig(img0, "gray")
    print('Parabéns: você ganhou!')

else:
    print('Ganhei: Eu pensei no número {} e não {}!'.format(computador, jogador))

jogador = 1
computador = 1

if jogador == computador:

    plt.figure(figsize=(5,5))
    plt.title('Imagem de Entrada')
    showfig(img1, "gray")
    print('Parabéns: você ganhou!')

else:
    print('Ganhei: Eu pensei no número {} e não {}!'.format(computador, jogador))
  • Hi Julia, can you be more specific? Have you tried anything? Are you getting any error code as a return? I think it can be interesting to also show how is your file folder, to know if the path that is pulling the image is correct.

  • 1

    Hello. I have identified and has been corrected, thank you!

1 answer

1


Instead of using a variable for each image, use an indexable structure such as lists or dictionaries. For numbers from scratch, a list would do, but I prefer to use dictionaries, in case I need more pictures that are not numbers after:

imgs = {
    0: cv2.imread("zero.jpg", 0),
    1: cv2.imread("um.jpg", 0),
}

Then after showing the image, just use this dictionary to reference the right image according to the drawn number:

computador = randint(0, 9)
...
showfig(imgs[computador], "gray")
  • 1

    , the first method I used, the second I used similar, but it worked. Thank you!

  • 1

    @Juliaoliveira Glad you could! If my answer has solved, consider marking it as accepted, to close the question. If you want to share what you did differently, I can edit the answer to make it more complete.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.