4.3 基于ROS的人脸检测

启动仿真环境

roslaunch wpr_simulation wpr1_single_face.launch 

编写 cv_face_detect.cpp

#include
#include
#include
#include
#include
#include

using namespace cv;
using namespace std;

//定义分类器
static CascadeClassifier face_cascade;
static Mat frame_gray;
static vector faces;
static vector::const_iterator face_iter;

void callbackRGB(const sensor_msgs::Image msg)
{
    cv_bridge::CvImagePtr cv_ptr;
    try
    {
        cv_ptr=cv_bridge::toCvCopy(msg,sensor_msgs::image_encodings::BGR8);
    }
    catch(const std::exception& e)
    {
        ROS_ERROR("cv_bridge exception:%s",e.what());
        return;
    }

    Mat imgOriginal = cv_ptr->image;
    //将彩色照片转换为黑白图片
    cvtColor(imgOriginal,frame_gray,CV_BGR2GRAY);
    //直方图均衡化
    equalizeHist(frame_gray,frame_gray);

    //检测人脸
    face_cascade.detectMultiScale(frame_gray,faces,1.1,9,0|CASCADE_SCALE_IMAGE,Size(30,30));

    //在彩色原图标注人脸位置
    if (faces.size()>0)
    {
        for (face_iter=faces.begin();face_iter != faces.end();++face_iter)
        {
            rectangle(
                imgOriginal,
                Point(face_iter->x,face_iter->y),
                Point(face_iter->x + face_iter->width,face_iter->y + face_iter->height),
                CV_RGB(255,0,255),
                2);
        }
    }
    imshow("faces",imgOriginal);
    waitKey(1);
    
}

int main(int argc, char *argv[])
{
    ros::init(argc,argv,"cv_face_detect");

    namedWindow("faces");

    std::string strLoadFile;
    char const* home = getenv("HOME");
    strLoadFile = home;
    strLoadFile += "/catkin_ws";
    strLoadFile +="/src/wpr_simulation/config/haarcascade_frontalface_alt.xml";

    bool res =face_cascade.load(strLoadFile);
    if (res==false)
    {
        ROS_ERROR("fail to load haarcascade_frontalface_alt.xml");
        return 0;
    }
    ros::NodeHandle nh;
    ros::Subscriber rgb_sub = nh.subscribe("kinect2/qhd/image_color_rect",1,callbackRGB);
    ros::spin();
    
    return 0;
}

增加编译规则

add_executable(cv_face_detect src/cv_face_detect.cpp)
add_dependencies(cv_face_detect ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
target_link_libraries(cv_face_detect
  ${catkin_LIBRARIES} ${OpenCV_LIBS}
)

运行节点

rosrun cv_pkg cv_face_detect

可视化效果如下

4.3 基于ROS的人脸检测_第1张图片

4.3 基于ROS的人脸检测_第2张图片

 

 使用键盘让机器人动起来,以此来检测人脸检测效果

 rosrun wpr_simulation keyboard_vel_ctrl

4.3 基于ROS的人脸检测_第3张图片

你可能感兴趣的:(4.3 基于ROS的人脸检测)