python - 语法错误: invalid syntax while trying to release webcam

标签 python opencv detection face webcam-capture

我编写了一个代码,计划通过从笔记本电脑的网络摄像头捕获帧来执行面部、眼睛和微笑检测。但是,当我完成后,以下代码不会运行并返回无效语法错误。 我不知道如何解决这个问题,因为该行返回的错误与互联网上的任何地方都一样。但我仍然可能在某个地方做错了。(顺便说一句,我对 Python 很陌生!)

import cv2
import sys
import numpy as np

face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_classifier = cv2.CascadeClassifier('haarcascade_eye.xml')
smile_classifier = cv2.CascadeClassifier('haarcascade_smile.xml')

video_capture = cv2.VideoCapture(0)   

img_counter = 0

while True:
    #Capture frame by frame
    _, frame = video_capture.read()
    im_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    k = cv2.waitKey(1)

    #Detect faces, eyes and smiles in input frame
     faces = face_classifier.detectMultiScale(im_gray, 
                                              scaleFactor = 1.5, 
                                              minNeighbors = 5,
                                              minSize=(30, 30),
                                            flags=cv2.CASCADE_SCALE_IMAGE)

     eyes = eye_classifier.detectMultiScale(im_gray, 
                                            scaleFactor = 1.5,
                                            minNeighbors = 3,
                                            minSize=(10, 10),
                                            maxSize=(15,15),
                                          flags = cv2.CASCADE_SCALE_IMAGE)

     smiles = smile_classifier.detectMultiScale(im_gray,
                                                scaleFactor = 1.5,
                                                minNeighbors = 3,
                                                minSize = (5,5),
                                                maxSize = (10,15),
                                         flags = cv2.CASCADE_SCALE_IMAGE)

    # Draw a rectangle around the faces
    for x, y, w, h in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    # Draw a rectangle around the eyes
    for ex, ey, ew, eh in eyes:
        cv2.rectangle(frame, (ex, ey), (ex+ew, ey+eh), (0,0,255), 1)         

        # Draw a rectangle around the smiles    
        for fx,fy,fw,fh in smiles:
            cv2.rectangle(frame, (fx,fy), (fx+fw, fy+fh), (110,100,200), 1.5)

            # Display the resulting frame
            cv2.imshow('Our Face Detector', frame)

            if k == 27: #ESC Pressed
                break
            elif k == 32: # SPACE pressed
                img_name = "FaceDetect_webcam_{}.png".format(img_counter)
                cv2.imwrite(img_name,frame)
                print("{} saved!".format(img_name, frame)
                img_counter += 1
video_capture.release()
cv2.destroyAllWindows()

这是错误1:

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)

File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/User/Desktop/Top Secret/EE 492/ANACONDA-PYTHON-OPENCV/untitled0.py", line 69
img_counter += 1
          ^
SyntaxError: invalid syntax

这是错误2:

File "<ipython-input-21-a9c9ddf625b0>", line 64
video_capture.release()
     ^
SyntaxError: invalid syntax

最佳答案

在这一行中:

print("{} saved!".format(img_name, frame)

(如评论中所述)缺少“)”。

此外,在同一行中使用“.format()”的语法不正确,因为您在“.format”括号内给出了两个变量,即“img_name”和“frame”但 print 的“”中只有一个“{}”。所以如果你想打印两个变量的值,应该有两个“{}”。请注意,这不会引发任何错误,而只是指出它。

希望这有帮助。

编辑:

检查代码中的缩进。

之后

k = cv2.waitKey(1)

“faces =face_classifier.....”行之前有一个空格。 (我不知道这是在粘贴代码时发生的还是在您的编辑器中也是如此)

另外,我认为您不需要将此 for 循环嵌套在前一个循环中。它应该在“while循环缩进”内

for fx,fy,fw,fh in smiles: cv2.rectangle(frame, (fx,fy), (fx+fw, fy+fh), (110,100,200), 1.5)

然后将接下来的代码行也放在“while循环缩进”中

最后你的代码将如下所示:

while True:
    #Capture frame by frame
    _, frame = video_capture.read()
    im_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    k = cv2.waitKey(1)

    #Detect faces, eyes and smiles in input frame
    faces = face_classifier.detectMultiScale(im_gray, 
                                          scaleFactor = 1.5, 
                                          minNeighbors = 5,
                                          minSize=(30, 30),
                                        flags=cv2.CASCADE_SCALE_IMAGE)

    eyes = eye_classifier.detectMultiScale(im_gray, 
                                        scaleFactor = 1.5,
                                        minNeighbors = 3,
                                        minSize=(10, 10),
                                        maxSize=(15,15),
                                      flags = cv2.CASCADE_SCALE_IMAGE)

    smiles = smile_classifier.detectMultiScale(im_gray,
                                            scaleFactor = 1.5,
                                            minNeighbors = 3,
                                            minSize = (5,5),
                                            maxSize = (10,15),
                                     flags = cv2.CASCADE_SCALE_IMAGE)

    # Draw a rectangle around the faces
    for x, y, w, h in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    # Draw a rectangle around the eyes
    for ex, ey, ew, eh in eyes:
        cv2.rectangle(frame, (ex, ey), (ex+ew, ey+eh), (0,0,255), 1)         

    # Draw a rectangle around the smiles    
    for fx,fy,fw,fh in smiles:
        cv2.rectangle(frame, (fx,fy), (fx+fw, fy+fh), (110,100,200), 1.5)

    # Display the resulting frame
    cv2.imshow('Our Face Detector', frame)

    if k == 27: #ESC Pressed
        break
    elif k == 32: # SPACE pressed
        img_name = "FaceDetect_webcam_{}.png".format(img_counter)
        cv2.imwrite(img_name,frame)
        print("{} saved!".format(img_name, frame)
        img_counter += 1
video_capture.release()

cv2.destroyAllWindows()

关于python - 语法错误: invalid syntax while trying to release webcam,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58742664/

相关文章:

python - 如何对两个 wav 文件的 fft 进行卷积

python - 如何在 Databricks 笔记本中获取运行参数和 runId?

python - 如何工作 "expand cells containing lists into their own variables in pandas"

python - 使用 lxml/requests 从网页进行 TLE (Python3.6.4)

c++ - OpenCV 图像处理——C++ vs C vs Python

android - ANDROID OpenCV 中的模式识别算法 SURF、SIFT 出现异常

android - 在Android上检测麦克风状态变化以检测音频记录

python - 如何在 python 中将十六进制字符串 "\x89PNG"转换为纯文本

c++ - 二值图像的空间直方图

Delphi:检测挂起的重新启动(例如从 Windows 更新)