代码拉取完成,页面将自动刷新
import shapefile
import math
from PIL import Image, ImageDraw
"""
Python图像库PIL(Python Image Library)是python的第三方图像处理库,
但是由于其强大的功能与众多的使用人数,几乎已经被认为是python官方图像处理库了。
"""
# 地理坐标转换为屏幕坐标
def world2screen(bbox, w, h, x, y):
minx, miny, maxx, maxy = bbox
xdist = maxx - minx
ydist = maxy - miny
xratio = w / xdist
yratio = h / ydist
px = int(w - ((maxx - x) * xratio))
py = int(((maxy - y) * yratio))
return px, py # 为了适应pngcanvas的坐标系,对y做了翻转
def main():
r = shapefile.Reader("shapefiles/GIS_CensusTract/GIS_CensusTract_poly")
width = 600
height = 400
# 初始化PIL库的Image对象
img = Image.new("RGB", (width, height), (255, 255, 255))
# PIL库的Draw模块用于填充多边形
draw = ImageDraw.Draw(img)
# 获取人口和区域
pop_index = None
area_index = None
# 绘制人口普查区域阴影
for i, f in enumerate(r.fields):
if f[0] == "POPULAT11":
pop_index = i-1
elif f[0] == "AREASQKM":
area_index = i-1
# 绘制多边形
for sr in r.shapeRecords():
density = sr.record[pop_index]/sr.record[area_index]
# weight 可以用来配置人口的颜色深浅
weight = min(math.sqrt(density/80.0), 1.0)*50
# print(density,"----",weight)
R = int(205 - weight)
G = int(215 - weight)
B = int(245 - weight)
pixels = []
for x, y in sr.shape.points:
(px, py) = world2screen(r.bbox, width, height, x, y)
pixels.append((px, py))
draw.polygon(pixels, fill=(R, G, B), outline=(255, 255, 255))
# img.save("choropleth.png")
img.show()
img.close()
r.close()
if __name__ == '__main__':
main()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。