Python OpenCV 断言失败错误:(-215) scn == 3 || 函数 cv::cvtColor 中的 scn == 4 交替工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24300644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:24:17  来源:igfitidea点击:

OpenCV Assertion Failed error: (-215) scn == 3 || scn == 4 in function cv::cvtColor works ALTERNATE times

pythonopencvcomputer-vision

提问by naiveDeveloper

I am a beginner in Python and OpenCV. I am trying out a piece of code which takes an input image from the webcam. The following is the piece of code.

我是 Python 和 OpenCV 的初学者。我正在尝试一段从网络摄像头获取输入图像的代码。下面是一段代码。

cam = create_capture(video_src, fallback='synth:bg=../cpp/lena.jpg:noise=0.05')    
while True:
    ret, img = cam.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.equalizeHist(gray)

    rects = detect(gray, cascade)
    vis = img.copy()
    draw_rects(vis, rects, (0, 255, 0))
    for x1, y1, x2, y2 in rects:
        roi = gray[y1:y2, x1:x2]
        vis_roi = vis[y1:y2, x1:x2]
        subrects = detect(roi.copy(), nested)
        draw_rects(vis_roi, subrects, (255, 0, 0))
    dt = clock() - t

    draw_str(vis, (20, 20), 'time: %.1f ms' % (dt*1000))

    cv2.imshow('facedetect', vis)
    if 0xFF & cv2.waitKey(5) == 27:
        break

    cv2.setMouseCallback('facedetect',capture_image)

cv2.destroyAllWindows()

I am using both both Python 2.7 ans Python 3.4 to execute this. In both I face a strange problem. The code gives an assertion Error like this

我同时使用 Python 2.7 和 Python 3.4 来执行此操作。在两者中,我都面临一个奇怪的问题。代码给出了这样的断言错误

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cv::cvtColor, file ........\opencv\modules\imgproc\src\color.cpp, line 3737 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.error: ........\opencv\modules\imgproc\src\color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor

OpenCV 错误:断言失败 (scn == 3 || scn == 4) in cv::cvtColor, file ........\opencv\modules\imgproc\src\color.cpp, line 3737 gray = cv2 .cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.error: ........\opencv\modules\imgproc\src\color.cpp:3737: 错误: (-215) scn == 3 || 函数 cv::cvtColor 中的 scn == 4

but it happens only on every ALTERNATE time of running. What might be the issue? I read from other posts that this error occurs when cv2.cvtColortries to convert an empty image which does not have 3 or 4 channels. This happens usually when a wrong path is specified. For my case, since it is working fine EVERY ALTERNATE time, the source cannot be wrong. Please help!!

但它只在每次交替运行时发生。可能是什么问题?我从其他帖子中了解到,当cv2.cvtColor尝试转换没有 3 或 4 个通道的空图像时会发生此错误。这通常发生在指定了错误的路径时。就我而言,由于它每次都可以正常工作,因此来源不会错。请帮忙!!

采纳答案by DrV

At least I do not find any major problem in your code, i.e. "should work". The problem seems to be in the camera driver. Cameras are different, and camera drivers are different (a.k.a. buggy).

至少我在您的代码中没有发现任何重大问题,即“应该可以”。问题似乎出在相机驱动程序中。相机不同,相机驱动程序不同(又名越野车)。

Unfortunately, debugging the camera driver is not a very easy mission. The odd behaviour is most likely bound to the specific camera, operating system, OpenCV, and camera driver version. It is not very likely the driver can be fixed. Just try to keep everything up to date.

不幸的是,调试相机驱动程序并不是一件容易的事。奇怪的行为很可能与特定的相机、操作系统、OpenCV 和相机驱动程序版本有关。不太可能修复驱动程序。尽量让一切保持最新。

However, as your camera can capture every second image, there are things to do.

但是,由于您的相机可以捕捉每一秒的图像,因此还有很多事情要做。

First, verify that the problem really is in the camera driver by replacing:

首先,通过替换以下内容来验证问题确实出在相机驱动程序中:

cam = create_capture(video_src, fallback='synth:bg=../cpp/lena.jpg:noise=0.05')

by

经过

cam = create_capture('synth:bg=../cpp/lena.jpg:noise=0.05')

As is probably evident form the code, this forces the camera to be simulated. Function create_captureis only a wrapper around VideoCaptureto provide this functionality. If your code runs fine with this, the problem is in the video driver.

从代码中可能很明显,这会强制模拟相机。函数create_capture只是VideoCapture提供此功能的包装器。如果您的代码运行良好,则问题出在视频驱动程序中。

After verifying that, you could try to run the following code:

验证后,您可以尝试运行以下代码:

import cv2

cam = cv2.VideoCapture(0)
cam.open(0)
results = [ cam.read()[0] for i in range(100) ]
print results

This should create a list of 100 Trues, and the process should take a few seconds, as the camera should capture 100 consecutive images.

这应该创建一个包含 100 个 Trues 的列表,该过程应该需要几秒钟,因为相机应该连续捕获 100 张图像。

In your code you do not seem to use the first value in the return tuple of cam.read(retin your code). It is Trueif the image is really captured. Also, cam.readshould block until there is an image available, no need to add any delays.

在您的代码中,您似乎没有使用cam.read(ret在您的代码中)的返回元组中的第一个值。它是True图像是否真正抓住。此外,cam.read应该阻塞直到有可用的图像,不需要添加任何延迟。

Most probably you will get a list [True, False, True, False, ...]because the video driver does something odd. There is no beautiful way to fix this, but there is an ugly one. Replace your capture line by:

很可能你会得到一个列表,[True, False, True, False, ...]因为视频驱动程序做了一些奇怪的事情。没有漂亮的方法来解决这个问题,但有一个丑陋的方法。将您的捕获线替换为:

# max. 10 retries
for i in range (10):
    ret, img = cam.read()
    if ret:
        break
else:
    # capture failed even after 10 tries
    raise MyExceptiom("Video driver does not like me.")

Of course, the driver may be so broken that you have to release and reopen it once in a while. Even uglier but doable, as well.

当然,驱动程序可能已损坏,您必须不时释放并重新打开它。甚至更丑,但也可行。

Summary: "Most probably it cannot be cured, it does not kill you, and there are medicines to alleviate the symptoms."

总结:“很可能它无法治愈,它不会杀死你,并且有药物可以缓解症状。”

回答by Maddoxx

Use a time.sleep(2)before entering the while loop or cap.read(). This time will help your camera to spool up.

time.sleep(2)在进入 while 循环之前使用 a或cap.read()。这一次将帮助您的相机绕线。