对“lena.jpg” 的灰度图像分别进行如下操作:
(1)先平滑滤波,进行Canny边缘检测,显示并保存图像;
源代码:
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/highgui/highgui_c.h>
#include <stdlib.h>
#include <stdio.h>
using namespace cv;
/// 全局变量
Mat src, src_gray;
Mat dst, detected_edges;
int edgeThresh = 1;
int lowThreshold;
int const max_lowThreshold = 100;
int ratio = 3;
int kernel_size = 3;
char* window_name =(char*) "lena";
/**
* @函数 CannyThreshold
* @简介: trackbar 交互回调 - Canny阈值输入比例1:3
*/
void CannyThreshold(int, void*)
{
/// 使用 3x3内核降噪
blur(src_gray, detected_edges, Size(3, 3));
/// 运行Canny算子
Canny(detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size);
/// 使用 Canny算子输出边缘作为掩码显示原图像
dst = Scalar::all(0);
src.copyTo(dst, detected_edges);
imshow(window_name, dst);
imwrite("C:\\Users\\15518\\Desktop\\opencv\\Blena.jpg",dst);
}
/** @函数 main */
int main(int argc)
{
/// 装载图像
src = imread("C:\\Users\\15518\\Desktop\\opencv\\lena.jpg");
imshow("原图像",src);
if (!src.data)
{
return -1;
}
/// 创建与src同类型和大小的矩阵(dst)
dst.create(src.size(), src.type());
/// 原图像转换为灰度图像
cvtColor(src, src_gray, CV_BGR2GRAY);
/// 创建显示窗口
namedWindow(window_name, CV_WINDOW_AUTOSIZE);
/// 创建trackbar
createTrackbar("Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold);
/// 显示图像
CannyThreshold(0, 0);
/// 等待用户反应
waitKey(0);
return 0;
}
结果图像
(2)在(1)的基础上,进行Hough直线变换 ,描绘显示并保存图像。
源代码:
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2/highgui/highgui_c.h>
#include <iostream>
using namespace cv;
using namespace std;
void help()
{
cout << "\nThis program demonstrates line finding with the Hough transform.\n"
"Usage:\n"
"./houghlines <image_name>, Default is pic1.jpg\n" << endl;
}
int main(int argc, char** argv)
{
//const char* filename = argc >= 2 ? argv[1] : "pic1.jpg";
const char* filename = "C:\\Users\\15518\\Desktop\\opencv\\lena.jpg";
Mat src = imread(filename, 0);
if (src.empty())
{
help();
cout << "can not open " << filename << endl;
return -1;
}
Mat dst, cdst;
Canny(src, dst, 50, 150, 3);
cvtColor(dst, cdst, CV_GRAY2BGR);
#if 0
vector<Vec2f> lines;
HoughLines(dst, lines, 1, CV_PI / 180, 100, 0, 0);
for (size_t i = 0; i < lines.size(); i++)
{
float rho = lines[i][0], theta = lines[i][1];
Point pt1, pt2;
double a = cos(theta), b = sin(theta);
double x0 = a * rho, y0 = b * rho;
pt1.x = cvRound(x0 + 1000 * (-b));
pt1.y = cvRound(y0 + 1000 * (a));
pt2.x = cvRound(x0 - 1000 * (-b));
pt2.y = cvRound(y0 - 1000 * (a));
line(cdst, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);
}
#else
vector<Vec4i> lines;
HoughLinesP(dst, lines, 1, CV_PI / 180, 10, 5, 10);
for (size_t i = 0; i < lines.size(); i++)
{
Vec4i l = lines[i];
line(cdst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 255, 0), 3, CV_AA);
}
#endif
imshow("source", src);
imshow("detected lines", cdst);
imwrite("C:\\Users\\15518\\Desktop\\opencv\\Hlena.jpg", cdst);
waitKey();
return 0;
}
结果图像: