Why do I get the following error after and hour of operation cv2.error:(-215:Assertion failed) !src.empty() in function 'cvtColor'

Things work fine for 30 minutes to an hour, then I get the following error: ```
(-215:Assertion failed) !_src.empty() in function ‘cvtColor’



   import cv2
    import sqlite3
    from datetime import datetime
    connection = sqlite3.connect("/home/harry/interface/wildlife.db")
    cursor = connection.cursor()
    x = 1
    c = 1
    streamTarget  = ''
    def activityScan(status,c):
        sql=cursor.execute("SELECT * FROM heavenStream WHERE id = ?",(c,))
        dbstatus = sql.fetchone()
        if(dbstatus[8]!=status):
            putMoe=(status,c)
            cursor.execute("UPDATE heavenStream SET streamTime =? where id=?", putMoe)
            connection.commit()
    
    def xmlFile(c):
        row=cursor.execute("SELECT * FROM heavenStream WHERE id = ?",(c,))
        streamTarget = row.fetchone()
        return streamTarget[2]
    
    def ipAddress(c):
        row=cursor.execute("SELECT * FROM heavenStream WHERE id = ?",(c,))
        streamTarget = row.fetchone()
    def vidCapture(c):
        h=0
        face_cascade = cv2.CascadeClassifier(xmlFile(c))
        cap = cv2.VideoCapture(ipAddress(c))
      #  while 1:
        ret, img = cap.read()
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.3, 5)
        for (x, y, w, h) in faces:
            cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)
            roi_gray = gray[y:y + h, x:x + w]
            roi_color = img[y:y + h, x:x + w]
    
        if(h):
            print("active")
            activityScan("active",c)
        else:
            print("inactive")
            activityScan("inactive",c)
        cv2.imshow('img', img)
    #    if cv2.waitKey(1) & 0xFF == 27:
    #           break
    
       cap.release()
   #     cv2.destroyAllWindows()
    
    def sensorAddress(moe):
        ab = int(datetime.today().strftime('%S'))
        if (ab % 2) == 0 :
            return moe
    #       print("...")
        else:
            y = last_id() - 1 
            if(moe >= y and y % 2 == 0):
                moe = 1
                return moe 
               # print(y)
            elif(moe >= y and y % 2 !=0):
                moe = 1
                return moe 
      #          print(".. .. --")
            else:
                moe = moe + 2
                return moe 
    
    def last_id():                  ### Last ID in database
        sql = cursor.execute('SELECT max(id) FROM heavenStream')
        max_id = sql.fetchone()[0]
        return max_id 
    
    def moeValue(moe): ## Larry
        if(moe == last_id()):
            moe = 1
            return sensorAddress(moe)
        elif(moe == last_id() - 1 and moe % 2 != 0):
            moe = 1
            return sensorAddress(moe)
        elif(moe % 2 ) == 0:
            moe = moe + 1
            return sensorAddress(moe)
        else:
           moe = moe + 2
           return sensorAddress(moe)
    while True:
        row=cursor.execute("SELECT * FROM heavenStream WHERE id = ?",(x,))
        streamTarget = row.fetchone()
        if ('moe' == streamTarget[8]):
           c = moeValue(streamTarget[0])
           vidCapture(c)
        lastDBrecord = last_id()
        if(x >= lastDBrecord):
           x = 1
        else:
           x = x + 1
Things work fine for 30 minutes to an hour, then I get the following error:


active
inactive
active
active
active
inactive
active
Traceback (most recent call last):
File “interface/larry5.py”, line 93, in
vidCapture(c)
File “interface/larry5.py”, line 33, in vidCapture
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.5.4-dev) /tmp/pip-req-build-6qnmwb6g/opencv/modules/imgproc/src/color.cpp:182:
error: (-215:Assertion failed) !_src.empty() in function ‘cvtColor’
My cameras are running at 10fps with a resolution of 176x144 using IPcam on two Samsung phones. I code below uses a database to switch cameras using OpenCV.


It works fine for up to an hour then fails. I used the code from the following website, https://pythonprogramming.net/haar-cascade-face-eye-detection-python-opencv-tutorial/ , as a basis, though I only have one xml file. I am running the latest version of Linux Mint. Any comments will be much appreciated.

Check your return value (ret) or image size from cap.read(). The error you are getting is an assertion failure that is checking to make sure the source image you pass in to cvtColor() has data (it doesn’t).

So after cap.read() do something like:

if img.empty():
continue

that way you won’t try to call cvtColor when the video capture object fails to return an image.

1 Like

may I suggest that you edit your question to fix the formatting. you’ve put prose in code tags.

same question:

My apologies, I am doing that now.

Thanks so much for your comment. It was very helpful I did the following, and the has run accurately for over 6 hours without failure. I did the following:


 ret, img = cap.read()
    if(ret == True):
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.3, 5)
        for (x, y, w, h) in faces:
            cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)
            roi_gray = gray[y:y + h, x:x + w]
            roi_color = img[y:y + h, x:x + w]
        if(h):
            print("active")
            print(ret)
            activityScan("active",c)
        else:
            print("inactive")
            print(ret)
            activityScan("inactive",c)

check to make sure that only intermittently not ret. usually, once it fails, it keeps failing. some backend may have different behavior though, where, after a failed read(), the next read() may succeed again.

if read() keeps failing, you’d be in an infinite loop that does nothing.