Python 打开 cv 错误:(-215) scn == 3 || 函数 cvtColor 中的 scn == 4

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30506126/
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 08:33:06  来源:igfitidea点击:

open cv error: (-215) scn == 3 || scn == 4 in function cvtColor

pythonopencvphoto

提问by arthurckl

I'm currently in Ubuntu 14.04, using python 2.7 and cv2.

我目前在 Ubuntu 14.04 中,使用 python 2.7 和 cv2。

When I run this code:

当我运行此代码时:

import numpy as np
import cv2

img = cv2.imread('2015-05-27-191152.jpg',0)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

it returns:

它返回:

 File "face_detection.py", line 11, in <module>
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: /home/arthurckl/Desktop/opencv-3.0.0-rc1/modules/imgproc/src/color.cpp:7564: error: (-215) scn == 3 || scn == 4 in function cvtColor

I already searched here and one answer said that I could be loading my photo the wrong way, because it should have 3 dimensions: rows, columns and depth.

我已经在这里搜索过,一个答案说我可能以错误的方式加载我的照片,因为它应该有 3 个维度:行、列和深度。

When I print the img.shape it returns only two numbers, so I must be doing it wrong. But I don't know the right way to load my photo.

当我打印 img.shape 时,它​​只返回两个数字,所以我一定是做错了。但我不知道加载照片的正确方法。

采纳答案by AdityaIntwala

Give the full path of image with forward slash. It solved the error for me.

用正斜杠给出图像的完整路径。它为我解决了错误。

E.g.

例如

import numpy as np
import cv2

