关于opencv的contourArea计算方法

cv::contourArea计算的轮廓面积并不等于轮廓点计数,原因是cv::contourArea是基于Green公式计算
在这里插入图片描述

老外的讨论 github

举一个直观的例子,图中有7个像素,橙色为轮廓点连线,按照contourArea的定义,轮廓的面积为橙色所包围的区域=3

在这里插入图片描述

以下代码基于opencv4.8.0

cv::contourArea源码位于.\sources\modules\imgproc\src\shapedescr.cpp

// area of a whole sequence
double cv::contourArea( InputArray _contour, bool oriented )
{CV_INSTRUMENT_REGION();Mat contour = _contour.getMat();int npoints = contour.checkVector(2);int depth = contour.depth();CV_Assert(npoints >= 0 && (depth == CV_32F || depth == CV_32S));if( npoints == 0 )return 0.;double a00 = 0;bool is_float = depth == CV_32F;const Point* ptsi = contour.ptr<Point>();const Point2f* ptsf = contour.ptr<Point2f>();Point2f prev = is_float ? ptsf[npoints-1] : Point2f((float)ptsi[npoints-1].x, (float)ptsi[npoints-1].y);for( int i = 0; i < npoints; i++ ){Point2f p = is_float ? ptsf[i] : Point2f((float)ptsi[i].x, (float)ptsi[i].y);a00 += (double)prev.x * p.y - (double)prev.y * p.x;prev = p;}a00 *= 0.5;if( !oriented )a00 = fabs(a00);return a00;
}

如果计算面积需要考虑轮廓点本身,可以通过cv::drawContoursI填充轮廓获得mask图像后统计非零点个数

cv::drawContours源码位于.\sources\modules\imgproc\src\drawing.cpp,主要包括两步:收集边缘cv::CollectPolyEdges和填充边缘cv::FillEdgeCollection,How does the drawContours function work in OpenCV when a contour is filled?

