gpt4 book ai didi

c++ - 用 opencv c++ 裁剪三角形

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:13:49 25 4
gpt4 key购买 nike

用户,

enter image description here

我想在图像上裁剪三角形并使用 opencv c++ 在另一个窗口中显示它。我知道所有三个坐标。谁能帮我?我没有在互联网上找到任何关于“三角裁剪”的答案。谢谢!

编辑:这里的问题是我不能使用 ROI 来裁剪三角形。我必须只复制三角形,没有任何背景或周围的东西。是否可以通过了解三角形 [p1(302,179)、p2(329,178)、p3(315,205)] 的坐标来创建自己的 ROI?

最佳答案

cv::Mat inputImage = cv::imread("input.png");
if (inputImage.channels() > 1)
{
cv::cvtColor(inputImage, inputImage, CV_RGB2GRAY);
}

// replace these values with your actual coordinates
// I found these by first saving your provided image, then
// using Microsoft Paint
int x0 = 242;
int y0 = 164;
int x1 = 314;
int y1 = 38;
int x2 = 387;
int y2 = 164;

// then create a line masking using these three points
cv::Mat lineMask = cv::Mat::zeros(inputImage.size(), inputImage.type());
cv::line(lineMask, cv::Point(x0, y0), cv::Point(x1, y1), cv::Scalar(255, 255, 0), 1, 8, 0);
cv::line(lineMask, cv::Point(x0, y0), cv::Point(x2, y2), cv::Scalar(255, 255, 0), 1, 8, 0);
cv::line(lineMask, cv::Point(x1, y1), cv::Point(x2, y2), cv::Scalar(255, 255, 0), 1, 8, 0);

// perform contour detection on your line mask
cv::vector<cv::vector<cv::Point>> contours;
cv::vector<cv::Vec4i> hierarchy;
cv::findContours(lineMask, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));

// calculate the distance to the contour
cv::Mat raw_dist(lineMask.size(), CV_32FC1);

for (int i = 0; i < lineMask.rows; i++)
{
for (int j = 0; j < lineMask.cols; j++)
{
raw_dist.at<float>(i, j) = cv::pointPolygonTest(contours[0], cv::Point2f(j, i), true);
}
}

double minVal; double maxVal;
cv::minMaxLoc(raw_dist, &minVal, &maxVal, 0, 0, cv::Mat());
minVal = std::abs(minVal);
maxVal = std::abs(maxVal);

// depicting the distances graphically
cv::Mat mask = cv::Mat::zeros(inputImage.size(), CV_8UC1);

for (int i = 0; i < mask.rows; i++)
{
for (int j = 0; j < mask.cols; j++)
{
if (raw_dist.at<float>(i, j) < 0)
{
mask.at<uchar>(i, j) = static_cast<uchar>(0);
continue;
}
mask.at<uchar>(i, j) = static_cast<uchar>(255);
}
}

// inverse the input image
cv::Mat invInput;
cv::bitwise_not(inputImage, invInput);

// then get only the region of your triangle
cv::Mat outputImage;
invInput.copyTo(outputImage, mask);
cv::bitwise_not(outputImage, outputImage);

// display for debugging purpose
cv::imshow("inputImage", inputImage);
cv::imshow("lineMask", lineMask);
cv::imshow("mask", mask);
cv::imshow("outputImage", outputImage);
cv::waitKey();

这是您的inputImage:

enter image description here

这是你的lineMask:

enter image description here

这是您创建的二进制掩码:

enter image description here

这是你的最终outputImage:

enter image description here

引用资料:

OpenCV draw line

OpenCV findContours

Point Polygon Test

关于c++ - 用 opencv c++ 裁剪三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33625186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com