opencv学习-物体轮廓外接矩形的绘制
Posted 殇堼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了opencv学习-物体轮廓外接矩形的绘制相关的知识,希望对你有一定的参考价值。
全部代码-单个物体
注意以下代码与对多个物体进行框选的代码的不同。
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main() {
Mat src, Gau_src, gray_src, binary_src;
src = imread("D:/images/hand.jpg");
if (src.empty()) {
cout << "Could not load the image ...." << endl;
return -1;
}
imshow("input_image", src);
GaussianBlur(src, Gau_src, Size(5, 5), 0, 0, 4);
imshow("Gau_src", Gau_src);
cvtColor(Gau_src, gray_src, COLOR_BGR2GRAY);
imshow("gray_src", gray_src);
threshold(gray_src, binary_src,100,255,THRESH_BINARY);
imshow("binary_src", binary_src);
vector<vector<Point>>contours;
findContours(binary_src, contours, 0, 2, Point());
for (int n = 0; n < contours.size(); n++) {
Rect rect = boundingRect(contours[n]);
rectangle(src, rect, Scalar(0, 0, 255), 1);
}
imshow("output_image", src);
waitKey(0);
return 0;
}
效果展示
全部代码-多个物体
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main() {
Mat src, Gau_src, gray_src, binary_src, canny_src,bitwise_src;
src = imread("D:/images/gem_test.png");
if (src.empty()) {
cout << "Could not load the image ...." << endl;
return -1;
}
imshow("input_image", src);
GaussianBlur(src, Gau_src, Size(3, 3), 0, 0, 4);
imshow("Gau_src", Gau_src);
cvtColor(Gau_src, gray_src, COLOR_BGR2GRAY);
imshow("gray_src", gray_src);
Canny(gray_src, canny_src, 2, 255, 3);
imshow("canny_src", canny_src);
vector<vector<Point>>contours;
findContours(canny_src, contours, 0, 2, Point());
for (int n = 0; n < contours.size(); n++) {
Rect rect = boundingRect(contours[n]);
rectangle(src, rect, Scalar(0, 0, 255), 1);
}
imshow("output_image", src);
waitKey(0);
return 0;
}
效果展示
以上是关于opencv学习-物体轮廓外接矩形的绘制的主要内容,如果未能解决你的问题,请参考以下文章
Opencv-python 找到图像轮廓并绘制,cv2.findContours()函数,求轮廓外接矩形,cv2.boundingrect()