翻译自:https://www.codeproject.com/Articles/114797/Polyline-Simplification#headingDPN
整个记录关于算法的部分是翻译来的,原作者实现的语言是C++,但是我看不懂这类代码,于是自己用Python实现了一遍,其中可能会有错误的地方,欢迎指出来让我改正。
from shapefile import Reader, Writer
import numpy as np
import math
import matplotlib.pyplot as plt
# 该shapefile文件内含一条线段,坐标系为:3857
shp = Reader('./vector/lyr_line.shp', encoding='utf-8')
feat = shp.shape(0)
line = np.array(feat.points)
# 保存为shapefile文件
def shpGen(fileName, pts):
w = Writer(fileName, encoding='utf-8', shapeType=3)
w.fields = shp.fields
w.line([pts])
w.record("测试", 3)
w.close()
# 点到线距离
def point2lineDistance(x0,y0,x1,y1,x2,y2):
a =x2 -x1
b = y2 - y1
c = b*x1- a*y1
return abs(a*y0 - b*x0 + c) / math.sqrt(a*a + b*b)
# return abs((x2-x1)*(y1-y0)-(x1-x0)*(y2-y1)) / math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))
# 点到点距离
def point2pointDistance(x1,y1,x2,y2):
dx = x2-x1
dy = y2-y1
return math.sqrt(dx*dx+dy*dy)
# 绘制
def plotLine(pts, simplifyLst, newlabel:str):
plt.figure(figsize=(15, 6))
plt.plot(pts[:,0], pts[:,1], 'r-*', linewidth=0.5, mfc='red', mec='red', label='origin')
plt.plot(simplifyLst[:,0], simplifyLst[:,1], 'b-s', linewidth=0.5, mfc='blue', mec='blue', label=newlabel)
plt.legend(loc='upper left')
plt.show()
该算法是一个时间复杂度为\({O(n)}\)的暴力算法。在连续的顶点中,与当前某一个key(简化过程中标记保留的顶点)的距离太近时会被去掉。
起止顶点一般会保留作为简化线的一部分,故标记为key,从第一个key(第一个顶点)开始,算法将遍历整条线段,所有连续顶点中,移除那些距离不超过容忍值的顶点,而第一个超过容忍值的顶点将标记为下一个key,从新key开始,算法重新遍历余下的点并重复上述过程,直到最后一个点。

def NearestSimplify(tolorence:float, pts:list) -> list:
start = 0
validFlags = np.zeros((len(pts), ), dtype="bool")
for i in range(1, len(pts)):
dist = math.sqrt(math.pow(pts[i][0]- pts[start][0], 2) +
math.pow(pts[i][1] - pts[start][1], 2))
if dist > tolorence:
validFlags[i] = True
start = i
validFlags[0] = True
return validFlags
flags = NearestSimplify(20, feat.points)
plotLine(line, line[flags], "Radial Distance")

flags = NearestSimplify(10, feat.points)
plotLine(line, line[flags], "Radial Distance")

临近点算法将点-点距离作为误差判据,而垂直距离简化则是将点-线段的距离作为误差判据。对于每个顶点Vi,需要计算它与线段[Vi-1, Vi+1]的垂直距离,距离小于给定容忍值的点将被移除。过程如下图所示:

最开始处理前三个顶点,计算第二个顶点的垂直距离,与容忍值作比较,大于则标记为key。然后算法往前移动开始处理下一个前三个顶点,第二次距离小于容忍值,移除中间顶点。重复直到处理所有顶点。
注意:对于每个被移除的顶点Vi,下一个可能被移除的候选顶点是Vi+2。这意味着原始多段线的点数最多只能减少50%。为了获得更高的顶点减少率,需要多次遍历。
def PerpendicularSimplify(tolorence:float, pts:list) -> list:
sp = 0
ep = 2
validFlags = np.zeros((len(pts), ), dtype="bool")
for i in range(1, len(pts) - 1):
verDist = point2lineDistance(
pts[i][0], pts[i][1],
pts[sp][0], pts[sp][1],
pts[ep][0], pts[ep][1])
if verDist > tolorence:
validFlags[i] = True
sp = i
ep = i + 2
validFlags[0] = validFlags[-1] = True
return validFlags
perLine = PerpendicularSimplify(20, feat.points)
plotLine(line, line[perLine], "Perpendicular Distance")

perLine = PerpendicularSimplify(10, feat.points)
plotLine(line, line[perLine], "Perpendicular Distance")

该算法使用点-线距离作距离判断。首先定义一条线段,起止点为原始线段的前两个顶点,对于每一个连续的顶点vi,计算它与前述线段的垂直距离,当距离超过容忍值时,将顶点vi - 1标记为key。顶点vi和vi + 1用来定义新的线段,算法重复直到最后一个点。下图为算法演示:

