1. 程式人生 > >OpenCv-C++-輪廓發現

OpenCv-C++-輪廓發現

#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>

using namespace cv;
using namespace std;

Mat src,dst;
void contours(int, void*);
int thresholdMax = 255;
int thresholdvalue = 100;
int main(int argc, char** argv)
{
	src = imread("D:/test/fish.png");
	if (!src.data)
{ printf("圖片為空"); return -1; } cvtColor(src, dst, CV_BGR2GRAY); namedWindow("output image"); createTrackbar("Canny thresh", "output image", &thresholdvalue, thresholdMax, contours); contours(0,0); imshow("input image", src); waitKey(0); return 0; } void contours(int, void *) { Mat canny_output;
dst = Mat::zeros(src.size(), CV_8UC3); vector<vector<Point>> contours; vector<Vec4i> hierachy; /*邊緣檢測,thresholdvalue,thresholdvalue*2這兩個引數比值一般來說是1:1.5、1:2、1:3*/ Canny(src, canny_output, thresholdvalue, thresholdvalue * 2, 3, false); findContours(canny_output, contours, hierachy,
RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0)); RNG rng(12345); for (size_t i = 0; i < contours.size(); i++) { Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255),rng.uniform(0, 255)); drawContours(dst, contours, (int)i, color, 1, LINE_AA, hierachy, 0, Point(0, 0)); } imshow("output image", dst); }

大致步驟:

  1. 先將圖片轉化為灰度影象
  2. 進行邊緣檢測
  3. 找到輪廓findContours
  4. 繪製輪廓drawContours

執行結果:

輸入
在這裡插入圖片描述
在這裡插入圖片描述