I want to do face-detection using OpenCV2 in ros. I use cv_bridge.
Under is face-detection code.
#include "ros/ros.h"
#include "image_transport/image_transport.h"
#include "cv_bridge/cv_bridge.h"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/objdetect/objdetect.hpp"
class MyCvPkg
{
image_transport::Subscriber img_sub_;
image_transport::ImageTransport it_;
void imageCallback(const sensor_msgs::ImageConstPtr &msg) {
ROS_INFO("Received image");
cv::Mat in_img = cv_bridge::toCvCopy(msg,"bgra8")->image;
cv::Mat face_img =in_img.clone();
//write opencv code
double scale = 4.0;
cv::Mat gray, smallImg(cv::saturate_cast<int>(face_img.rows/scale), cv::saturate_cast<int>(face_img.cols/scale), CV_8UC1);
// グレースケール画像に変換
cv::cvtColor(face_img, gray, CV_BGR2GRAY);
// 処理時間短縮のために画像を縮小
cv::resize(gray, smallImg, smallImg.size(), 0, 0, cv::INTER_LINEAR);
cv::equalizeHist( smallImg, smallImg);
// 分類器の読み込み
std::string cascadeName = "./haarcascade_frontalface_alt.xml"; // Haar-like
//std::string cascadeName = "./lbpcascade_frontalface.xml"; // LBP
cv::CascadeClassifier cascade;
cascade = cv::CascadeClassifier("haarcascade_frontalface_alt.xml");
if (cascade.empty()) {
std::cerr << "cannot load cascade file" << std::endl;
}
//if(!cascade.load(cascadeName))
//return -1;
std::vector<cv::Rect> faces;
// マルチスケール(顔)探索
// 画像,出力矩形,縮小スケール,最低矩形数,(フラグ),最小矩形
cascade.detectMultiScale(smallImg, faces,
1.1, 2,
CV_HAAR_SCALE_IMAGE
,
cv::Size(30, 30));
// 結果の描画
std::vector<cv::Rect>::const_iterator r = faces.begin();
for(; r != faces.end(); ++r) {
cv::Point center;
int radius;
center.x = cv::saturate_cast<int>((r->x + r->width*0.5)*scale);
center.y = cv::saturate_cast<int>((r->y + r->height*0.5)*scale);
radius = cv::saturate_cast<int>((r->width + r->height)*0.25*scale);
cv::circle( face_img, center, radius, cv::Scalar(80,80,255), 3, 8, 0 );
}
cv::imshow("window", face_img);//画像を表示.
cv::waitKey(1);
//write opencv code
}
public:
MyCvPkg(ros::NodeHandle nh = ros::NodeHandle()) : it_(nh)
{
img_sub_ = it_.subscribe("image", 3, &MyCvPkg::imageCallback, this);
cv::namedWindow("Fast", 1);
}
};
int main (int argc, char **argv)
{
ros::init(argc, argv, "my_cv_pkg_node");
MyCvPkg mcp;
ros::spin();
}
cannot load cascade file OpenCV Error: Assertion failed (!empty()) in detectMultiScale, file /tmp/binarydeb/ros-kinetic-opencv3-3.2.0/modules /objdetect/src/cascadedetect.cpp, line 1681
terminate called after throwing an instance of 'cv::Exception' what(): /tmp/binarydeb/ros-kinetic-opencv3-3.2.0/modules/objdetect/src/cascadedetect.cpp:1681: error: (-215) !empty() in function detectMultiScale
Cascade file cannot be loaded. Please tell me how to solve above error.
Originally posted by sekken on ROS Answers with karma: 1 on 2017-12-06
Post score: 0