红色的条带由指定的容忍值生成,而线段则由原始线的前两个顶点生成。第三个顶点不在红色条带内,意味着该顶点是一个key。通过第二,三顶点定义新的条带,位于条带内的最后一个顶点也标记为key,而其他点则移除。算法重复直到新吊带包含原始线段的最后一个顶点。
def ReuWitkamSimplify(tolorence:float, pts:list) -> list:
sp = 0
ep = 1
validFlags = np.zeros((len(pts), ), dtype="bool")
for i in range(2, len(pts)):
verDist = point2lineDistance(
pts[i][0], pts[i][1],
pts[sp][0], pts[sp][1],
pts[ep][0], pts[ep][1])
if verDist > tolorence:
validFlags[i-1] = True
sp = ep
ep = i
validFlags[0] = validFlags[-1] = True
return validFlags
rLine = ReuWitkamSimplify(20, feat.points)
plotLine(line, line[rLine], "Reumann-Witkam")

rLine = ReuWitkamSimplify(10, feat.points)
plotLine(line, line[rLine], "Reumann-Witkam")

Ophein 使用 最小和最大距离容忍值来约束搜索区域。对于连续的顶点\({v_i}\),它与当前\({key}\)(通常是\({v_0}\))的径向距离可以被计算出来。在容忍值范围内的最后一个顶点被用来定义一条射线\({R(v_{key} , v_i)}\),如果这样的顶点不存在,那么射线将被定义为\({R(v_{key} , v_{key + 1})}\)。计算每一个连续的顶点\({v_j}\)(在\({v_i}\)后边)与射线\({R}\) 间的垂直距离, 当该距离超过最小容忍值或者当\({v_j}\)与\({v_k}\)间的辐射距离大于最大容忍值时,在\({v_{j-1}}\)位置上的顶点,将被认为是一个新\({key}\)。

值得注意的是,关于如何定义射线\({R(v_{key},v_i)}\) 去控制搜索区域的方法存在多个,可能的方法有如下几种:

def opheimSimplify(minTolorence:int, maxTolorence:int, pts) -> list:
vKey = 0
validPtsLst = np.zeros((len(pts),), dtype='bool')
for i in range(vKey, len(pts)):
if point2pointDistance(pts[vKey][0], pts[vKey][1], pts[i][0], pts[i][1]) > minTolorence:
vi = i
break
for j in range(vi + 1, len(pts)):
vj2rayDist = point2lineDistance(
pts[j][0], pts[j][1],
pts[vKey][0], pts[vKey][1],
pts[vi][0], pts[vi][1])
radialDist = point2pointDistance(pts[vKey][0], pts[vKey][1], pts[j][0], pts[j][1])
if vj2rayDist <= minTolorence or radialDist > maxTolorence:
vKey = j - 1
validPtsLst[j-1] = True
else:
continue
validPtsLst[0] = validPtsLst[-1]= True
return np.array(validPtsLst)
opheim = opheimSimplify(2, 20, np.array(feat.points))
plotLine(line, line[opheim], "opheim")

opheim = opheimSimplify(2, 10, np.array(feat.points))
plotLine(line, line[opheim], "opheim")

Lang 简化算法定义一个固定大小的搜索区域,它的第一个和最后一个点来自线段的同一个片段——用来计算处于中间的顶点的垂直距离。若任何计算出的距离大于指定的容忍值,那么搜索区域将通过排除其最后一个顶点进行收缩,这个过程会一直重复直到所有垂直距离小于特定的容忍值,或者中间顶点全部排除。所有中间节点移除后,新的搜索区域将以旧搜索区域的最后一个点作为起点进行构建。

