cv::RotatedRect 中的非零像素数 [英] Number of non-zero pixels in a cv::RotatedRect
问题描述
正如标题所说,我正在尝试在 cv::Mat 的某个区域(即 RotatedRect 内)中查找非零像素的数量.
as the title says i'm trying to find the number of non-zero pixels in a certain area of a cv::Mat, namely within a RotatedRect.
对于常规 Rect,可以简单地在 ROI 上使用 countNonZeroPixels.然而,ROI 只能是常规(非旋转)矩形.
For a regular Rect one could simply use countNonZeroPixels on a ROI. However ROIs can only be regular (non rotated) rectangles.
另一个想法是绘制旋转的矩形并将其用作蒙版.然而 openCV 既不支持绘制旋转的矩形也不支持 countNonZeroPixels 接受掩码.
Another idea was to draw the rotated rectangle and use that as a mask. However openCV neither supports the drawing of rotated rectangles nor does countNonZeroPixels accept a mask.
有没有人可以优雅地解决这个问题?
Does anyone have a solution for how to elegantly solve this ?
谢谢!
推荐答案
好的,这是我的第一次尝试.
Ok, so here's my first take at it.
这个想法是将图像反向旋转到矩形的旋转,然后在拉直的矩形上应用 roi.
The idea is to rotate the image reverse to the rectangle's rotation and than apply a roi on the straightened rectangle.
- 如果旋转的矩形不完全在图像内,这将中断
您可能可以通过在旋转之前应用另一个 roi 来加快速度,以避免旋转整个图像...
- This will break if the rotated rectangle is not completely within the image
You can probably speed this up by applying another roi before rotation to avoid having to rotate the whole image...
#include <highgui.h>
#include <cv.h>
// From http://stackoverflow.com/questions/2289690/opencv-how-to-rotate-iplimage
cv::Mat rotateImage(const cv::Mat& source, cv::Point2f center, double angle)
{
cv::Mat rot_mat = cv::getRotationMatrix2D(center, angle, 1.0);
cv::Mat dst;
cv::warpAffine(source, dst, rot_mat, source.size());
return dst;
}
int main()
{
cv::namedWindow("test1");
// Our rotated rect
int x = 300;
int y = 350;
int w = 200;
int h = 50;
float angle = 47;
cv::RotatedRect rect = cv::RotatedRect(cv::Point2f(x,y), cv::Size2f(w,h), angle);
// An empty image
cv::Mat img = cv::Mat(cv::Size(640, 480), CV_8UC3);
// Draw rotated rect as an ellipse to get some visual feedback
cv::ellipse(img, rect, cv::Scalar(255,0,0), -1);
// Rotate the image by rect.angle * -1
cv::Mat rotimg = rotateImage(img, rect.center, -1 * rect.angle);
// Set roi to the now unrotated rectangle
cv::Rect roi;
roi.x = rect.center.x - (rect.size.width / 2);
roi.y = rect.center.y - (rect.size.height / 2);
roi.width = rect.size.width;
roi.height = rect.size.height;
cv::imshow("test1", rotimg(roi));
cv::waitKey(0);
}
这篇关于cv::RotatedRect 中的非零像素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!