Opencv (一) 边缘检测

Opencv (一) 边缘检测

1. 示例代码

#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"

#include <stdio.h>

using namespace cv;
using namespace std;

int edgeThresh = 1;
int edgeThreshScharr = 1;

Mat image, gray, blurImage, edge1, edge2, cedge;

const char* window_name1 = "Edge map : Canny default (Sobel gradient)";
const char* window_name2 = "Edge map : Canny with custom gradient (Scharr)";

// define a trackbar callback
static void onTrackbar(int, void*)
{
    // 1.对图像进行均值滤波,去除一些噪声,也可以使用其他滤波器进行平滑
	blur(gray, blurImage, Size(3, 3));  //(3,3)滤波器尺寸大小

	// 2.Canny边缘检测,使用Sobel gradient
	// blurImage:输入图像
	// edge1:输出边缘检测结果
	// edgeThresh, edgeThresh*3 双阈值检测
	// 3:Sobel卷积核尺寸
	Canny(blurImage, edge1, edgeThresh, edgeThresh * 3, 3);
	cedge = Scalar::all(0);

	image.copyTo(cedge, edge1);
	imshow(window_name1, cedge);

	/// 3.使用Scharr进行边缘检测
	Mat dx, dy;
	Scharr(blurImage, dx, CV_16S, 1, 0);   // x方向导数
	Scharr(blurImage, dy, CV_16S, 0, 1);   // y方向导数
	Canny(dx, dy, edge2, edgeThreshScharr, edgeThreshScharr * 3, true); //true,使用更精准的方式进行边缘提取,即L2梯度
	/// Using Canny's output as a mask, we display our result
	cedge = Scalar::all(0);
	image.copyTo(cedge, edge2);
	imshow(window_name2, cedge);
}

static void help()
{
	printf("\nThis sample demonstrates Canny edge detection\n"
		"Call:\n"
		"    /.edge [image_name -- Default is fruits.jpg]\n\n");
}

const char* keys =
{
	"{help h||}{@image |fruits.jpg|input image name}"
};

int main(int argc, const char** argv)
{
	help();
	CommandLineParser parser(argc, argv, keys);
	string filename = parser.get<string>(0);
	filename = "right.jpg";
	image = imread(samples::findFile(filename), IMREAD_COLOR);
	if (image.empty())
	{
		printf("Cannot read image file: %s\n", filename.c_str());
		help();
		return -1;
	}
	cedge.create(image.size(), image.type());
	cvtColor(image, gray, COLOR_BGR2GRAY);

	// Create a window
	namedWindow(window_name1, 1);
	namedWindow(window_name2, 1);

	// create a toolbar
	createTrackbar("Canny threshold default", window_name1, &edgeThresh, 100, onTrackbar);
	createTrackbar("Canny threshold Scharr", window_name2, &edgeThreshScharr, 400, onTrackbar);

	// Show the image
	onTrackbar(0, 0);

	// Wait for a key stroke; the same function arranges events processing
	waitKey(0);

	return 0;
}

2.示例图像

在这里插入图片描述

3.检测结果

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值