OpenCV - 检测后突出显示口区域

时间:2017-03-01 09:15:36

标签: python-2.7 opencv

我想只提取我的代码检测到的嘴的矩形部分我该怎么做:

import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml')
mouth_cascade = cv2.CascadeClassifier('/usr/local/share/OpenCV/haarcascades/haarcascade_smile.xml')
img = cv2.imread('Images/image_0033.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)
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]
    mouth = mouth_cascade.detectMultiScale(roi_gray,2.0,25)
    for (ex,ey,ew,eh) in mouth:
        cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),3)

cv2.imshow('img',nwimg)
cv2.waitKey(0)
cv2.destroyAllWindows()

如代码中所示,我只想提取矩形口区域,我使用了var = img[y:y+h,x:x+w]之类的命令,但这没有用。

1 个答案:

答案 0 :(得分:1)

很简单,替换这一行:

cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),3)

cv2.rectangle(img,(ex,ey),(ex+ew,ey+eh),(0,255,0),3)

并显示以下内容:

cv2.imshow('Detected Mouth',img)

通过这种方式,您将在嘴上画一个矩形。

修改

您可以使用numpy操作裁剪您感兴趣的区域(在本例中为嘴巴),如下所示:

crop_img = img[ey:ey+eh, ex:ex+ew]
cv2.imshow('Cropped Mouth',crop_img)

这就是我得到的:

示例1:

enter image description here

enter image description here

示例2:

enter image description here

enter image description here