The search region is constructed using a look_ahead value of 4. For each intermediate vertex, its perpendicular distance to the segment S (v0, v4) is calculated. Since at least one distance is greater than the tolerance, the search region is reduced by one vertex. After recalculating the distances to S (v0, v3), all intermediate vertices fall within the tolerance. The last vertex of the search region v3 defines a new key. This process repeats itself by updating the search region and defining a new segment S (v3, v7).
搜索区域使用前四个顶点来生成。计算每一个中间顶点到片段S(v0, v4)的垂直距离,只要至少存在一个顶点的垂直距离超过容忍值,搜索区域便简化一个顶点。再重复计算中间顶点到片段S(v0, v3),所有的中间顶点到片段S的垂直距离都位于容忍值内,搜索区域的最后一个顶点v3作为一个新key同时它也用来定义一个新的区域(片段)S(v3, v7)。
def langSimplify(tolorence, pts, steps=0) -> list:
vKey = 0
end = 2
validLst = np.zeros((len(pts),), dtype='bool')
if(steps == 0):
maxSteps = len(pts) - 1
else:
maxSteps = steps
while vKey < maxSteps and end < maxSteps:
isBigger = False
# print("segment:(%s,%s)" % (vKey, end))
for i in range(vKey + 1, end):
perDist = point2lineDistance(
pts[i][0], pts[i][1],
pts[vKey][0], pts[vKey][1],
pts[end][0], pts[end][1])
if perDist > tolorence:
isBigger = True
end -= 1
break
else:
continue
if not isBigger:
vKey = end
end += 2
validLst[vKey] = True
validLst[0] = validLst[-1] = True
return validLst
langLine = langSimplify(20, feat.points, steps=0)
plotLine(line, line[langLine], "Lang")

langLine = langSimplify(10, feat.points, steps=0)
plotLine(line, line[langLine], "Lang")

Douglas-Peucker算法使用点-边距离作为误差衡量标准。该算法从连接原始Polyline的第一个和最后一个顶点的边开始,计算所有中间顶点到边的距离,距离该边最远的顶点,如果其距离大于指定的公差,将被标记为Key并添加到简化结果中。这个过程将对当前简化中的每条边进行递归,直到原始Polyline的所有顶点与当前考察的边的距离都在允许误差范围内。该过程如下图所示:
初始时,简化结果只有一条边(起点-终点)。第一步中,将第四个顶点标记为一个Key,并相应地加入到简化结果中;第二步,处理当前结果中的第一条边,到该边的最大顶点距离低于容差,因此不添加任何点;在第三步中,当前简化的第二个边找到了一个Key(点到边的距离大于容差)。这条边在这个Key处被分割,这个新的Key添加到简化结果中。这个过程一直继续下去,直到找不到新的Key为止。注意,在每个步骤中,只处理当前简化结果的一条边。
def douglasPeuckerSimplify(tolorence, pts) -> list:
start = 0
end = len(pts) - 1
def findPt(start, end) -> list:
curPt = 0
maxDist = 0
for i in range(start + 1, end):
perpenDist = point2lineDistance(
pts[i][0], pts[i][1],
pts[start][0], pts[start][1],
pts[end][0], pts[end][1])
if perpenDist > maxDist:
maxDist = perpenDist
curPt = i
if maxDist > tolorence:
preKey = findPt(start, curPt)
postKey = findPt(curPt, end)
return [] + preKey + postKey
else:
return [pts[end]]
return [pts[0]] + findPt(start, end)
res = douglasPeuckerSimplify(20, feat.points)
plotLine(line, np.array(res), "Douglas-Peucker")

res = douglasPeuckerSimplify(10, feat.points)
plotLine(line, np.array(res), "Douglas-Peucker")

res = douglasPeuckerSimplify(5, feat.points)
plotLine(line, np.array(res), "Douglas-Peucker")

