人口密度图生成过程总共分为两部分
1.利用坐标数据mat文件生成点注释-ground_truth图
2.利用gaussian_filter函数生成人口密度图
数据集介绍:
这里我们采用UCF-QNRF_ECCV18的图片作为训练集,如下图所示。
ground_truth数据集是由mat文件组成的,数据格式为[y0,x0](不同数据集表示的方法不同)表示人头所在的像素点。利用scipy函数即可读取数据。
加载数据,加载图片和mat文件
gt = scipy.io.loadmat("./UCF-QNRF_ECCV18/Test/img_0001_ann.mat")
img = cv2.imread("./UCF-QNRF_ECCV18/Test/img_0001.jpg")
利用mat文件生成点注释-ground_truth图
k = np.zeros((img.shape[0],img.shape[1]))
for i in range(len(gt)):#生成头部点注释图
if gt[i][0] < img.shape[1] and gt[i][1] < img.shape[0]:
k[int(gt[i][1])][int(gt[i][0])] += 1
利用ground_truth图经过高斯滤波
def gaussian_filter_density(gt):
# 初始化密度图
density = np.zeros(gt.shape, dtype=np.float32)
# 获取gt中不为0的元素的个数
gt_count = np.count_nonzero(gt)
# 如果gt全为0,就返回全0的密度图
if gt_count == 0:
return density
sigma = 16
density += scipy.ndimage.filters.gaussian_filter(gt, sigma, mode='constant')
return density
完整代码:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm as CM
import cv2
import scipy.ndimage
import scipy.io
def gaussian_filter_density(gt):
# 初始化密度图
density = np.zeros(gt.shape, dtype=np.float32)
# 获取gt中不为0的元素的个数
gt_count = np.count_nonzero(gt)
# 如果gt全为0,就返回全0的密度图
if gt_count == 0:
return density
sigma = 16
density += scipy.ndimage.filters.gaussian_filter(gt, sigma, mode='constant')
return density
def density_map(img,gt):
k = np.zeros((img.shape[0],img.shape[1]))
for i in range(len(gt)):#生成头部点注释图
if gt[i][0] < img.shape[1] and gt[i][1] < img.shape[0]:
k[int(gt[i][1])][int(gt[i][0])] += 1
k = gaussian_filter_density(k)
return k
gt = scipy.io.loadmat("./UCF-QNRF_ECCV18/Test/img_0001_ann.mat")
img = cv2.imread("./UCF-QNRF_ECCV18/Test/img_0001.jpg")
groundtruth = density_map(img,gt['annPoints'])
plt.figure(2)
plt.imshow(groundtruth,cmap=CM.jet)
plt.show()
结果: