opencv
演示
- 输入说明 原图在顶层后然后再去按键,不然会失效(未知原因)
1.roberts 边缘检测
2.sobel算子
3.Canny算子
4.Laplace算子
5.Canny算子,轮廓显示
空格 人脸检测 - 准备一张图片
- 效果 默认显示原图和灰阶图
- roberts 边缘检测
//roberts 边缘检测
Mat roberts(Mat srcImage)
{
Mat dstImage = srcImage.clone();
int nRows = dstImage.rows;
int nCols = dstImage.cols;
for (int i = 0; i < nRows - 1; i++) {
for (int j = 0; j < nCols - 1; j++) {
//根据公式计算
int t1 = (srcImage.at<uchar>(i, j) -
srcImage.at<uchar>(i + 1, j + 1)) *
(srcImage.at<uchar>(i, j) -
srcImage.at<uchar>(i + 1, j + 1));
int t2 = (srcImage.at<uchar>(i + 1, j) -
srcImage.at<uchar>(i, j + 1)) *
(srcImage.at<uchar>(i + 1, j) -
srcImage.at<uchar>(i, j + 1));
//计算g(x,y)
dstImage.at<uchar>(i, j) = (uchar)sqrt(t1 + t2);
}
}
return dstImage;
}
2. sobel算子
Sobel(src_gray, grad_x, CV_16S, 1, 0, 3, 1, 1, BORDER_DEFAULT);//求x方向梯度
convertScaleAbs(grad_x, abs_grad_x);//转换格式 8u
Sobel(src_gray, grad_y, CV_16S, 0, 1, 3, 1, 1, BORDER_DEFAULT);//求y方向梯度
convertScaleAbs(grad_y, abs_grad_y);
//合并梯度
addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, dst);
cv::imshow("solbel算子", dst);
3. Canny算子
//3.Canny算子
Mat canny_output;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Canny(src_gray, canny_output, 100, 300);
cv::imshow("Canny算子", canny_output);
4. Laplace算子
Laplacian(src_gray, dst, -1, 3);
cv::imshow("Laplace算子", dst);
5. Canny算子,轮廓显示
Mat canny_output;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
Canny(src_gray, canny_output, 100, 300);
// 寻找轮廓
findContours(canny_output, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_TC89_KCOS);
/// 绘出轮廓
Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3);
for (int i = 0; i < contours.size(); i++)
{
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
}
//在窗体中显示结果
namedWindow("Contours", WINDOW_AUTOSIZE);
cv::imshow("Contours", drawing);
空格 人脸检测 官方的模型,不太精确
//人脸检测的
CascadeClassifier faceCascade;
int ret = faceCascade.load("data/haarcascades/haarcascade_frontalface_alt.xml"); //加载分类器,注意文件路径
//int ret = faceCascade.load("cascade.xml"); //加载分类器,注意文件路径
if (!ret)//从指定的文件目录中加载级联分类器
{
cerr << "ERROR:Could not load classifier cascade" << endl;
continue;
}
Mat imgGray;
vector<Rect> faces;
if (src.channels() == 3)
{
cvtColor(src, imgGray, COLOR_RGB2GRAY);
}
else
{
imgGray = src;
}
equalizeHist(imgGray, imgGray);
faceCascade.detectMultiScale(imgGray, faces, 1.1, 4, 0, Size(65, 65)); //检测人脸
if (faces.size() > 0)
{
for (int i = 0; i < faces.size(); i++)
{
//rectangle(src, Point(faces[i].x, faces[i].y), Point(faces[i].x + faces[i].width, faces[i].y + faces[i].height),
// Scalar(0, 255, 0), 1, 8); //框出人脸位置
rectangle(src, faces[i], Scalar(0, 0, 255), 2, 8, 0);
}
}
else {
cerr << "ERROR:Could not detect face" << endl;
continue;
}
// namedWindow("FacesOfPrettyGirl", WINDOW_NORMAL);
cv::imshow("FacesDetect", src);