img = cv2.imread('C:/Python34/images/2015-05-27-191152.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Also, if you give 0in second parameter while loading image using cv2.imreadthan no need to convert image using cvtColor, it is already loaded as grayscale image eg.

此外,如果您0在使用加载图像时输入第二个参数cv2.imread而不需要使用 转换图像cvtColor,则它已经作为灰度图像加载,例如。

import numpy as np
import cv2

gray = cv2.imread('C:/Python34/images/2015-05-27-191152.jpg',0)

回答by Kalarav Parmar

Please Set As Below

请设置如下

img = cv2.imread('2015-05-27-191152.jpg',1)     // Change Flag As 1 For Color Image
                                                //or O for Gray Image So It image is 
                                                //already gray

回答by Farooq Khan

First thing you should check is that whether the image exists in the root directory or not. This is mostly due to image with height = 0. Which means that cv2.imread(imageName)is not reading the image.

您应该检查的第一件事是图像是否存在于根目录中。这主要是由于高度 = 0cv2.imread(imageName)的图像。这意味着没有读取图像。

回答by Bhanu Chander

Here is what i observed when I used my own image sets in .jpgformat. In the sample script available in Opencv doc, note that it has the undistortand crop the imagelines as below:

这是我在.jpg格式中使用自己的图像集时所观察到的。在Opencv doc 中可用的示例脚本中,请注意它具有如下所示的undistortcrop the image行:

# undistort
dst = cv2.undistort(img, mtx, dist, None, newcameramtx)

# crop the image
x,y,w,h = roi
dst = dst[y:y+h, x:x+w]
cv2.imwrite('calibresult.jpg',dst)

So, when we run the code for the first time, it executes the line cv2.imwrite('calibresult.jpg',dst)saving a image calibresult.jpgin the current directory. So, when I ran the code for the next time, along with my sample image sets that I used for calibrating the camera in jpg format, the code also tried to consider this newly added image calibresult.jpgdue to which the error popped out

因此,当我们第一次运行代码时,它会执行在当前目录中cv2.imwrite('calibresult.jpg',dst)保存图像的行calibresult.jpg。因此,当我下次运行代码时,连同我用于以 jpg 格式校准相机的示例图像集,代码还尝试考虑这个新添加的图像,calibresult.jpg因为错误弹出

error: C:\builds\master_PackSlaveAddon-win64-vc12-static\opencv\modules\imgproc\src\color.cpp:7456: error: (-215) scn == 3 || scn == 4 in function cv::ipp_cvtColor

What I did was: I simply deleted that newly generated image after each run or alternatively changed the type of the image to say pngor tifftype. That solved the problem. Check if you are inputting and writing calibresultof the same type. If so, just change the type.

我所做的是:我只是在每次运行后删除了新生成的图像,或者将图像的类型更改为 saypngtifftype。那解决了问题。检查您输入和书写calibresult的类型是否相同。如果是这样,只需更改类型。

回答by supriya junghare

Only pass name of the image, no need of 0:

只传递图像的名称,不需要0

img=cv2.imread('sample.jpg')

回答by Gurkamal

img = cv2.imread('2015-05-27-191152.jpg',0)

The above line of code reads your image in grayscale color model, because of the 0 appended at the end. And if you again try to convert an already gray image to gray image it will show that error.

上面的代码行以灰度颜色模型读取您的图像,因为末尾附加了 0。如果您再次尝试将已经是灰色的图像转换为灰色图像,它将显示该错误。

So either use above style or try undermentioned code:

所以要么使用上面的样式,要么尝试下面提到的代码:

img = cv2.imread('2015-05-27-191152.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

回答by shenmeme

i think it because cv2.imreadcannot read .jpgpicture, you need to change .jpgto .png.

我认为是因为cv2.imread无法阅读.jpg图片,您需要更改.jpg.png

回答by Fran?ois Leblanc

I've had this error message show up, for completely unrelated reasons to the flags 0 or 1 mentionned in the other answers. You might be seeing it too because cv2.imreadwill noterror out if the path string you pass it is not an image:

由于与其他答案中提到的标志 0 或 1 完全无关的原因,我显示了此错误消息。你可能会看到它也因为cv2.imread不会出错,如果你通过它的路径字符串不是一个图像:

In [1]: import cv2
   ...: img = cv2.imread('asdfasdf')  # This is clearly not an image file
   ...: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
   ...:

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cv::cvtColor, file C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp, line 10638
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-4-19408d38116b> in <module>()
      1 import cv2
      2 img = cv2.imread('asdfasdf')  # This is clearly not an image file
----> 3 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

error: C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:10638: error: (-215) scn == 3 || scn == 4 in function cv::cvtColor

So you're seeing a cvtColorfailure when it's in fact a silent imreaderror. Keep that in mind next time you go wasting an hour of your life with that cryptic metaphor.

因此,cvtColor当它实际上是一个无声imread错误时,您会看到失败。下次当你用那个神秘的比喻浪费你一个小时的生命时,请记住这一点

Solution

解决方案

You might need to check that your path string represents a valid file before passing it to cv2.imread:

在将它传递给之前,您可能需要检查您的路径字符串是否代表有效文件cv2.imread

import os


def read_img(path):
    """Given a path to an image file, returns a cv2 array

    str -> np.ndarray"""
    if os.path.isfile(path):
        return cv2.imread(path)
    else:
        raise ValueError('Path provided is not a valid file: {}'.format(path))


path = '2015-05-27-191152.jpg'
img = read_img(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Written this way, your code will fail gracefully.

以这种方式编写,您的代码将优雅地失败。

回答by ehivan24

This answer if for the people experiencing the same problem trying to accessing the camera.

此答案适用于在尝试访问相机时遇到相同问题的人。

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

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

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

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

Using Linux:

使用 Linux:

if you are trying to access the camera from your computer most likely there is a permission issue, try running the python script with sudo it should fix it.

如果您尝试从计算机访问相机,很可能存在权限问题,请尝试使用 sudo 运行 python 脚本,它应该可以修复它。

sudo python python_script.py

To test if the camera is accessible run the following command.

要测试摄像头是否可访问,请运行以下命令。

ffmpeg -f v4l2 -framerate 25 -video_size 640x480 -i /dev/video0 output.mkv 

回答by Vivek Patwari

This code for those who are experiencing the same problem trying to accessing the camera could be written with a safety check.

对于在尝试访问相机时遇到相同问题的人,可以使用安全检查编写此代码。

if ret is True:
   gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
else:
   continue

OR in case you want to close the camera/ discontinue if there will be some problem with the frame itself

或者,如果您想关闭相机/如果框架本身有问题,请停止使用

if ret is True:
   gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
else:
   break

For reference https://github.com/HackerShackOfficial/AI-Smart-Mirror/issues/36

供参考https://github.com/HackerShackOfficial/AI-Smart-Mirror/issues/36