Home > database >  Opencv Region of Interest
Opencv Region of Interest

Time:05-18

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')

CodePudding user response:

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()

CodePudding user response:

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

Sample image taken from enter image description here

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)

enter image description here

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]

  • Related