使用Python、Contours绘制等高线
主要是通过python、opencv库的子模块Contour来分析灰度图,并绘制等高线
参考文档:https://docs.opencv.org/
安装opencv
pip install opencv-python
分析位图文件,将颜色分层,并绘制等高线
import cv2 as cv
img=cv.imread("terrain.png")
gray=cv.cvtColor(img,cv.COLOR_RGBA2GRAY,0)
ret,thresh=cv.threshold(gray,127,255,cv.THRESH_BINARY)
contours,heirarchy=cv.findContours(thresh,cv.RETR_CCOMP,cv.CHAIN_APPROX_SIMPLE)
cv.drawContours(img,contours,-1,(0,255,0),1)
cv.imshow('aaa',img)
if cv.waitKey(0):
cv.destroyAllWindows()
安装颜色库,用来计算颜色差值
pip install colour
将高度图分成15段(255/17),并将每一段用不同的颜色,由低到高、由红到蓝,绘制等高线
import cv2 as cv
from colour import Color
img=cv.imread("terrain.png")
gray=cv.cvtColor(img,cv.COLOR_RGBA2GRAY,0)
colors=list(Color("red").range_to(Color("blue"),int(255/17)))
for i in range(0,len(colors)):
ret,thresh=cv.threshold(gray,i*255/len(colors),255,cv.THRESH_BINARY)
contours,heirarchy=cv.findContours(thresh,cv.RETR_CCOMP,cv.CHAIN_APPROX_SIMPLE)
cv.drawContours(img,contours,-1,(colors[i].blue*255,colors[i].green*255,colors[i].red*255),1)
cv.imshow('aaa',img)
if cv.waitKey(0):
cv.destroyAllWindows()
由于这里contours是数组,元素是点数据,所以还可以利用xml库输出svg矢量图
import cv2 as cv
from colour import Color
import xml.dom.minidom as minidom
img=cv.imread("terrain.png")
gray=cv.cvtColor(img,cv.COLOR_RGBA2GRAY,0)
colors=list(Color("red").range_to(Color("blue"),int(255/17)))
dom=minidom.getDOMImplementation().createDocument(None,'svg',None)
root=dom.documentElement
root.setAttribute('width',"1024")
root.setAttribute('height',"1024")
root.setAttribute("viewBox","0 0 1024 1024")
root.setAttribute("xmlns","http://www.w3.org/2000/svg")
root.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink")
root.setAttribute("xmlns:sodipodi","http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd")
group=dom.createElement('g')
root.appendChild(group)
for i in range(0,len(colors)):
ret,thresh=cv.threshold(gray,i*255/len(colors),255,cv.THRESH_BINARY)
contours,heirarchy=cv.findContours(thresh,cv.RETR_CCOMP,cv.CHAIN_APPROX_SIMPLE)
for a in contours:
element=dom.createElement('path')
element.setAttribute('style',"fill:none;fill-opacity:0.512111;stroke-width:1.0;stroke:"+colors[i].hex+";stroke-opacity:1")
s="M"
for b in a:
s+=" %d,%d"%(b[0][0],b[0][1])
s+=" z"
element.setAttribute('d',s)
group.appendChild(element)
with open('aaa.svg','w',newline='\n',encoding='utf-8') as f:
dom.writexml(f, addindent='\t', newl='\n',encoding='utf-8')