目录一.加解密算法数字签名对称加密DES(DataEncryptionStandard)3DES(TripleDES)AES(AdvancedEncryptionStandard)RSA加密法DSA(DigitalSignatureAlgorithm)ECC(EllipticCurvesCryptography)非对称加密签名与加密过程非对称加密的应用对称加密与非对称加密的结合二.数字证书图解一.加解密算法加密简单而言就是通过一种算法将明文信息转换成密文信息,信息的的接收方能够通过密钥对密文信息进行解密获得明文信息的过程。根据加解密的密钥是否相同,算法可以分为对称加密、非对称加密、对称加密和非
1.问题描述使用Python的turtle(海龟绘图)模块提供的函数绘制直线。2.问题分析一幅复杂的图形通常都可以由点、直线、三角形、矩形、平行四边形、圆、椭圆和圆弧等基本图形组成。其中的三角形、矩形、平行四边形又可以由直线组成,而直线又是由两个点确定的。我们使用Python的turtle模块所提供的函数来绘制直线。在使用之前我们先介绍一下turtle模块的相关知识点。turtle模块提供面向对象和面向过程两种形式的海龟绘图基本组件。面向对象的接口类如下:1)TurtleScreen类:定义图形窗口作为绘图海龟的运动场。它的构造器需要一个tkinter.Canvas或ScrolledCanva
我一直在尝试用Ruby实现Luhn算法。我一直在执行以下步骤:该公式根据其包含的校验位验证数字,该校验位通常附加到部分帐号以生成完整帐号。此帐号必须通过以下测试:从最右边的校验位开始向左移动,每第二个数字的值加倍。将乘积的数字(例如,10=1+0=1、14=1+4=5)与原始数字的未加倍数字相加。如果总模10等于0(如果总和以零结尾),则根据Luhn公式该数字有效;否则无效。http://en.wikipedia.org/wiki/Luhn_algorithm这是我想出的:defvalidCreditCard(cardNumber)sum=0nums=cardNumber.to_s.s
下面是我写的一个计算斐波那契数列中的值的方法:deffib(n)ifn==0return0endifn==1return1endifn>=2returnfib(n-1)+(fib(n-2))endend它工作到n=14,但在那之后我收到一条消息说程序响应时间太长(我正在使用repl.it)。有人知道为什么会这样吗? 最佳答案 Naivefibonacci进行了大量的重复计算-在fib(14)fib(4)中计算了很多次。您可以将内存添加到您的算法中以使其更快:deffib(n,memo={})ifn==0||n==1returnnen
为了防止在迁移到生产站点期间出现数据库事务错误,我们遵循了https://github.com/LendingHome/zero_downtime_migrations中列出的建议。(具体由https://robots.thoughtbot.com/how-to-create-postgres-indexes-concurrently-in概述),但在特别大的表上创建索引期间,即使是索引创建的“并发”方法也会锁定表并导致该表上的任何ActiveRecord创建或更新导致各自的事务失败有PG::InFailedSqlTransaction异常。下面是我们运行Rails4.2(使用Acti
编辑:更改了标题。我对两个部分是否相同不太感兴趣,而是如果它们在一定的公差范围内彼此共线。如果是这样,那么这些线应该聚集在一起作为一个单独的线段。编辑:我想有一个简短的说法:我试图以一种有效的方式将相似的线段聚集在一起。假设我有线段f(fx0,fy0)和(fx1,fy1)和g(gx0,gy0)和(gx1,gy1)这些来自计算机视觉算法边缘检测器之类的东西,在某些情况下,两条线基本相同,但由于像素容差而被视为两条不同的线。有几种情况f和g共享完全相同的端点,例如:f=(0,0),(10,10)g=(0,0),(10,10)f和g共享大致相同的端点和大致相同的长度,例如:f=(0,0.01
我正在开发一个类似微论坛的项目,其中一个特殊用户发布一条快速(接近推文大小)的主题消息,订阅者可以用他们自己的类似大小的消息来响应。直截了当,没有任何形式的“挖掘”或投票,只是每个主题消息的响应按时间顺序排列。但预计会有很高的流量。我们想根据它们引起的响应嗡嗡声来标记主题消息,使用0到10的等级。在谷歌上搜索了一段时间的趋势算法和开源社区应用示例,到目前为止已经收集到两个有趣的引用资料,但我还没有完全理解它们:Understandingalgorithmsformeasuringtrends,关于使用基线趋势算法比较维基百科页面浏览量的讨论,在SO上。TheBritneySpearsP
为了简洁起见,我想优化以下代码。x1.each{|x|x2.each{|y|....xN.each{|z|yield{}.merge(x).merge(y)......merge(z)}}}假设x1,x2,...,xN是Enumerator对象。以上内容不够简洁它与x1、x2作为Array一起工作,但不是作为Enumerators因为应该为内部循环重置枚举器迭代器我试过了,但没有成功:[x1,x2,...,xN].reduce(:product).map{|x|x.reduce:merge}有什么建议吗?更新目前解决了:[x1,x2,...,xN].map(:to_a).reduce(
我收到错误:unsupportedcipheralgorithm(AES-256-GCM)(RuntimeError)但我似乎具备所有要求:ruby版本:$ruby--versionruby2.1.2p95OpenSSL会列出gcm:$opensslenc-help2>&1|grepgcm-aes-128-ecb-aes-128-gcm-aes-128-ofb-aes-192-ecb-aes-192-gcm-aes-192-ofb-aes-256-ecb-aes-256-gcm-aes-256-ofbRuby解释器:$irb2.1.2:001>require'openssl';puts
文章目录一.Dijkstra算法想解决的问题二.Dijkstra算法理论三.java代码实现一.Dijkstra算法想解决的问题解决的问题:求解单源最短路径,即各个节点到达源点的最短路径或权值考察其他所有节点到源点的最短路径和长度局限性:无法解决权值为负数的情况二.Dijkstra算法理论参数:S记录当前已经处理过的源点到最短节点U记录还未处理的节点dist[]记录各个节点到起始节点的最短权值path[]记录各个节点的上一级节点(用来联系该节点到起始节点的路径)Dijkstra算法步骤:(1)初始化:顶点集S:节点A到自已的最短路径长度为0。只包含源点,即S={A}顶点集U:包含除A外的其他顶