正如标题所说,我正在尝试查找cv::Mat的某个区域中的非零像素数,即RotatedRect中的像素数。
对于常规的Rect,可以简单地在ROI上使用countNonZeroPixels。然而,ROI只能是规则的(非旋转的)矩形。
另一个想法是绘制旋转后的矩形,并将其用作蒙版。但是,openCV既不支持绘制旋转的矩形,countNonZeroPixels也不接受蒙版。
有没有人知道如何优雅地解决这个问题?
谢谢!
发布于 2011-07-12 05:43:31
好的,这是我的第一个想法。
这个想法是将图像反向旋转到矩形的旋转,然后在拉直的矩形上应用roi。
#include #include // From http://stackoverflow.com/questions/2289690/opencv-how-to-rotate-iplimage cv::Mat rotateImage(const cv::Mat& rotateImage,cv::Point2f center,double angle) { cv::Mat rot_mat = cv::getRotationMatrix2D(center,angle,1.0);cv::Mat dst;cv::warpAffine(http://stackoverflow.com/questions/2289690/opencv-how-to-rotate-iplimage,dst,rot_mat,source.size();return dst;} int main() { cv::namedWindow("test1");//我们旋转后的矩形x= 300;int y= 350;int w= 200;int h= 50;浮动角度= 47;cv::RotatedRect rect = cv::RotatedRect(cv::Point2f(x,y),cv::Size2f(w,h),angle);//一个空图像cv::Mat img = cv::Mat(cv::Size(640,480),CV_8UC3);//将旋转后的矩形绘制为椭圆,得到一些视觉反馈cv:: ellipse (img,rect,cv::Scalar(255,0,0),-1);//通过rect.angle * -1 cv::Mat rotimg = rotateImage(img,rect.center,-1 *rect.angle)旋转图像;//将roi设置为现在未旋转的矩形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);}
发布于 2013-04-10 13:32:39
一种完全不同的方法可能是旋转你的图像(在相反的方向),并仍然使用矩形感兴趣区域与countNonZeroPixels相结合。唯一的问题是,你必须围绕ROI中心的轴心旋转图像……
为了使其更清楚,请参阅附加的示例:
发布于 2015-02-28 09:49:45
为了避免在类似的任务中旋转,我使用下面的函数迭代RotatedRect中的每个像素:
double filling(Mat& img, RotatedRect& rect){
double non_zero = 0;
double total = 0;
Point2f rect_points[4];
rect.points( rect_points );
for(Point2f i=rect_points[0];norm(i-rect_points[1])>1;i+=(rect_points[1]-i)/norm((rect_points[1]-i))){
Point2f destination = i+rect_points[2]-rect_points[1];
for(Point2f j=i;norm(j-destination)>1;j+=(destination-j)/norm((destination-j))){
if(img.at<uchar>(j) != 0){
non_zero+=1;
}
total+=1;
}
}
return non_zero/total;
}
这看起来就像通常的矩形迭代,但在每一步,我们在指向目的地的方向上将单位1px向量添加到当前点。
这个循环不会遍历所有的点并跳过几个像素,但它对我的任务来说是可以的。
更新:最好使用LineIterator进行迭代:
Point2f rect_points[4];
rect.points(rect_points);
Point2f x_start = rect_points[0];
Point2f x_end = rect_points[1];
Point2f y_direction = rect_points[3] - rect_points[0];
LineIterator x = LineIterator(frame, x_start, x_end, 4);
for(int i = 0; i < x.count; ++i, ++x){
LineIterator y = LineIterator(frame, x.pos(), x.pos() + y_direction, 4);
for(int j=0; j < y_count; j++, ++y){
Vec4b pixel = frame.at<Vec4b>(y.pos);
/* YOUR CODE HERE */
}
}
https://stackoverflow.com/questions/6653272
复制相似问题