47

I am trying to make a face tracker that combines Haar Cascade Classification with Lucas Kanade good feature detection. However, I keep getting an error that I cannot figure out what it means nor how to solve it.

Can anyone help me here?

Error:

line 110, in <module>
cv2.imshow('frame',img)
error: /build/buildd/opencv-2.4.8+dfsg1/modules/highgui/src/window.cpp:269: 
error: (-215)size.width>0 && size.height>0 in function imshow

Code:

from matplotlib import pyplot as plt
import numpy as np

import cv2

face_classifier = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')


cap = cv2.VideoCapture(0)


# params for ShiTomasi corner detection
feature_params = dict( maxCorners = 200,
                       qualityLevel = 0.01,
                       minDistance = 10,
                       blockSize = 7 )

# Parameters for lucas kanade optical flow
lk_params = dict( winSize  = (15,15),
                  maxLevel = 2,
                  criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))

# Create some random colors
color = np.random.randint(0,255,(100,3))

# Take first frame and find corners in it
ret, old_frame = cap.read()



cv2.imshow('Old_Frame', old_frame)
cv2.waitKey(0)
old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
restart = True
#while restart == True:
face = face_classifier.detectMultiScale(old_gray, 1.2, 4)

if len(face) == 0:
    print "This is empty"

for (x,y,w,h) in face:
    focused_face = old_frame[y: y+h, x: x+w]

cv2.imshow('Old_Frame', old_frame)

face_gray = cv2.cvtColor(old_frame,cv2.COLOR_BGR2GRAY)

gray = cv2.cvtColor(focused_face,cv2.COLOR_BGR2GRAY)

corners_t = cv2.goodFeaturesToTrack(gray, mask = None, **feature_params)
corners = np.int0(corners_t)

print corners

for i in corners:
    ix,iy = i.ravel()
    cv2.circle(focused_face,(ix,iy),3,255,-1)
    cv2.circle(old_frame,(x+ix,y+iy),3,255,-1)

plt.imshow(old_frame),plt.show()


# Create a mask image for drawing purposes
mask = np.zeros_like(old_frame)

while(1):
    ret,frame = cap.read()
    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # calculate optical flow
    p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, corners_t, None, **lk_params)

    # Select good points
    good_new = p1[st==1]
    good_old = corners_t[st==1]

    # draw the tracks
    print "COLORING TIME!"
    for i,(new,old) in enumerate(zip(good_new,good_old)):
        print i
        print color[i]
        a,b = new.ravel()
        c,d = old.ravel()
        mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
        frame = cv2.circle(frame,(a, b),5,color[i].tolist(),-1)
        if i == 99:
            break
    img = cv2.add(frame,mask)

    cv2.imshow('frame',img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

    # Now update the previous frame and previous points
    old_gray = frame_gray.copy()
    p0 = good_new.reshape(-1,1,2)

cv2.destroyAllWindows()
cap.release()
user3377126
  • 1,743
  • 4
  • 23
  • 38
  • 1
    this line: `cv2.imshow('Old_Frame', old_frame_resized)` where is old_frame_resized defined? – cziemba Jan 14 '15 at 21:55
  • Oh sorry, it is actually cv2.imshow('Old_Frame', old_frame). This error still exists though – user3377126 Jan 14 '15 at 22:26
  • 2
    Any idea which `imshow` is throwing the error? The error likely means the image is empty. I suggest checking the `cap.read()` return values, specifically the `ret` value for False, meaning the capture failed. – cziemba Jan 15 '15 at 14:41
  • 2
    I agree with @cziemba. I found the following in the opencv doc [(Getting Started with Videos)](http://docs.opencv.org/trunk/doc/py_tutorials/py_gui/py_video_display/py_video_display.html): cap.read() returns a bool (True/False). If frame is read correctly, it will be True. So you can check end of the video by checking this return value. Sometimes, cap may not have initialized the capture. In that case, this code shows error. You can check whether it is initialized or not by the method cap.isOpened(). If it is True, OK. Otherwise open it using cap.open(). – gfkri Jan 15 '15 at 15:26
  • I also had some problems in the past that the first few frames of VideoCapture can be empty, all null values. While reading from cameras, of course, not videos. – G. Führ Aug 22 '15 at 14:53
  • The answer to this question is covered in the following link https://stackoverflow.com/a/31342428/7951425 – A.ATLASSI Jun 06 '19 at 14:29

17 Answers17

24

This error message

error: (-215)size.width>0 && size.height>0 in function imshow

simply means that imshow() is not getting video frame from input-device. You can try using

cap = cv2.VideoCapture(1) 

instead of

cap = cv2.VideoCapture(0) 

& see if the problem still persists.

Sᴀᴍ Onᴇᴌᴀ
  • 7,491
  • 8
  • 27
  • 56
Gauranga
  • 776
  • 6
  • 15
17

I have the same problem, fix the ret in capture video

import numpy as np
import cv2

# Capture video from file
cap = cv2.VideoCapture('video1.avi')

while True:

    ret, frame = cap.read()

    if ret == True:

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        cv2.imshow('frame',gray)


        if cv2.waitKey(30) & 0xFF == ord('q'):
            break

    else:
        break

cap.release()
cv2.destroyAllWindows()
Cristian Q
  • 487
  • 3
  • 7
7

I had this problem.

Solution: Update the path of the image.

If the path contains (for example: \n or \t or \a) it adds to the corruption. Therefore, change every back-slash "\" with front-slash "/" and it will not make create error but fix the issue of reading path.

Also double check the file path/name. any typo in the name or path also gives the same error.

Ghoul Fool
  • 4,667
  • 9
  • 54
  • 100
abadymoezain
  • 71
  • 1
  • 3
5

You have to delay

Example Code:

import cv2
import numpy as np
import time

cam = cv2.VideoCapture(0)
time.sleep(2)

while True:
    ret,frame = cam.read()
    cv2.imshow('webcam', frame)
    if cv2.waitKey(1)&0xFF == ord('q'):
        break

cam.release()
cv2.destroyAllWindows()
Salih Karagoz
  • 1,766
  • 2
  • 17
  • 32
박광유
  • 51
  • 1
  • 1
4

I have also met this issue. In my case, the image path is wrong, so the img read is NoneType. After I correct the image path, I can show it without any issue.

jdhao
  • 13,374
  • 7
  • 87
  • 151
2

In these two lines:

mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)

frame = cv2.circle(frame,(a, b),5,color[i].tolist(),-1)

try instead:

cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)

