【问题标题】:Attaching two separate Python codes附加两个单独的 Python 代码
【发布时间】:2017-08-10 17:21:36
【问题描述】:

我有两个代码:第一个从实时提要中检测人脸,第二个从网络摄像头捕获图像。

我想将这些代码附加到一个 Python 文件中,以便首先检测到人脸,然后只为人脸捕获图像。

以下是代码:

抓拍人脸:

import cv2
video_capture = cv2.VideoCapture(0)

# Capture frame
ret, frame = video_capture.read()

# Write frame in file
cv2.imwrite('image.jpg', frame)

# When everything is done, release the capture
video_capture.release()

检测人脸:

import cv2
import sys

faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

video_capture = cv2.VideoCapture(0)

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

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

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=2.0,
        minNeighbors=5,
        minSize=(30, 30),
        flags=cv2.cv.CV_HAAR_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)

    # Display the resulting frame
    cv2.imshow('Video', frame)

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

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

我希望这两个脚本在一个脚本中协同工作。

问候

【问题讨论】:

  • 抱歉,Stack Overflow 不是代码编写服务。你的组合代码是什么,你到底遇到了什么问题?

标签: python python-2.7 opencv image-processing


【解决方案1】:

你已经接近了!只需在找到面 x,y 位置的帧阵列上进行切片。另外,如果您想保存灰色图像,请将框架替换为灰色。

仅保存来自网络摄像头的面孔(彩色)

import cv2
import sys

faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

video_capture = cv2.VideoCapture(0)

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

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

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=2.0,
        minNeighbors=5,
        minSize=(30, 30),
        flags = 0
        #flags=cv2.cv.CV_HAAR_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)

    # Display the resulting frame
    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        # Write frame in file
        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)        
            cv2.imwrite('only_face.jpg', frame[y:y+h,x:x+w])
        break

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

正如@Antti Haapala 所说,不要只要求做某事ASAP。告诉我们您尝试了哪种方式以及您面临的挑战。

【讨论】:

    猜你喜欢
    • 2015-03-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    相关资源
    最近更新 更多