Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Image always renders as a gray box

When I load a set of image files into a list and try to display one, it always renders as a gray box.The images are not gray boxes. The size of the image window displayed by openCV varies with the size of the actual image on file.

import cv2
import glob
import random

def loadImages(path):
    
    imdir = path
    ext = ['png', 'jpg', 'gif']    # Add image formats here
    
    files = []
    [files.extend(glob.glob(imdir + '*.' + e)) for e in ext]
    #print("files", files)
    
    images = [cv2.imread(file) for file in files]
    return images

images = loadImages("classPhotos/")
print(str(len(images)), "images loaded")
#print(images)
cv2.imshow("image", random.choice(images))
tmp = input()

The image looks like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Add this 2 lines after cv2.imshow("image", random.choice(images)) to make it work properly.

cv2.waitKey(0) 
cv2.destroyAllWindows() 
  • cv2.imshow shows the image instantly and then doesn’t show it.
  • cv2.waitKey waits for a specific time/ keeps showing the image.
    • putting 0 as an argument makes it wait infinitely unless a key is pressed.
  • cv2.destroyAllWindows() helps close the window otherwise it gets stuck.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading