网络摄像头甚至没有打开OpenCV只是打印输出

时间:2019-01-21 13:44:08

标签: python opencv

我通过遵循一些教程创建了OpenCV函数,该教程从我的摄像头捕获100帧并将其存储在我提到的路径中,但是当我尝试检查摄像头是否已与OpenCV正确集成时 我已经运行了这段代码

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

这工作得很好,我可以看到自己处于灰色框

import cv2
import numpy as np

# Load HAAR face classifier
face_classifier = cv2.CascadeClassifier('Haarcascades/haarcascade_frontalface_default.xml')

# Load functions
def face_extractor(img):
    # Function detects faces and returns the cropped face
    # If no face detected, it returns the input image

    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    faces = face_classifier.detectMultiScale(gray, 1.3, 3)

    if faces is ():
        return None

    # Crop all faces found
    for (x,y,w,h) in faces:
        cropped_face = img[y:y+h, x:x+w]

    return cropped_face

# Initialize Webcam
cap = cv2.VideoCapture(0)
# ret, frame = cap.read()
count = 0

# Collect 100 samples of your face from webcam input
while(True):

    ret, frame = cap.read()
    print(type(frame))
    print(frame.shape)
#     if ret==True:
    if face_extractor(frame) is not None:
        count += 1
        face = cv2.resize(face_extractor(frame), (200, 200))
        face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)

        # Save file in specified directory with unique name
        file_name_path = r'C:\Users\madhumani\path\\' + str(count) + '.jpg'
        cv2.imwrite(file_name_path, face)

        # Put count on images and display live count
        cv2.putText(face, str(count), (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
        cv2.imshow('Face Cropper', face)

    else:
        print("Face not found")

#     else:
#         print("no camera")
    if cv2.waitKey(1) == 13 or count == 100: #13 is the Enter Key
        break

cap.release()
cv2.destroyAllWindows()      
print("Collecting Samples Complete")

根据该教程,网络摄像头应捕获该特定人的100帧并将其存储在路径中,而只是将face not found打印为输出

以下是输出:

<type 'numpy.ndarray'>
(480L, 640L, 3L)
Face not found
<type 'numpy.ndarray'>
(480L, 640L, 3L)
Face not found
<type 'numpy.ndarray'>
(480L, 640L, 3L)
Face not found
<type 'numpy.ndarray'>
(480L, 640L, 3L)
Face not found
<type 'numpy.ndarray'>
(480L, 640L, 3L)
Face not found

1 个答案:

答案 0 :(得分:0)

您的代码正在运行,它将文件写入指定的路径。我认为您唯一缺少的是给定路径C:\Users\madhumani\path\不存在,您应该首先创建目录。

您可以通过添加以下代码来创建目录:

import os
dir = r'C:\Users\madhumani\path\\'
if not os.path.exists(dir):
    os.makedirs(dir)

或手动创建。