(OpenCV 人脸识别源码)LINUX下调用opencv简单识别人脸 亲身操作成功 并附上源码 C++
本人使用环境 工具与库ubuntu18.04opencv4.2.0cmake 3.10.2找个地方目录文件: mkdirprojectproject下 mkdir facedetectfacedetect 先mkdir build再创建CMakeLists.txt facedetect.cpp使用以下指令将所需要...
·
本人使用环境 工具与库 ubuntu18.04 opencv4.2.0 cmake 3.10.2
找个地方建工程文件: mkdir project
project下 mkdir facedetect
facedetect 先mkdir build 再创建CMakeLists.txt facedetect.cpp
使用以下指令将所需要的资源,复制到build底下,请确保当前路径为在build下:
所需资源为:haarcascade_frontalface_default.xml . (可以通过find 指令去查找这个资源的位置,https://blog.csdn.net/nb_zsy/article/details/104150589,指令不回的搜左边那个网址)
cp -r /usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml .
这个指令是根据我自己的环境输的,你们要按自己的路径来输指令,需要的资源就是haarcascade_frontalface_default.xml
在build底下 执行 cmake … (只有两个点,不知道为啥这里多显示一个点)
接着执行 cmake --build ./build/
成功的话你应该看到以下内容(不包括.jpg文件)
接着向build下添加自己想识别的jpg图片,执行build下的facedetect程序 ,人脸将会用绿色的框框标记。
./facedetect zsy_sister.jpg(该图片是我自己拍的)
./facedetect harris_and_wife.jpg(该图片是网上搜的)
CMakeLists.txt 代码:
#cmake need this
cmake_minimum_required(VERSION 3.1)
#Enable C++ 11
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED)
#define project name
project(detectface)
#find OpenCV
find_package(OpenCV REQUIRED)
#If package found,several variable will be set
message(STATUS "OpenCV libray status: ")
message(STATUS" config: ${OpenCV_DIR}")
message(STATUS" version: ${OpenCV_VERSION}")
message(STATUS" libraries: ${OpenCV_LIBS}")
message(STATUS" include path: ${OpenCV_INCLUDE_DIRS}")
#declare executable target build from sources
add_executable(facedetect facedetect.cpp)
#link to OpenCV lib
target_link_libraries(facedetect ${OpenCV_LIBS})
facedetect.cpp 源码:
#include "opencv2/opencv.hpp"
int main(int argc, char const *argv[])
{
cv::CascadeClassifier cascade;
std::string imageName, cascadeName;
cv::Mat image, gray;
std::vector<cv::Rect> faces;
cv::Scalar greenColor = cv::Scalar(0,255,0);
cascadeName = "./haarcascade_frontalface_default.xml";
imageName = argv[1];
//load image and class
if(!cascade.load(cascadeName)){
std::cerr << "Could not load classifier cascade" << std::endl;
}else if(imageName.empty()){
std::cout<<"Could not read"<<imageName<<std::endl;
}else{
image = cv::imread(imageName,1);
if (image.empty())
{
std::cout << "Could not imread image" << std::endl;
/* code */
}
}
//convert to gray
cv::cvtColor(image,gray,cv::COLOR_BGR2GRAY);
// run face detector
cascade.detectMultiScale(image,faces,1.1,2,0,cv::Size(30,30));
//output rectange
for(size_t i = 0; i < faces.size(); ++i){
cv::Rect r = faces[i];
cv::rectangle(
image,cv::Point(cvRound(r.x),cvRound(r.y)),
cv::Point(cvRound(r.x+r.width-1),cvRound(r.y+r.height-1)),
greenColor,3,8,0);
}
cv::imshow("result",image);
cv::waitKey(0);
cv::destroyAllWindows();
return 0;
}
感谢YOUTUBE大神的指导,会翻墙的朋友请直接看:
https://www.youtube.com/watch?v=GwHRG-JZZew
更多推荐
已为社区贡献3条内容
所有评论(0)