断言失败:函数 imshow 中的 size.width>0 && size.height>0

Assertion failure : size.width>0 && size.height>0 in function imshow

我在 raspberry pi 上使用 opencv2 和 python。我是 python 和 opencv 的新手。我试图读取 jpeg 图像并显示图像,它显示以下错误:

/home/pi/opencv-2.4.9/modules/highgui/src/window.cpp:269: \
  error: (-215) size.width>0 &&  size.height>0 in function imshow.

代码是:

import cv2
# windows to display image
cv2.namedWindow("Image")
# read image
image = cv2.imread('home/pi/bibek/book/test_set/bbb.jpeg')
# show image
cv2.imshow("Image", image)
# exit at closing of window
cv2.waitKey(0)
cv2.destroyAllWindows()

图像加载失败(可能是因为您忘记了路径中的前导 /)。 imread 然后 returns None。将 None 传递给 imshow 会导致它尝试创建大小为 0x0 的 window,但失败了。

cv 中糟糕的错误处理可能归因于它在 C++ 实现上的包装层非常薄(在错误时返回 NULL 是一种常见的做法)。

在 Rpi 3 中使用 Raspbian 时,我在尝试读取二维码时遇到了同样的问题。错误是因为 cv2 无法读取图像。如果使用 png 图片安装 pypng 模块。

sudo pip install pypng

这是导致问题的路径,我遇到了同样的问题,但是当我提供图像的完整路径时,它运行良好。

导致此错误的原因之一是指定路径中没有文件。因此,一个好的做法是像这样验证路径(如果您使用的是基于 linux 的机器):

ls <path-provided-in-imread-function>

如果路径不正确或文件丢失,您将得到一个错误。

就我而言,我忘记将终端的工作目录更改为代码+testImage 的工作目录。因此,它无法在那里找到图像。

最后,这对我有用:

我将图像和 Python 文件保存在桌面上。我把我的cmd目录改成了它,

cd Desktop

然后检查我的文件:

ls

这是我的有效代码:

import cv2
import numpy as np

im = cv2.imread('unnamed.jpg')
#Display the image
cv2.imshow('im',im)
cv2.waitKey(2000) #Milliseconds

在读取图像文件时,指定颜色选项应该可以解决这个问题, 例如:

image=cv2.imread('img.jpg',cv2.IMREAD_COLOR)

添加 cv2.IMREAD_COLOR 应该可以解决这个问题

在指定文件地址的代码中使用 r
例如:

import cv2
img = cv2.imread(r'D:\Study\Git\OpenCV\resources\lena.png')
cv2.imshow('output', img)
cv2.waitKey(0)

r 代表“原始”,将导致字符串中的反斜杠被解释为实际反斜杠而不是特殊字符。

这个问题发生在我刚刚写图片扩展名失败的时候。
请检查您是否忘记写扩展名或图像完整路径的任何其他部分。

请记住,无论您是使用 OpenCV 还是 Mathplotlib 打印图像,都需要扩展名。

我也遇到了类似的错误,所以我没有提出新问题,而是认为将所有问题都收集在这里可能是个好主意,因为已经有一些有用的答案...

我的代码(Python中使用OpenCV打开视频的教科书代码):

import cv2 as cv
import os

path = 'C:/Users/username/Google Drive/Master/THESIS/uva_nemo_db/videos/'
os.chdir(path)
video_file = '001_deliberate_smile_2.mp4'
cap = cv.VideoCapture(video_file) 


if not cap.isOpened():
    print("Error opening Video File.")

while True:
    # Capture frame-by-frame
    ret, frame = cap.read()
    cv.imshow('frame',frame)

    if cv.waitKey(1) & 0xFF == ord('q'):
        break

    # if frame is read correctly, ret is True
    if not ret:
        print("Can't retrieve frame - stream may have ended. Exiting..")
        break

# When everything done, release the capture
cap.release()
cv.destroyAllWindows()

让我目瞪口呆的原因是我遇到了同样的错误 - 但是 - 视频实际播放了......当 运行 代码时 Python 解释器打开了一个实例Python 运行 视频。一旦视频结束,它就会跳出循环,关闭视频并抛出错误:

Traceback (most recent call last): File "C:/Users/username/Documents/smile-main/video-testing.py", line 24, in cv.imshow('frame',frame) cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\pip-req-build-wwma2wne\opencv\modules\highgui\src\window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'

如有任何意见,我将不胜感激!

**

编辑:我是如何修复我的错误的!

**

我将代码封装在 try/except 中,如下所示:

# Import required libraries
import cv2 as cv
import os

path = 'C:/Users/username/Google Drive/Master/THESIS/uva_nemo_db/videos/'
# test_path = 'C:/Users/username/Downloads'
os.chdir(path)
os.getcwd()
video_file = '001_deliberate_smile_2.mp4'

cap = cv.VideoCapture(video_file) #cap for "Video Capture Object"
   

if not cap.isOpened():
    print("Error opening Video File.")
try:
    while True:
        # Capture frame-by-frame
        ret, frame = cap.read()
        cv.imshow('frame',frame)

        if cv.waitKey(1) & 0xFF == ord('q'):
            break

        # if frame is read correctly, ret is True
        if not ret:
            print("Can't retrieve frame - stream may have ended. Exiting..")
            break
except:
    print("Video has ended.")


# When everything done, release the capture
cap.release()
cv.destroyAllWindows()

我仍然很感激任何关于为什么即使视频播放正常也会弹出这个错误,以及为什么 try/except 消除它的任何意见。

谢谢!

我用这段代码解决了

    os.chdir(f"{folder_path}")

因为图片没有加载。对我来说 VScode 相对路径是个问题,但是从 VSCode 本身复制文件路径后问题就解决了。

我在 VSCode 上也遇到了同样的问题。在 Notepad++ 上尝试了 运行 相同的代码,它成功了。要在 VSCode 上解决此问题,请不要忘记在左侧窗格中打开您正在使用的文件夹。这解决了我的问题。