简体   繁体   中英

Take a picture based on the scale of detection- Python + OpenCV

Below is my code which doing to detect the face via webcam.

import numpy as np
import cv2

face_cascade =     cv2.CascadeClassifier('C:\OpenCV2.0\data\haarcascades\haarcascade_frontalface_default.xml')


img = cv2.VideoCapture(0)

while(1):
    _,f=img.read()
    gray = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
         detect_frame = cv2.rectangle(f,(x,y),(x+w,y+h),(255,0,0),2)


    cv2.imshow('img',f)

if cv2.waitKey(25) == 27:
    break



cv2.destroyAllWindows()
img.release()

Through this code, I want to take a picture once it realizes the scale of frame changing or the person is moving. After taking the picture, It will save a picture in a file, then continue its job.

May you guys help me the way to solve this case? Thank you too much for your enthusiasm.

This is the code that I've written, what it does is that it first finds the center of the rectangle that we got through face detection. Then it compares the value of the center coordinate after a certain interval of time like 2s, if the value of pixel has changed above a certain threshold it will show that movement is detected. The code worked fine. To improve accuracy you can add more points in the condition whose change in value will indicate movement.

import numpy as np
import cv2

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

cap = cv2.VideoCapture(0)
i=1000
c=10 

while 1:
    _, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    #we will increment the value of i after every loop so that we could check value of coordinate after a certain time
    i=i+1

    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,150,10),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]

        #finding the center of the rectangle(around face)
        a=y+h/2
        b=x+w/2

        d = x + w / 2
        if i % 5 == 0:
            print (abs(a - c))
            if (abs(a-c))>9:            #change this value to calibrate
                print("Movement Detected")
            c = y + h / 2

    cv2.imshow('img',img)
    k = cv2.waitKey(30) & 0xff

    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

We needed to update value after sometime to compare for which I've used if i%5==0 where i is incremented after every loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM