使用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')

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值