cv2.circle(frame,(a, b),5,color[i].tolist(),-1)

I had the same problem and the variables were being returned empty

Paul Roub
  • 35,100
  • 27
  • 72
  • 83
Zed86M
  • 21
  • 1
1

I also met the error message in raspberry pi 3, but my solution is reload kernel of camera after search on google, hope it can help you.

sudo modprobe bcm2835-v4l2

BTW, for this error please check your camera and file path is workable or not

Ethan Kuo
  • 111
  • 1
  • 5
1

That error also shows when the video has played fine and the script will finish but that error always throws because the imshow() will get empty frames after all frames have been consumed.

That is especially the case if you are playing a short (few sec) video file and you don't notice that the video actually played on the background (behind your code editor) and after that the script ends with that error.

universality
  • 130
  • 5
0
while(cap.isOpened()):

    ret, img = cap.read()
    print img
    if img==None:   #termino los frames?
        break   #si, entonces terminar programa
    #gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    cv2.imshow('img2',img)
SiHa
  • 5,520
  • 12
  • 23
  • 37
0

cv2.circle and cv2.lines are not working. Mask and frame both are returning None. these functions (line and circle) are in opencv 3 but not in older versions.

Irum Zahra Awan
  • 246
  • 1
  • 3
  • 15
0

I use ssh to connect to remote server and have python code execute cv2.VideoCapture(0) to capture remote webcam, then encounter this error message:

error: (-215)size.width>0 && size.height>0 in function imshow

Finally, I have to grant access to /dev/video0 (which is my webcam device) with my user account and the error message was gone. Use usermod to add user into group video

usermod -a -G video user
allenyllee
  • 559
  • 1
  • 7
  • 11
0

This is a problem with space consumption or choosing the wrong camera. My suggestion in to restart kernel and clear output and run it again. It works then.

Par bas
  • 143
  • 1
  • 2
0

Although this is an old thread, I got this error as well and the solution that worked for me is not mentioned here.

Simply put, in my case the webcam was still in use on the background, as I saw the LED light being on. I have not yet been able to reproduce the issue, so I'm not sure a simple cv2.VideoCapture(0).release() would have solved it. I'll edit this post if and when I have found it out.

For me a restart of my PC solved the issue, without changing anything to the code.

JKarouta
  • 1
  • 2
0

This Error can also occur if you slice a negative point and pass it to the array. So check if you did

sivi
  • 9,048
  • 2
  • 43
  • 47
0

I was facing the same problem while trying to open images containing spaces and special characters like the following ´

So, after modifying the images names removing their spaces and special characters, everything worked perfectly.

ASRodrigo
  • 81
  • 1
  • 1
-1

Check if you have "opencv_ffmpeg330.dll" in python27 root directory or of the python version you are using. If not you will find it in "....\OpenCV\opencv\build\bin".

Choose the appropriate version and copy the dll into the root directory of your python installation and re-run the program

Jeru Luke
  • 13,413
  • 9
  • 57
  • 71
pasagar
  • 1
  • 2
-1

Simply use an image extension like .jpeg or .png.