[python] OpenCV !_src.empty() in function 'cvtColor' error

I am trying to do a basic colour conversion in python however I can't seem to get past the below error. I have re-installed python, opencv and tried on both python 3.4.3 (latest) and python 2.7 (which is on my Mac).

I installed opencv using python's package manager opencv-python.

Here is the code that fails:

frame = cv2.imread('frames/frame%d.tiff' % count)
frame_HSV= cv2.cvtColor(frame,cv2.COLOR_RGB2HSV)

This is the error message:

cv2.error: OpenCV(3.4.3) /Users/travis/build/skvark/opencv-python/opencv/modules/imgproc/src/color.cpp:181: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'

This question is related to python opencv

The answer is


I had the same problem and it turned out that my image names included special characters (e.g. château.jpg), which could not bet handled by cv2.imread. My solution was to make a temporary copy of the file, renaming it e.g. temp.jpg, which could be loaded by cv2.imread without any problems.

Note: I did not check the performance of shutil.copy2 vice versa other options. So probably there is a better/faster solution to make a temporary copy.

import shutil, sys, os, dlib, glob, cv2

for f in glob.glob(os.path.join(myfolder_path, "*.jpg")):
    shutil.copy2(f, myfolder_path + 'temp.jpg')
    img = cv2.imread(myfolder_path + 'temp.jpg')
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    os.remove(myfolder_path + 'temp.jpg')

If there are only few files with special characters, renaming can also be done as an exeption, e.g.

for f in glob.glob(os.path.join(myfolder_path, "*.jpg")):
    try:
        img = cv2.imread(f)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    except:
        shutil.copy2(f, myfolder_path + 'temp.jpg')
        img = cv2.imread(myfolder_path + 'temp.jpg')
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        os.remove(myfolder_path + 'temp.jpg')

Another thing which might be causing this is a 'weird' symbol in your file and directory names. All umlaut (äöå) and other (éóâ etc) characters should be removed from the file and folder names. I've had this same issue sometimes because of these characters.


If the path is correct and the name of the image is OK, but you are still getting the error

use:

from skimage import io

img = io.imread(file_path)

instead of:

cv2.imread(file_path)

The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ).


The solution os to ad './' before the name of image before reading it...


In my case it was a permission issue. I had to:

  • chmod a+wrx the image,

then it worked.


If anyone is experiencing this same problem when reading a frame from a webcam [with code similar to "frame = cv2.VideoCapture(0)"] and work in Jupyter Notebook, you may try:

  1. ensure previously tried code is not running already and restart Jupyter Notebook kernel

  2. SEPARATE code "frame = cv2.VideoCapture(0)" in separate cell on place where it is [previous code put in cell above, code under put to cell down]

  3. then run all the code above cell where is "frame = cv2.VideoCapture(0)"

  4. then try run next cell with its only code "frame = cv2.VideoCapture(0)" - AND - till you will continue in executing other cells - ENSURE - that ASTERIX on the left side of this particular cell DISAPEAR and command order number appear instead - only then continue

  5. now you can try execute the rest of your code as your camera input should not be empty anymore :-)

  6. After end, ensure you close all your program and restart kernel to prepare it for another run


If anyone is experiencing this same problem when reading a frame from a webcam:

Verify if your webcam is being used on another task and close it. This wil solve the problem.

I spent some time with this error when I realized my camera was online in a google hangouts group. Also, Make sure your webcam drivers are up to date


  • Most probably there is an error in loading the image, try checking directory again.
  • Print the image to confirm if it actually loaded or not

I've been in same situation as well, and My case was because of the Korean letter in the path...

After I remove Korean letters from the folder name, it works.

OR put

[#-*- coding:utf-8 -*-]

(except [ ] at the edge)

or something like that in the first line to make python understand Korean or your language or etc. then it will work even if there is some Koreans in the path in my case.

So the things is, it seems like there is something about path or the letter. People who answered are saying similar things. Hope you guys solve it!


In my case, the image was incorrectly named. Check if the image exists and try

import numpy as np
import cv2

img = cv2.imread('image.png', 0)
cv2.imshow('image', img)

must please see guys that the error is in the cv2.imread() .Give the right path of the image. and firstly, see if your system loads the image or not. this can be checked first by simple load of image using cv2.imread(). after that ,see this code for the face detection

import numpy as np
import cv2

cascPath = "/Users/mayurgupta/opt/anaconda3/lib/python3.7/site-   packages/cv2/data/haarcascade_frontalface_default.xml"

eyePath = "/Users/mayurgupta/opt/anaconda3/lib/python3.7/site-packages/cv2/data/haarcascade_eye.xml"

smilePath = "/Users/mayurgupta/opt/anaconda3/lib/python3.7/site-packages/cv2/data/haarcascade_smile.xml"

face_cascade = cv2.CascadeClassifier(cascPath)
eye_cascade = cv2.CascadeClassifier(eyePath)
smile_cascade = cv2.CascadeClassifier(smilePath)

img = cv2.imread('WhatsApp Image 2020-04-04 at 8.43.18 PM.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
    img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
    eyes = eye_cascade.detectMultiScale(roi_gray)
    for (ex,ey,ew,eh) in eyes:
        cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Here, cascPath ,eyePath ,smilePath should have the right actual path that's picked up from lib/python3.7/site-packages/cv2/data here this path should be to picked up the haarcascade files


Your code can't find the figure or the name of your figure named the by error message. Solution:

import cv2
import numpy as np 
import matplotlib.pyplot as plt 
img=cv2.imread('??.jpg')#solution:img=cv2.imread('haha.jpg')
print(img)

I kept getting this error too:

Traceback (most recent call last):
  File "face_detector.py", line 6, in <module>
    gray_img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor

My cv2.cvtColor(...) was working fine with \photo.jpg but not with \news.jpg. For me, I finally realized that when working on Windows with python, those escape characters will get you every time!! So my "bad" photo was being escaped because of the file name beginning with "n". Python took the \n as an escape character and OpenCV couldn't find the file!

Solution:
Preface file names in Windows python with r"...\...\" as in

cv2.imread(r".\images\news.jpg")

Check whether its the jpg, png, bmp file that you are providing and write the extension accordingly.