调用opencv接口二值化后进行轮廓查找,然后使用line绘制出来边缘
#include <iostream> #include <vector> #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <omp.h> using namespace std; using namespace cv; int main() { setUseOptimized(true); Mat img = imread("F:/1.jpg"); Mat copyImg,grayImg, binImg; cvtColor(img, grayImg, COLOR_BGR2GRAY); //提取二值化图像中的轮廓数据 vector<vector<Point> > contour_vec; vector<Vec4i> hierarchy; img.copyTo(copyImg); int s = cv::getTickCount(); //二值化 threshold(grayImg, binImg, 100, 255, THRESH_BINARY_INV); //bitwise_not(binImg, binImg); //轮廓查找 findContours(binImg, contour_vec, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_NONE); //cout << "contours number: " << contour_vec.size() << endl; // 以前常用的for循环绘制轮廓 /*Mat blkImg(binImg.size(), CV_8UC1, Scalar(0)); for(int i = 0; i < contour_vec.size(); i++) { drawContours(blkImg, contour_vec, i, Scalar(255), -1); } */ //绘制单通道轮廓图像,背景为白色,轮廓线条用黑色 #pragma omp parallel for for (int i = 0; i < contour_vec.size(); i++) { //绘制轮廓的最小外结矩形 RotatedRect rect = minAreaRect(contour_vec[i]); Point2f P[4]; rect.points(P); for (int j = 0; j <= 3; j++) { line(copyImg, P[j], P[(j + 1) % 4], Scalar(255), 1); } } int e = cv::getTickCount(); std::cout << "BlobDetect cost time: " << static_cast<double>(e - s) / cv::getTickFrequency() * 1000 << "ms" << std::endl; contour_vec.clear(); hierarchy.clear(); imshow("blkImg", copyImg); waitKey(0); return 0; }