OpenCV是个计算机视觉和机器学习软件库。应用领域也比较广,包括图片识别,运动跟踪,计算机视觉等等。提供大量的Python接口。
在python中的安装:
pip install opencv-python
这里的案例是先使用Basemap画初始地图,然后在初始地图上画点。由于初始地图画的时间比较久,生成图片的数量也比较大,故先保存初始地图,利用plt转换经纬度坐标为像素坐标后,利用opencv加载已有图片画点。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import cv2 as cv
def load_map():
fig = plt.figure(figsize=(2.65, 3),dpi=300)
ax = fig.add_subplot(1,1,1)
plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0)
m = Basemap(llcrnrlon=118.05,llcrnrlat=24.4,urcrnrlon=118.2,urcrnrlat=24.57)
m.readshapefile('island',name='island',drawbounds=True,linewidth=0.5,color='#862E21')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
return m, ax, fig
basemap, ax, fig = load_map()
x, y = basemap(station['lon'].to_list(), station['lat'].to_list())
basemap.scatter(x, y, marker='D', color='#B33F2D', s=10, zorder=0)
for i in tcd.index:
lons, lats = to_loc(tcd['FENCE_LOC'][i])
ax.plot(lons, lats, '-', lw=0.5, color='#3D698B', marker=None, zorder=2)
plt.savefig(PLOT + '{}.png'.format('Parking_Lots'))
这个Parking_Lots.png就是后面要在上面画点的图片。
df_shot = gj[gj.time == time]
x = df_shot['lon'].to_list()
y = df_shot['lat'].to_list() # 获得x,y的经纬度坐标
basemap, ax, fig = load_map()
# transform coor to pixel
points, = ax.plot(x, y)
xi, yi = points.get_data()
xy_pixels = ax.transData.transform(np.vstack([xi, yi]).T)
xpix, ypix = xy_pixels.T
width, height = fig.canvas.get_width_height()
ypix = height - ypix # for cv, (0,0) is at lower left while (0,0) is at upper right for others
xpix = xpix.astype('int')
ypix = ypix.astype('int')
注意:opencv(0,0)是在左下角,别的大多在右上角。所以有ypix = height - ypix
的这一步
img = cv.imread(PLOT + 'Parking_Lots.png') # 读取图片
for xi, yi in zip(xpix, ypix):
cv.circle(img, (xi, yi), 5, (0, 140, 255), -1) # BGR in cv
cv.imwrite(PLOT + 'Time_Panel.png', img)
注意:
cv.imshow('img',img)
cv.waitKey()
cv.destroyAllWindows()
cv2.circle(img, center, radius, color[, thickness[, lineType[, shift]]])