cv2.imshow() 在 PyCharm (MacOS) 中无法正常工作

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

环境:

这段简单的代码 运行 没有错误;但是,没有生成图像,也没有显示任何内容,我不得不手动停止代码并中断它退出,否则它似乎永远 运行 ?这个完全相同的代码曾经在我的 windows 笔记本电脑上运行良好。有什么线索吗?代码:

import cv2

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

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

试试这个代码

首先,试试你能不能创建一个window。

import cv2

cv2.namedWindow('displaymywindows', cv2.WINDOW_NORMAL)
  • 来自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.

然后加载读取并加载您的图像:

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

waitKey(0)表示等到用户按下一个键。

已更新(添加了错误处理)


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()

更新后 Xcode 一切正常。

在 Ubuntu 18.04 和 Anaconda 环境下,我收到 Pycharm as

的错误

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

pip install opencv-python

外,pip install opencv-python-headless 已解决