出した輪郭線を円や四角で囲みたい
opencv C++
輪郭線までは出せているのですが、その輪郭線を円や四角で囲む方法がわかりません
#include"stdafx.h"
#include<vector>
#include<strstream>
void run()
{
cv::Mat image;
//メインループ
while (1) {
//グレースケール入力
cv::Mat src = cv::imread("/*任意の2値画像*/", cv::IMREAD_GRAYSCALE);
// モルフォロジー処理
cv::Mat opening;
cv::Mat kernel(3, 3, CV_8U, cv::Scalar(1));
cv::morphologyEx(thresh, opening, cv::MORPH_OPEN, kernel, cv::Point(-1, -1), 2);
//cv::imshow("モルフォロジー処理化", opening);
// 背景領域抽出
cv::Mat sure_bg;
cv::dilate(opening, sure_bg, kernel, cv::Point(-1, -1), 3);
// 前景領域抽出
cv::Mat dist_transform;
cv::distanceTransform(opening, dist_transform, CV_DIST_L2, 5); //輪郭から距離が離れるほど濃くする
cv::Mat sure_fg;
double minVal, maxVal;
cv::Point minLoc, maxLoc;
cv::minMaxLoc(dist_transform, &minVal, &maxVal, &minLoc, &maxLoc);
cv::threshold(dist_transform, sure_fg, 0.2*maxVal, 255, 0);
dist_transform = dist_transform / maxVal;
// 不明領域抽出
cv::Mat unknown, sure_fg_uc1;
sure_fg.convertTo(sure_fg_uc1, CV_8UC1);
cv::subtract(sure_bg, sure_fg_uc1, unknown);
// 前景ラベリング
using namespace std;
int compCount = 0;
vector<vector<cv::Point> > contours;
vector<cv::Vec4i> hierarchy;
sure_fg.convertTo(sure_fg, CV_32SC1, 1.0);
cv::findContours(sure_fg, contours, hierarchy, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE);
if (contours.empty()) return;
cv::Mat markers = cv::Mat::zeros(sure_fg.rows, sure_fg.cols, CV_32SC1);
int idx = 0;
for (; idx >= 0; idx = hierarchy[idx][0], compCount++)
cv::drawContours(markers, contours, idx, cv::Scalar::all(compCount + 1), -1, 8, hierarchy, INT_MAX);
markers = markers + 1;
// 不明領域は今のところゼロ
for (int i = 0; i<markers.rows; i++) {
for (int j = 0; j<markers.cols; j++) {
unsigned char &v = unknown.at<unsigned char>(i, j);
if (v == 255) {
markers.at<int>(i, j) = 0;
}
}
}
watershed(hsv, markers);
cv::Mat wshed(markers.size(), CV_8UC3);
vector<cv::Vec3b> colorTab;
for (int i = 0; i < compCount; i++)
{
int b = cv::theRNG().uniform(0, 255);
int g = cv::theRNG().uniform(0, 255);
int r = cv::theRNG().uniform(0, 255);
colorTab.push_back(cv::Vec3b((uchar)b, (uchar)g, (uchar)r));
}
// paint the watershed image
for (int i = 0; i < markers.rows; i++) {
for (int j = 0; j < markers.cols; j++)
{
int index = markers.at<int>(i, j);
if (index == -1)
wshed.at<cv::Vec3b>(i, j) = cv::Vec3b(255, 255, 255);
else if (index <= 0 || index > compCount)
wshed.at<cv::Vec3b>(i, j) = cv::Vec3b(0, 0, 0);
else
wshed.at<cv::Vec3b>(i, j) = colorTab[index - 1];
}
}
cv::Mat imgG;
cvtColor(gray, imgG, cv::COLOR_GRAY2BGR);
wshed = wshed * 0.5 + imgG * 0.5;
}
}