Mainly through python, the submodule Contour of the opencv library to analyze the grayscale image and draw the contour line
Reference documentation: https://docs.opencv.org/
install opencv
pip install opencv-python
Analyze bitmap files, layer colors, and draw contours
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()
Install the color library to calculate the color difference
pip install colour
Divide the height map into 15 segments (255/17), and use different colors for each segment, from low to high, from red to blue, and draw contour lines
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()
Since the contours here are arrays and the elements are point data, you can also use the xml library to output svg vector graphics
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')