1. 前言
记录密度图的生成,防止以后找不到。代码也是从别人那得来的
2. 高斯核模糊
在生成伪装密度图时,使用如下公式:
\[F(x) = \sum^N_{i=1} \delta(x-x_i) * G_{\sigma}(x) \]其实就是在有人头的地方,首先把像素的值设为1,然后对它及周围的区域进行高斯平滑
这就是模糊图放大后的样子。
3. 代码
import scipy.io as io # 读取mat文件的坐标
import cv2 # 读取图像和在高斯核计算时使用
import numpy as np
from matplotlib import pyplot as plt
# 获取标注
pixes = io.loadmat("./GT_IMG_1.mat")
counts = pixes['image_info'][0][0][0][0][1][0][0] # 标签总人数 嵌套了很多层数组
xy = pixes['image_info'][0][0][0][0][0] # (counts,2)的数组
# 获得高斯核
def fspecial(ksize_x=5, ksize_y = 5, sigma=4):
# 返回大小为(ksize,ksize)的二维高斯滤波器核矩阵
# 完全等价于matlab中的fspecial('Gaussian',[ksize, ksize],sigma);
kx = cv2.getGaussianKernel(ksize_x, sigma)
ky = cv2.getGaussianKernel(ksize_y, sigma)
return np.multiply(kx,np.transpose(ky)) # 原理可参考https://blog.csdn.net/yl_best/article/details/106357056
# 读取图片文件主要是为了获取尺寸
from PIL import Image
img = Image.open("./IMG_1.jpg").convert("L")
img = np.array(img)
# 以灰度图形式显示,不显示坐标轴
plt.imshow(img,cmap='Greys_r')
plt.axis('off')
plt.show()
# 开始生成密度图了
h,w = img.shape
# 密度图
labels = np.zeros(shape=(h,w))
for loc in xy:
f_size = 15
sigma = 4.0
H = fspecial(f_size,f_size,sigma)
x = min(abs(int(loc[0])),int(w)) # 头部坐标
y = min(abs(int(loc[1])),int(h)) # 防止越界
# 邻域的对角 考虑选择 (x1,y1) 到 (x2,y2) 区域
x1 = x - f_size/2 ; y1 = y - f_size/2
x2 = x + f_size/2 ; y2 = y + f_size/2
dfx1 = 0; dfy1 = 0; dfx2 = 0; dfy2 = 0 # 偏移
change_H = False
if x1 < 0 :
# 左上角在图像外了
dfx1 = abs(x1) # 偏移量就是它的绝对值
x1 = 0 # 左上角直接置零,源码中是1,因为matlab矩阵索引从0开始
change_H = True
if y1 < 0:
dfy1 = abs(y1)
y1 = 0
change_H = True
if x2 > w:
dfx2 = x2 - w
x2 =w-1 # 右下角超出,那么直接是最后一行/列,索引值是h-1和w-1
change_H =True
if y2 > h:
dfy2 = y2 -h
y2 = h-1
change_H =True
x1h = 1+dfx1
y1h = 1 + dfy1
x2h = f_size - dfx2 # x2h-x1h +1 = f_size - dfx2 - dfx1 其中dfx2+dfx1
y2h = f_size - dfy2 # y2h-y1h +1 = f_size - dfy2 -1 - dfy1 +1 = f_size - dfy2 - dfy1
if change_H:
H = fspecial(int(y2h-y1h+1), int(x2h-x1h+1),sigma)
labels[int(y1):int(y2), int(x1):int(x2)] = labels[int(y1):int(y2), int(x1):int(x2)] + H
plt.imshow(labels,cmap='jet')
plt.axis('off')
标签:中密度,int,ShanghaiTechA,集为例,ksize,y1,y2,sigma,size
From: https://www.cnblogs.com/x-ocean/p/16829098.html