简体   繁体   中英

Opencv Region of Interest

I have a program that detects a face when the the web cam i recording. I've created a region of interest and i want to only detect faces only within the roi. Im trying to instruct my program to operate only in that region. Have no clue how to

cap = cv2.VideoCapture(0)
Cascade_face = cv2.CascadeClassifier('C:\\Users\moham\PycharmProjects\Face\cascade\cascade.xml')
roi = cap[40:520,340:550]
while True:
    success, img = cap.read()
    imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = Cascade_face.detectMultiScale(imgGray, 1.3, 5)
    for (x, y, w, h) in faces:
        img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 3)
    cv2.imshow('face_detect', img)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyWindow('face_detect')

Try this for ROI. I do not have cascade.xml. Actually, I cannot test it.

    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]  
    cv2.imshow('face_detect',img)
    k = cv2.waitKey(30) & 0xff
    if k == 27: # press 'ESC' to quit
        break
cap.release()
cv2.destroyAllWindows()

You need to create a mask using the coordinates of the ROI.

Sample image taken from this link :

在此处输入图像描述

Code:

img = cv2.imread('crowd.jpg')
# create background to draw the mask
black = np.zeros((img.shape[0], img.shape[1]), np.uint8)
#ROI for this image: img[40:180, 130:300]
# create the mask using ROI coordinates
black = cv2.rectangle(black, (180, 40), (300, 130), 255, -1)
# masking the image 
roi = cv2.bitwise_and(img, img, mask = black)

在此处输入图像描述

Now you can perform face detection on roi . You need to incorporate the above snippet in your code accordingly.

Note: To draw rectangle, cv2.rectangle() follows (x1, y1), (x2, y2) order. But to crop an image, the order is reversed: crop_img = img[y1:x1, y2:x2]

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