简体   繁体   English

如何从图像遮罩旋转的矩形?

[英]How to mask a rotated rectangle from an image?

I have an image that I need to mask some portion of it. 我有一张需要遮盖其中一部分的图像。 The portion is a rotated rectangle. 该部分是旋转的矩形。 When I pass on the arguments of top-left corner and bottom-right corner to the function cv.rectangle() , it does not form a rotated rectangle, instead, it draws a rectangle with no tilt. 当我将左上角和右下角的参数传递给函数cv.rectangle() ,它不会形成旋转的矩形,而是会绘制一个没有倾斜的矩形。 However, I want to mask a rotated rectangle in an image and I have all the four coordinates of the rectangle. 但是,我想在图像中遮盖旋转的矩形,并且具有矩形的所有四个坐标。 Is there any way to do this? 有什么办法吗? Thank you. 谢谢。 Any help is appreciated. 任何帮助表示赞赏。 I am using OpenCV in python. 我在python中使用OpenCV。

To draw a rotated rectangle, extract the four corners into a contour, then use cv::drawContours 要绘制旋转的矩形,请将四个角提取到轮廓中,然后使用cv :: drawContours

cv::RotatedRect rr(cv::Point(x, y), cv::Size(w, h), angle);
cv::Point2f pts[4];
rr.points(pts);
std::vector<std::vector<cv::Point>> contours;
contours.push_back(std::vector<cv::Point>());
for(int i = 0; i < 4; i++) contours[0].push_back(pts[i]);
cv::drawContours(image, contours, 0, cv::Scalar::all(255), -1);

oops, that's C++ ... but transcoding to python should be straightforward :) Section 7 of this tutorial has what you need. 糟糕,这是C ++,但是将代码转换为python应该很简单:) 本教程的第7节介绍了您所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM