CV2(cv2.imwrite) - Python不断抛出“断言失败”错误

时间:2017-09-08 03:49:24

标签: python opencv

所以,如果我离开,我会继续得到一个“断言失败”错误,

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

所以,很自然地,我在这里找出原因。这里有完整的“荣耀:”

的错误
  

OpenCV错误:断言失败(dims == 2&&(sizes [0] == 1 || sizes [1] == 1 || sizes [0] * sizes [1] == 0))在create中,文件/tmp/opencv-20170224-1869-10nlf6f/opencv-2.4.13.2/modules/core/src/matrix.cpp,第1466行   libc ++ abi.dylib:以cv类型的未捕获异常终止::异常:/tmp/opencv-20170224-1869-10nlf6f/opencv-2.4.13.2/modules/core/src/matrix.cpp:1466:错误:( -215)dims == 2&& (size [0] == 1 || sizes [1] == 1 || sizes [0] * sizes [1] == 0)in function create

以下是我的代码的副本:

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()

1 个答案:

答案 0 :(得分:1)

您在imwrite()内有三个参数:文件名和两个图片(vidgray[y:y+h, x:x+w])。当然,您只能传入一张图片。但是imwrite()实际上可以接受三个参数,第三个是质量/压缩级别的参数标志。来自the imwrite() docs

  

Python cv2.imwrite(filename, img[, params]) → retval
  ...
  参数 - 特定格式的保存参数,编码为paramId_1,paramValue_1,paramId_2,paramValue_2,....目前支持以下参数: