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

**URL:** <https://forum.opencv.org/t/why-do-i-get-the-following-error-after-and-hour-of-operation-cv2-error-215-assertion-failed-src-empty-in-function-cvtcolor/7586>\
**Category:** Python\
**Tags:** videoio\
**Created:** [February 15, 2022, 7:07pm UTC](https://forum.opencv.org/t/why-do-i-get-the-following-error-after-and-hour-of-operation-cv2-error-215-assertion-failed-src-empty-in-function-cvtcolor/7586 "2022-02-15T19:07:40Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![Harry\_Hobson](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/harry_hobson/32/901_2.png) [@Harry\_Hobson](https://forum.opencv.org/u/Harry_Hobson)\
**Post date:** [February 15, 2022, 7:07pm UTC](https://forum.opencv.org/t/why-do-i-get-the-following-error-after-and-hour-of-operation-cv2-error-215-assertion-failed-src-empty-in-function-cvtcolor/7586/1 "2022-02-15T19:07:40Z")

</div>

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

```nohighlight

```

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

```

```auto
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.

```auto

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

---

<div class="post-metadata">

**Author:** ![Steve\_in\_Denver](https://avatars.discourse-cdn.com/v4/letter/s/eada6e/32.png) [@Steve\_in\_Denver](https://forum.opencv.org/u/Steve_in_Denver)\
**Post date:** [February 15, 2022, 8:42pm UTC](https://forum.opencv.org/t/why-do-i-get-the-following-error-after-and-hour-of-operation-cv2-error-215-assertion-failed-src-empty-in-function-cvtcolor/7586/2 "2022-02-15T20:42:49Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![crackwitz](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/crackwitz/32/14_2.png) [@crackwitz](https://forum.opencv.org/u/crackwitz)\
**Post date:** [February 15, 2022, 11:24pm UTC](https://forum.opencv.org/t/why-do-i-get-the-following-error-after-and-hour-of-operation-cv2-error-215-assertion-failed-src-empty-in-function-cvtcolor/7586/3 "2022-02-15T23:24:32Z")

</div>

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

same question:

> <https://stackoverflow.com/questions/71122785/why-do-i-get-the-following-error-after-and-hour-of-operation-cv2-error-215ass>

---

<div class="post-metadata">

**Author:** ![Harry\_Hobson](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/harry_hobson/32/901_2.png) [@Harry\_Hobson](https://forum.opencv.org/u/Harry_Hobson)\
**Post date:** [February 16, 2022, 8:00am UTC](https://forum.opencv.org/t/why-do-i-get-the-following-error-after-and-hour-of-operation-cv2-error-215-assertion-failed-src-empty-in-function-cvtcolor/7586/4 "2022-02-16T08:00:23Z")

</div>

My apologies, I am doing that now.

---

<div class="post-metadata">

**Author:** ![Harry\_Hobson](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/harry_hobson/32/901_2.png) [@Harry\_Hobson](https://forum.opencv.org/u/Harry_Hobson)\
**Post date:** [February 16, 2022, 8:03am UTC](https://forum.opencv.org/t/why-do-i-get-the-following-error-after-and-hour-of-operation-cv2-error-215-assertion-failed-src-empty-in-function-cvtcolor/7586/5 "2022-02-16T08:03:51Z")

</div>

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:

```auto

 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)

```

---

<div class="post-metadata">

**Author:** ![crackwitz](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.opencv.org/crackwitz/32/14_2.png) [@crackwitz](https://forum.opencv.org/u/crackwitz)\
**Post date:** [February 16, 2022, 11:18am UTC](https://forum.opencv.org/t/why-do-i-get-the-following-error-after-and-hour-of-operation-cv2-error-215-assertion-failed-src-empty-in-function-cvtcolor/7586/6 "2022-02-16T11:18:58Z")

</div>

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.
