使用opencv c ++裁剪三角形 [英] Crop Triangle with opencv c++
问题描述
用户,
我想在图像上裁剪该三角形并使用 opencv c++ 在另一个窗口中显示它.我知道所有三个坐标.谁能帮我?我在网上没有找到任何关于三角形裁剪"的答案.谢谢!
I want to crop that Triangle on the image and show it in another window with opencv c++. I know all three Coordinates. Can anyone help me? I did not find any answer on the Internet about "triangle cropping". Thanks!
这里的问题是我不能使用 ROI 来裁剪三角形.我只需要复制没有任何背景或其他东西的三角形.是否可以通过知道三角形 [p1(302,179), p2(329,178), p3(315,205)] 的坐标来创建我自己的 ROI?
The Problem here is that i cannot use ROI for cropping the Triangle. I have to copy just the triangle without any background or something around. Is it possible to create my own ROI by knowing the Coordinates of the triangle [p1(302,179), p2(329,178), p3(315,205)]?
推荐答案
你可以使用掩码来实现,如下面的代码所示
you can do it by using mask as shown with the code below
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;
int main( int, char** argv )
{
Mat src = imread( argv[1] );
Mat gray;
cvtColor(src, gray, COLOR_BGR2GRAY );
gray = gray < 127;
vector<vector<Point> > contours;
findContours(gray, contours,
RETR_EXTERNAL,
CHAIN_APPROX_SIMPLE);
for( size_t i = 0; i< contours.size(); i++ )
{
Rect rect = boundingRect(contours[i]);
Mat mask = gray(rect);
Mat srcROI = src(rect);
srcROI.setTo(Scalar(0,0,255),mask);
imshow("srcROI",srcROI);
waitKey();
}
imshow( "result", src );
waitKey(0);
return(0);
}
根据问题的变化,我建议使用下面的测试代码
according the change on the question i suggest the test code below
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
using namespace std;
int main( int, char** argv )
{
Mat src = imread("lena.jpg");
vector<Point> points;
points.push_back( Point(200,200));
points.push_back( Point(370,370));
points.push_back( Point(220,410));
Mat mask = Mat::zeros( src.size(), CV_8UC1 );
fillConvexPoly( mask, points, Scalar( 255 ));
Rect rect = boundingRect( points );
Mat roi = src( rect ).clone();
mask = mask( rect ).clone();
rect.x = rect.x - 180;
rect.y = rect.y - 180;
Mat srcROI = src( rect );
roi.copyTo( srcROI, mask );
imshow( "result", src );
waitKey(0);
return(0);
}
这篇关于使用opencv c ++裁剪三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!