cv2.imshow() is not working properly in PyCharm (MacOS)

Viewed 6326

Environment:

  • interpreter: Python 3.9.0
  • OS: macOS Big Sur

This simple code is running fine with no errors; however, no image is produced and nothing is displayed, and I'm forced to manually stop the code and interrupt it to exit, otherwise it just seems to run forever? This exact same code used to work fine on my windows laptop. Any clue? The code:

import cv2

CV_cat = cv2.imread('Cat.jpg')
cv2.imshow('displaymywindows', CV_cat)
cv2.waitKey(1500)
4 Answers
import cv2

CV_cat = cv2.imread('Cat.jpg')
cv2.imshow('displaymywindows', CV_cat)
cv2.waitKey(0)   #wait for a keyboard input
cv2.destroyAllWindows()

try this code

With Ubuntu 18.04 and Anaconda environment I was getting the error with Pycharm as

process finished with exit code 139 (interrupted by signal 11 sigsegv)

Solved it by pip install opencv-python-headless in addition to pip install opencv-python

First, try whether you can create a window or not.

import cv2

cv2.namedWindow('displaymywindows', cv2.WINDOW_NORMAL)
  • From the documentation:

    • There is a special case where you can already create a window and load image to it later. In that case, you can specify whether window is resizable or not. It is done with the function cv2.namedWindow(). By default, the flag is cv2.WINDOW_AUTOSIZE. But if you specify flag to be cv2.WINDOW_NORMAL, you can resize window. It will be helpful when image is too large in dimension and adding track bar to windows.

Then load read and load your image:

CV_cat = cv2.imread('car.png')
cv2.imshow('displaymywindows', CV_cat)
cv2.waitKey(0)
cv2.destroyAllWindows()

waitKey(0) means wait till the user press a key.

Updated (error-handling is added)


import cv2
import sys

try:
    cv2.namedWindow('displaymywindows', cv2.WINDOW_NORMAL)
    CV_cat = cv2.imread('car.png')
    cv2.imshow('displaymywindows', CV_cat)
    cv2.waitKey(0)
except:
    e = sys.exc_info()[0]
    print("Error: {}".format(e))

cv2.destroyAllWindows()

After updating Xcode everything worked for me.

Related