首页 > 解决方案 > 如何用opencv绘制一个绿色矩形?

问题描述

对 C++ 来说真的很新,所以我为这样的问题道歉。一直在尝试这些,但它们似乎不起作用。

(我在 opencv 中执行模板匹配功能 - https://docs.opencv.org/3.4/de/da9/tutorial_template_matching.html

编辑:这是我使用的图像、模板和蒙版的代码!

cv::Mat image = cv::Mat(height,width, CV16UC1, image); // image in short
cv::Mat temp;
image.convertTo(temp, CV32_F); // convert image to 32 bits

cv::image_template = cv::Mat(t_width, t_height, CV_32F, t_image); // template
cv::mask_template = cv::Mat(t_width, t_height, CV_32F, m_image); // mask

cv:: Mat img_display, result;
temp.copyTo(img_display); // image to display
int result_cols = temp.cols - image_template.cols + 1;
int result_rows = temp.rows - image_template.rows + 1;
result.create(result_rows, result_cols, CV32FC1);

// all the other code
matchTemplate(temp, image_template, result, 0, mask_template);
normalize( result, result, 0, 1, cv::NORM_MINMAX, -1, cv::Mat());

// localize the minimum and maximum values in the result matrix
double minVal;
double maxVal;
cv::Point minLoc;
cv::Point maxLoc;
cv::Point matchLoc;
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, cv::Mat());
// for match_method TM_SQDIFF we take lowest values
matchLoc = minLoc;


// display source image and result matrix , draw rectangle around highest possible matching area
cv::rectangle( img_display, matchLoc, cv::Point( matchLoc.x + image_template.cols, matchLoc.y + image_template.rows), cv::Scalar::all(255), 2, 8, 0);
cv::rectangle( result, matchLoc, cv::Point(matchLoc.x + image_template.cols, matchLoc.y + image_template.rows), cv::Scalar::all(255), 2, 8, 0);

这是给定的代码:

cv::rectangle( img_display, matchLoc, cv::Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), cv::Scalar::all(0), 2, 8, 0 );

尝试使用以下代码片段更改它,但似乎不起作用。

cv::rectangle( img_display, matchLoc, cv::Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), cv::Scalar(0,255,0) , 2, 8, 0 );

这也不起作用

rectangle(ref, maxloc, Point(maxloc.x + tpl.cols, maxloc.y + tpl.rows), CV_RGB(0,255,0), 2);

请让我知道我错在哪里!

标签: c++opencv

解决方案


只需添加

#define CV_RGB(r, g, b) 

在您的代码之上,以便 OpenCV 知道它将使用 RGB 颜色空间而不是默认的 BGR。

然后以这种方式绘制绿色矩形。

rectangle(frame, Point(startX, startY), Point(endX, endY), CV_RGB(0, 255, 0), 2);

推荐阅读