struct PolyEdge
{PolyEdge() : y0(0), y1(0), x(0), dx(0), next(0) {}//PolyEdge(int _y0, int _y1, int _x, int _dx) : y0(_y0), y1(_y1), x(_x), dx(_dx) {}int y0, y1;int64 x, dx;PolyEdge *next;
};static void
CollectPolyEdges( Mat& img, const Point2l* v, int count, std::vector<PolyEdge>& edges,const void* color, int line_type, int shift, Point offset )
{int i, delta = offset.y + ((1 << shift) >> 1);Point2l pt0 = v[count-1], pt1;pt0.x = (pt0.x + offset.x) << (XY_SHIFT - shift);pt0.y = (pt0.y + delta) >> shift;edges.reserve( edges.size() + count );for( i = 0; i < count; i++, pt0 = pt1 ){Point2l t0, t1;PolyEdge edge;pt1 = v[i];pt1.x = (pt1.x + offset.x) << (XY_SHIFT - shift);pt1.y = (pt1.y + delta) >> shift;Point2l pt0c(pt0), pt1c(pt1);if (line_type < cv::LINE_AA){t0.y = pt0.y; t1.y = pt1.y;t0.x = (pt0.x + (XY_ONE >> 1)) >> XY_SHIFT;t1.x = (pt1.x + (XY_ONE >> 1)) >> XY_SHIFT;Line(img, t0, t1, color, line_type);// use clipped endpoints to create a more accurate PolyEdgeif ((unsigned)t0.x >= (unsigned)(img.cols) ||(unsigned)t1.x >= (unsigned)(img.cols) ||(unsigned)t0.y >= (unsigned)(img.rows) ||(unsigned)t1.y >= (unsigned)(img.rows)){clipLine(img.size(), t0, t1);if (t0.y != t1.y){pt0c.y = t0.y; pt1c.y = t1.y;pt0c.x = (int64)(t0.x) << XY_SHIFT;pt1c.x = (int64)(t1.x) << XY_SHIFT;}}else{pt0c.x += XY_ONE >> 1;pt1c.x += XY_ONE >> 1;}}else{t0.x = pt0.x; t1.x = pt1.x;t0.y = pt0.y << XY_SHIFT;t1.y = pt1.y << XY_SHIFT;LineAA(img, t0, t1, color);}if (pt0.y == pt1.y)continue;edge.dx = (pt1c.x - pt0c.x) / (pt1c.y - pt0c.y);if (pt0.y < pt1.y){edge.y0 = (int)(pt0.y);edge.y1 = (int)(pt1.y);edge.x = pt0c.x + (pt0.y - pt0c.y) * edge.dx; // correct starting point for clipped lines}else{edge.y0 = (int)(pt1.y);edge.y1 = (int)(pt0.y);edge.x = pt1c.x + (pt1.y - pt1c.y) * edge.dx; // correct starting point for clipped lines}edges.push_back(edge);}
}struct CmpEdges
{bool operator ()(const PolyEdge& e1, const PolyEdge& e2){return e1.y0 - e2.y0 ? e1.y0 < e2.y0 :e1.x - e2.x ? e1.x < e2.x : e1.dx < e2.dx;}
};static void
FillEdgeCollection( Mat& img, std::vector<PolyEdge>& edges, const void* color, int line_type)
{PolyEdge tmp;int i, y, total = (int)edges.size();Size size = img.size();PolyEdge* e;int y_max = INT_MIN, y_min = INT_MAX;int64 x_max = 0xFFFFFFFFFFFFFFFF, x_min = 0x7FFFFFFFFFFFFFFF;int pix_size = (int)img.elemSize();int delta;if (line_type < CV_AA)delta = 0;elsedelta = XY_ONE - 1;if( total < 2 )return;for( i = 0; i < total; i++ ){PolyEdge& e1 = edges[i];CV_Assert( e1.y0 < e1.y1 );// Determine x-coordinate of the end of the edge.// (This is not necessary x-coordinate of any vertex in the array.)int64 x1 = e1.x + (e1.y1 - e1.y0) * e1.dx;y_min = std::min( y_min, e1.y0 );y_max = std::max( y_max, e1.y1 );x_min = std::min( x_min, e1.x );x_max = std::max( x_max, e1.x );x_min = std::min( x_min, x1 );x_max = std::max( x_max, x1 );}if( y_max < 0 || y_min >= size.height || x_max < 0 || x_min >= ((int64)size.width<<XY_SHIFT) )return;std::sort( edges.begin(), edges.end(), CmpEdges() );// start drawingtmp.y0 = INT_MAX;edges.push_back(tmp); // after this point we do not add// any elements to edges, thus we can use pointersi = 0;tmp.next = 0;e = &edges[i];y_max = MIN( y_max, size.height );for( y = e->y0; y < y_max; y++ ){PolyEdge *last, *prelast, *keep_prelast;int draw = 0;int clipline = y < 0;prelast = &tmp;last = tmp.next;while( last || e->y0 == y ){if( last && last->y1 == y ){// exclude edge if y reaches its lower pointprelast->next = last->next;last = last->next;continue;}keep_prelast = prelast;if( last && (e->y0 > y || last->x < e->x) ){// go to the next edge in active listprelast = last;last = last->next;}else if( i < total ){// insert new edge into active list if y reaches its upper pointprelast->next = e;e->next = last;prelast = e;e = &edges[++i];}elsebreak;if( draw ){if( !clipline ){// convert x's from fixed-point to image coordinatesuchar *timg = img.ptr(y);int x1, x2;if (keep_prelast->x > prelast->x){x1 = (int)((prelast->x + delta) >> XY_SHIFT);x2 = (int)(keep_prelast->x >> XY_SHIFT);}else{x1 = (int)((keep_prelast->x + delta) >> XY_SHIFT);x2 = (int)(prelast->x >> XY_SHIFT);}// clip and draw the lineif( x1 < size.width && x2 >= 0 ){if( x1 < 0 )x1 = 0;if( x2 >= size.width )x2 = size.width - 1;ICV_HLINE( timg, x1, x2, color, pix_size );}}keep_prelast->x += keep_prelast->dx;prelast->x += prelast->dx;}draw ^= 1;}// sort edges (using bubble sort)keep_prelast = 0;do{prelast = &tmp;last = tmp.next;PolyEdge *last_exchange = 0;while( last != keep_prelast && last->next != 0 ){PolyEdge *te = last->next;// swap edgesif( last->x > te->x ){prelast->next = te;last->next = te->next;te->next = last;prelast = te;last_exchange = prelast;}else{prelast = last;last = te;}}if (last_exchange == NULL)break;keep_prelast = last_exchange;} while( keep_prelast != tmp.next && keep_prelast != &tmp );}
}

其中填充算法为scan-line polygon filling algorithm,下面转载该文

Polygon Filling? How do you do that?

In order to fill a polygon, we do not want to have to determine the type of polygon that we are filling. The easiest way to avoid this situation is to use an algorithm that works for all three types of polygons. Since both convex and concave polygons are subsets of the complex type, using an algorithm that will work for complex polygon filling should be sufficient for all three types. The scan-line polygon fill algorithm, which employs the odd/even parity concept previously discussed, works for complex polygon filling.

Reminder: The basic concept of the scan-line algorithm is to draw points from edges of odd parity to even parity on each scan-line.
What is a scan-line? A scan-line is a line of constant y value, i.e., y=c, where c lies within our drawing region, e.g., the window on our computer screen.

The scan-line algorithm is outlined next.

When filling a polygon, you will most likely just have a set of vertices, indicating the x and y Cartesian coordinates of each vertex of the polygon. The following steps should be taken to turn your set of vertices into a filled polygon.

1.Initializing All of the Edges:
The first thing that needs to be done is determine how the polygon’s vertices are related. The all_edges table will hold this information.
Each adjacent set of vertices (the first and second, second and third, …, last and first) defines an edge. For each edge, the following information needs to be kept in a table:
缩进 1.The minimum y value of the two vertices.
缩进 2.The maximum y value of the two vertices.
缩进 3.The x value associated with the minimum y value.
缩进 4.The slope of the edge.
The slope of the edge can be calculated from the formula for a line:
y = mx + b;
where m = slope, b = y-intercept,
y0 = maximum y value,
y1 = minimum y value,
x0 = maximum x value,
x1 = minimum x value

The formula for the slope is as follows:
m = (y0 - y1) / (x0 - x1).

For example, the edge values may be kept as follows, where N is equal to the total number of edges - 1 and each index into the all_edges array contains a pointer to the array of edge values.
在这里插入图片描述
2.Initializing the Global Edge Table:
The global edge table will be used to keep track of the edges that are still needed to complete the polygon. Since we will fill the edges from bottom to top and left to right. To do this, the global edge table table should be inserted with edges grouped by increasing minimum y values. Edges with the same minimum y values are sorted on minimum x values as follows:
缩进 1.Place the first edge with a slope that is not equal to zero in the global edge table.
缩进 2.If the slope of the edge is zero, do not add that edge to the global edge table.
缩进 3.For every other edge, start at index 0 and increase the index to the global edge table once each time the current edge’s y value is greater than that of the edge at the current index in the global edge table.

Next, Increase the index to the global edge table once each time the current edge’s x value is greater than and the y value is less than or equal to that of the edge at the current index in the global edge table.

If the index, at any time, is equal to the number of edges currently in the global edge table, do not increase the index.

Place the edge information for minimum y value, maximum y value, x value, and 1/m in the global edge table at the index.

The global edge table should now contain all of the edge information necessary to fill the polygon in order of increasing minimum y and x values.

3.Initializing Parity
The initial parity is even since no edges have been crossed yet.

4.Initializing the Scan-Line
The initial scan-line is equal to the lowest y value for all of the global edges. Since the global edge table is sorted, the scan-line is the minimum y value of the first entry in this table.

5.Initializing the Active Edge Table
The active edge table will be used to keep track of the edges that are intersected by the current scan-line. This should also contain ordered edges. This is initially set up as follows:

Since the global edge table is ordered on minimum y and x values, search, in order, through the global edge table and, for each edge found having a minimum y value equal to the current scan-line, append the edge information for the maximum y value, x value, and 1/m to the active edge table. Do this until an edge is found with a minimum y value greater than the scan line value. The active edge table will now contain ordered edges of those edges that are being filled as such:
在这里插入图片描述
6.Filling the Polygon
Filling the polygon involves deciding whether or not to draw pixels, adding to and removing edges from the active edge table, and updating x values for the next scan-line.

Starting with the initial scan-line, until the active edge table is empty, do the following:
缩进 1.Draw all pixels from the x value of odd to the x value of even parity edge pairs.
缩进 2.Increase the scan-line by 1.
缩进 3.Remove any edges from the active edge table for which the maximum y value is equal to the scan_line.
缩进 4.Update the x value for for each edge in the active edge table using the formula x1 = x0 + 1/m. (This is based on the line formula and the fact that the next scan-line equals the old scan-line plus one.)
缩进 5.Remove any edges from the global edge table for which the minimum y value is equal to the scan-line and place them in the active edge table.
缩进 6.Reorder the edges in the active edge table according to increasing x value. This is done in case edges have crossed.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/163108.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

anaconda中安装pytorch(GPU版)(离线安装)(最简单)

anaconda中安装pytorch&#xff08;GPU版&#xff09;&#xff08;离线安装&#xff09;&#xff08;最简单&#xff09;_anaconda安装pytorch gpu-CSDN博客anaconda里安装pytorch,GPU版本&#xff0c;离线本地安装&#xff0c;新手_anaconda安装pytorch gpuhttps://blog.csdn.…

头歌平台——基于数组的工资处理系统

第1关&#xff1a;数据输入和计算 任务描述 本关任务&#xff1a; 编写函数input_data(char uid[10][5], int salary[10], int csalary[10], int revenue[10], int _water_electricity[10], int _deductions[10])&#xff0c;作用为输入职工的代号&#xff0c;岗位工资&#…

打工人一定要学会找资源~

还有很多小伙伴不知道怎么找资源吗&#xff1f;今天就给大家推荐一下几个资源网站&#xff0c;无论是图片又或是视频。通通都能找到&#xff01; 一、全网1000平台视频解析下载器——XDown 在线视频下载工具&#xff0c;几乎能下全网所有平台的视频&#xff0c;而且下完还能自…

javaEE - 2(11000字详解多线程)

一&#xff1a;多线程带来的的风险-线程安全 线程安全的概念&#xff1a;如果多线程环境下代码运行的结果是符合我们预期的&#xff0c;即在单线程环境应该的结果&#xff0c;则说这个程序是线程安全的。 当多个线程同时访问共享资源时&#xff0c;就会产生线程安全的风险&am…

Unity3D 拖拽赋值组件与通过Find赋值组件的优点与缺点详解

Unity3D是一款流行的游戏开发引擎&#xff0c;提供了丰富的功能和工具&#xff0c;使开发人员能够轻松创建高质量的游戏。在Unity3D中&#xff0c;我们经常需要通过拖拽赋值组件或通过Find赋值组件来实现不同对象之间的交互。本文将详细介绍这两种方法的优点和缺点&#xff0c;…

ICML2021 | RSD: 一种基于几何距离的可迁移回归表征学习方法

目录 引言动机分析主角&#xff08;Principal Angle&#xff09;表征子空间距离正交基错配惩罚可迁移表征学习实验数据集介绍 实验结果总结与展望 论文链接 相关代码已经开源 引言 深度学习的成功依赖大规模的标记数据&#xff0c;然而人工标注数据的代价巨大。域自适应&…

VA01/VA02/VA03 销售订单根据定价和步骤校验权限隐藏价格

1、业务需求 针对用户使用销售订单时&#xff0c;根据定价和步骤顺序&#xff0c;判断是否有权限&#xff0c;没有权限时隐藏销售订单抬头和行项目的部分价格数据 要限制的定价和步骤在spro中的位置 限制的步骤 2、增强实现 2.1权限对象 创建带有定价和步骤的权限对象 分配…

力扣刷题 day48:10-18

1.4的幂 给定一个整数&#xff0c;写一个函数来判断它是否是 4 的幂次方。如果是&#xff0c;返回 true &#xff1b;否则&#xff0c;返回 false 。 整数 n 是 4 的幂次方需满足&#xff1a;存在整数 x 使得 n 4x 方法一&#xff1a;不断除以4 #方法一&#xff1a;不断除…

如何用工业树莓派和MQTT平台打通OT和IT?

一、应用设备 OT端设备&#xff1a;步进电机&#xff0c;MODBUS TCP远程I/O模块&#xff0c;PLC设备 边缘侧设备&#xff1a;宏集工业树莓派&#xff1b; IT端设备&#xff1a;PC、安卓手机&#xff1b; IT端软件&#xff1a;宏集HiveMQ MQTT通信平台 二、原理 宏集工业树…

python之自动化点餐定时任务

1、准备一个可执行的python文件 2、使用定时任务管理器配置定时任务 Cron是linux系统的任务管理器 2.1打开终端或控制台 2.2进入crontab编辑器&#xff1a; crontab -e 编辑crontab文件 crontab -l 列出当前用户的所有定时任务 crontab -r 删除当前用户的crontab文…

Web安全测试详解

前言 随着互联网时代的蓬勃发展&#xff0c;基于Web环境下的应用系统、应用软件也得到了越来越广泛的使用。 目前&#xff0c;很多企业的业务发展都依赖于互联网&#xff0c;比如&#xff0c;网上银行、网络购物、网络游戏等。但&#xff0c;由于很多恶意攻击者想通过截获他人…

虹科 | 解决方案 | 机械免拆压力测试方案

对于发动机的气门卡滞或气门开闭时刻错误、活塞环磨损、喷油嘴泄漏/堵塞等故障&#xff0c;往往需要解体发动机或拆卸部件才能发现&#xff1b;而对于某些轻微的故障&#xff0c;即使解体了发动机后也经常难于肉眼判别 虹科Pico提供的WPS500压力测试方案&#xff0c;可以动态测…

7+非肿瘤+WGCNA+分型+实验,筛选关键基因进一步分型以及表达验证

今天给同学们分享一篇非肿瘤WGCNA分型实验的生信文章“Identification of molecular subtypes and immune infiltration in endometriosis: a novel bioinformatics analysis and In vitro validation”&#xff0c;这篇文章于2023年8月18日发表在Front Immunol期刊上&#xff…

IPV6 ND协议--源码解析【根源分析】

ND协议介绍 ND介绍请阅读上一篇文章&#xff1a;IPv6知识 - ND协议【一文通透】11.NDP协议分析与实践_router solicitation报文中不携带source link-layer address-CSDN博客 ND协议定义了5种ICMPv6报文类型&#xff0c;如下表所示&#xff1a; NS/NA报文主要用于地址解析RS/…

GEE:绘制土地利用类型面积分布柱状图

作者:CSDN @ _养乐多_ 本文记录了,在 Google Earth Engine (GEE)中进行随机森林分类后绘制不同类型面积分布柱状图的代码片段。 完整代码请看博客《GEE:随机森林分类教程(样本制作、特征添加、训练、精度、参数优化、贡献度、统计面积)》 柱状图效果如下所示, 文章目…

高性能计算与多模态处理的探索之旅:英伟达GH200性能优化与GPT-4V的算力加速未来

★多模态大模型&#xff1b;GPU算力&#xff1b;LLMS&#xff1b;LLM&#xff1b;LMM&#xff1b;GPT-4V&#xff1b;GH200&#xff1b;图像识别&#xff1b;目标定位&#xff1b;图像描述&#xff1b;视觉问答&#xff1b;视觉对话&#xff1b;英伟达&#xff1b;Nvidia&#…

leetCode 392. 判断子序列 动态规划 + 优化空间 / 双指针 等多种解法

392. 判断子序列 - 力扣&#xff08;LeetCode&#xff09; 给定字符串 s 和 t &#xff0c;判断 s 是否为 t 的子序列。字符串的一个子序列是原始字符串删除一些&#xff08;也可以不删除&#xff09;字符而不改变剩余字符相对位置形成的新字符串。&#xff08;例如&#xff0c…

剖析深度学习中的epoch与batch_size关系、代码

目录 前言1. 定义2. 代码 前言 为了区分深度学习中这两者的定义&#xff0c;详细讲解其关系以及代码 1. 定义 在 PyTorch 中&#xff0c;“epoch”&#xff08;周期&#xff09;和 “batch size”&#xff08;批大小&#xff09;是训练神经网络时的两个重要概念 它们用于控…

【大数据】Kafka 入门简介

Kafka 入门简介 1.什么是 Kafka2.Kafka 的基本概念3.Kafka 分布式架构4.配置单机版 Kafka4.1 下载并解压包4.2 启动 Kafka4.3 创建 Topic4.4 向 Topic 中发送消息4.5 从 Topic 中消费消息 5.实验5.1 实验一&#xff1a;Python 实现生产者消费者5.2 实验二&#xff1a;消费组实现…

光伏电站绝缘阻抗异常排查方法

安科瑞 崔丽洁 概述 01 光伏发电是依托电力电子技术,利用太阳光照将太阳能转化为电能的系统。光伏发电不需要使用化石燃料&#xff0c;减少了发电时产生的污染&#xff0c;并且减少了能源消耗。光伏发电依托政策扶持&#xff0c;快速在国内普及。光伏发电与传统火电发电原理不同…