MattTucker
MattTucker

Reputation: 1

CV2(cv2.imwrite)- Python keeps throwing an, "Assertion failed," error

So, I keep getting an an, "assertion failed" error if I leave in,

        cv2.imwrite('FaceRecBaseTest/' + str(sum) + '.jpeg', vid, gray[y:y+h, x:x+w])

So, naturally, I'm here to find out why. Here is there error in its full "glory:"

OpenCV Error: Assertion failed (dims == 2 && (sizes[0] == 1 || sizes[1] == 1 || sizes[0]*sizes[1] == 0)) in create, file /tmp/opencv-20170224-1869-10nlf6f/opencv-2.4.13.2/modules/core/src/matrix.cpp, line 1466 libc++abi.dylib: terminating with uncaught exception of type cv::Exception: /tmp/opencv-20170224-1869-10nlf6f/opencv-2.4.13.2/modules/core/src/matrix.cpp:1466: error: (-215) dims == 2 && (sizes[0] == 1 || sizes[1] == 1 || sizes[0]*sizes[1] == 0) in function create

Here is a copy of my code:

import cv2
import time
face_cascade = cv2. 
CascadeClassifier('haarcascade/haarcascade_frontalface_alt.xml')
video_capture = cv2.VideoCapture(0)
sum = 0
while True:
    # Captures video frame by frame
    ret, vid = video_capture.read()
    vid = cv2.resize(vid, (320, 220))
    gray = cv2.cvtColor(vid, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.1, 5)

    print str(len(faces))
    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        sum += 1
        cv2.rectangle(vid, (x, y), (x+w, y+h), (0, 255, 0), 2)
        cv2.imwrite('FaceRecBaseTest/' + str(sum) + '.jpeg', vid, gray[y:y+h, x:x+w])
        cv2.waitKey(1)
    cv2.putText(vid, "Video: " + str(time.ctime()), (0, 10), 
    cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255), 2, 8, bottomLeftOrigin = False)
    # Display the results
    if sum > 20:
        break
    cv2.imshow('Video', vid)
    cv2.waitKey(1)
video_capture.release()
cv2.destroyAllWindows()

Upvotes: 0

Views: 1991

Answers (1)

alkasm
alkasm

Reputation: 23002

You've got three arguments inside imwrite(): the filename and two images (vid and gray[y:y+h, x:x+w]). Of course, you can only pass in one image. However imwrite() can actually accept three parameters, the third being a parameters flag for quality/compression level. From the imwrite() docs:

Python: cv2.imwrite(filename, img[, params]) → retval
...
params – Format-specific save parameters encoded as pairs paramId_1, paramValue_1, paramId_2, paramValue_2, ... . The following parameters are currently supported:

Upvotes: 1

Related Questions