这段代码解决Python中cv.boxPoints的替换问题,C++ 中请使用新的API函数。以及画出最小轮廓的方法。
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main() {
cv::Mat image = cv::imread("./data/pic9.png");
Mat image_copy(image);
//转成灰度图
Mat gray;
cv::cvtColor(image,gray,cv::COLOR_BGR2GRAY);
cv::imshow("gray",gray);
cv::imshow("image",image);
//转成二值图
Mat inrange_pic9,hsv_pic9;
cv::cvtColor(image,hsv_pic9,cv::COLOR_BGR2HSV);
// cv::imshow("hsv_pic9",hsv_pic9);
cv::inRange(hsv_pic9,Scalar(0,5,5),Scalar(88,255,255),inrange_pic9);
cv::imshow("inrange_pic9",inrange_pic9);
// 腐蚀膨胀让其更加分明
Mat morp_pic9;
Mat kernel = cv::getStructuringElement(cv::MORPH_RECT, Size(5, 5));
cv::morphologyEx(inrange_pic9,morp_pic9,cv::MORPH_OPEN,kernel);
cv::imshow("morp_pic9",morp_pic9);
// 反转一下
cv::bitwise_not(morp_pic9,morp_pic9);
cv::imshow("morp_pic9",morp_pic9);
//寻找轮廓
std::vector<std::vector<cv::Point> > contours;
vector<cv::Vec4i> hierarchy;
cv::findContours(morp_pic9,contours,hierarchy,cv::RETR_EXTERNAL,cv::CHAIN_APPROX_SIMPLE);
cv::drawContours(image_copy,contours,-1,Scalar(0,0,255),2);
cv::imshow("image_copy",image_copy);
//开始找轮廓的特性
for (int i = 0; i < contours.size(); ++i) {
//画他的外接矩形
Rect rect = cv::boundingRect(contours[i]);
int x,y,width,height;
x=rect.x;y=rect.y;width=rect.width;height=rect.height;
cv::rectangle(image_copy,Point(x,y),Point(x+width,y+height),Scalar(255,0,0),2);
//画出最小矩形
RotatedRect rotatedRect = cv::minAreaRect(contours[i]);
//使用新的方法,cv::boxpoints的替换方法
Point2f boxs[4];
rotatedRect.points(boxs);
vector<vector<Point> > c;
vector<Point> vp;
for (int j = 0; j < 4; ++j) {
vp.push_back(Point(boxs[j].x,boxs[j].y));
}
c.push_back(vp);
cv::drawContours(image_copy,c,-1,Scalar(0,255,0),3);
// cv::rectangle(image_copy,Point(boxs[0].x,boxs[0].y),Point(boxs[2].x,boxs[2].y),Scalar(0,255,0),3);
cv::circle(image_copy,Point(boxs[2].x+boxs[0].x,boxs[2].y+boxs[0].y)/2,2,Scalar(0,0,255),-1);
// vector<cv::Point2f> points;
// cv::boxPoints(rotatedRect,points);
// cout<<points[0]<<endl;
}
cv::imshow("image_newcopy",image_copy);
cv::waitKey(0);
cv::destroyAllWindows();
return 0;
}