programing

열린 cv 오류 : (-215) scn == 3 ||

nasanasas 2020. 9. 19. 11:23
반응형

열린 cv 오류 : (-215) scn == 3 || cvtColor 함수의 scn == 4


저는 현재 python 2.7 및 cv2를 사용하는 Ubuntu 14.04에 있습니다.

이 코드를 실행할 때 :

import numpy as np
import cv2

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

다음을 반환합니다.

 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

나는 이미 여기에서 검색했고 한 대답은 행, 열 및 깊이의 3 차원을 가져야하기 때문에 내 사진을 잘못된 방식으로로드 할 수 있다고 말했습니다.

img.shape를 인쇄하면 두 개의 숫자 만 반환되므로 잘못하고있는 것 같습니다. 하지만 내 사진을로드하는 올바른 방법을 모르겠습니다.


슬래시로 이미지의 전체 경로를 제공하십시오. 그것은 나를 위해 오류를 해결했습니다.

import numpy as np
import cv2

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

또한를 0사용하여 이미지 cv2.imread를 변환 할 필요없이 이미지를로드하는 동안 두 번째 매개 변수 를 주면 cvtColor이미 회색조 이미지로로드됩니다.

import numpy as np
import cv2

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

아래와 같이 설정하십시오

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

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

위의 코드 줄은 끝에 0이 추가 되었기 때문에 회색조 색상 모델로 이미지를 읽습니다. 그리고 이미 회색 이미지를 회색 이미지로 다시 변환하려고하면 해당 오류가 표시됩니다.

따라서 위의 스타일을 사용하거나 아래에 언급 된 코드를 사용해보십시오.

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

이미지의 이름 만 전달하고 다음은 필요하지 않습니다 0.

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

먼저 확인해야 할 것은 이미지가 루트 디렉토리에 있는지 여부입니다. 이것은 대부분 높이가 0 인 cv2.imread(imageName)이미지 때문입니다. 이는 이미지를 읽지 않음을 의미합니다 .


나는 다른 답변에서 언급 된 플래그 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 cvtColor failure when it's in fact a silent imread error. Keep that in mind next time you go wasting an hour of your life with that cryptic metaphor.

Solution

You might need to check that your path string represents a valid file before passing it to 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.


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:

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

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

The above error is the result of an invalid image name or if the file does not exists in the local directory.

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

Also if you are using the 2nd argument of cv2.imread() as '0', then it is already converted into a grayscaled image.

The difference between converting the image by passing 0 as parameter and applying the following:

img = cv2.cvtCOLOR(img, cv2.COLOR_BGR2GRAY) 

is that, in the case img = cv2.cvtCOLOR(img, cv2.COLOR_BGR2GRAY), the images are 8uC1 and 32sC1 type images.


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


Here is what i observed when I used my own image sets in .jpg format. In the sample script available in Opencv doc, note that it has the undistort and crop the image lines as below:

# 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.jpg in 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.jpg due to which the error popped out

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 png or tiff type. That solved the problem. Check if you are inputting and writing calibresult of the same type. If so, just change the type.


On OS X I realised, that while cv2.imread can deal with "filename.jpg" it can not process "file.name.jpg". Being a novice to python, I can't yet propose a solution, but as François Leblanc wrote, it is more of a silent imread error.

So it has a problem with an additional dot in the filename and propabely other signs as well, as with " " (Space) or "%" and so on.


I also found if your webcam didnt close right or something is using it, then CV2 will give this same error. I had to restart my pc to get it to work again.


The simplest solution for removing that error was running the command

cap.release()
cv2.closeAllWindows()

That worked for me and also sometimes restarting the kernel was required because of old processes running in the background.

If the image isn't in the working directory then also it wont be working for that try to place the image file in pwd in the same folder as there is code else provide the full path to the image file or folder.

To avoid this problem in future try to code with exceptional handling so that if incorrect termination happens for some random reason the capturing device would get released after the program gets over.


2015-05-27-191152.jpg << Looking back at your image format, I occasionally confused between .png and .jpg and encountered the same error.


i think it because cv2.imread cannot read .jpg picture, you need to change .jpg to .png.


Try this at line 11, worked for me.I think you're missing the parameters of function detectMultiScale()

faces = face_cascade.detectMultiScale(gray, 1.3, 5)

참고URL : https://stackoverflow.com/questions/30506126/open-cv-error-215-scn-3-scn-4-in-function-cvtcolor

반응형