How to open a list of images with Opencv?

Asked

Viewed 139 times

-1

I’m trying to open images and show them on screen from a directory called 'Photos' with various images . jpg, but when the windows open they simply do not load the images and the interpreter does not return any error, it just stops working.

import cv2 as cv
from os import listdir, path
import time

path = path.dirname(path.realpath(__file__)) + "\Photos"  #Traz o caminho do diretorio atual
files = [f for f in listdir(path)]  #Armazena o nome dos arquivos numa lista
print(files) #['cat.jpg', 'cats 2.jpg', 'cats.jpg']

for file in files:
  img = cv.imread(f'Photos/{file}')
  cv.imshow(f"{file}", img)
  time.sleep(10)
  cv.destroyAllWindows()

cv.waitKey(0)

*None of these images takes up much space (the largest only has 312kbs)

Screen that should show the photo: [1]: https://i.stack.Imgur.com/pYy0P.png

2 answers

2


The problem is in the function time.sleep. This function interrupts the execution of the main thread, making the program "sleep". Consequently, the image loading on the screen is also interrupted, temporarily. You cannot see the image being loaded on the screen - at the end of the process - because after the end of the function sleep, the program already closes the window before the image is loaded.

You can do a test to prove this by removing the line of code in which the screen is destroyed. In this case, the program would create all windows, and the images would only appear after all executions of the function had been completed sleep - in other words, after the repeat loop has been completed.

cv.imshow(f"{file}", img)          # <- Cria a janela e inicia o carregamento da imagem
time.sleep(10)                     # <- Interrompe o carregamento da imagem
cv.destroyAllWindows()             # <- Destrói a tela antes da imagem ser carregada

The solution to this problem is to replace the function sleep by function cv.waitKey - because it does not interrupt the main thread - passing as argument the time in milliseconds. See below:

import cv2 as cv
from os import listdir, path
import time

path = path.dirname(path.realpath(__file__)) + "\Photos"
files = [f for f in listdir(path)]
print(files)

for file in files:
    img = cv.imread(f'Photos/{file}')
    cv.imshow(f"{file}", img)
    cv.waitKey(10000)          # 10 segundos = 10000 milissegundos.
    cv.destroyAllWindows()

0

  1. item
import cv2
from os import listdir, path
imagem = cv2.imread("lampada.png")
cv2.imshow("Original", imagem)

print "Altura (height): %d pixels" % (imagem.shape[0])
print "Largura (width): %d pixels" % (imagem.shape[1])
print "Canais (channels): %d"      % (imagem.shape[2])
    
cv2.waitKey(0)

or

  1. item
########################
# Open a file
path = "/var/www/html/"
dirs = os.listdir( path )

# This would print all the files and directories
for file in dirs:
   print file

Browser other questions tagged

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