Datasets:

Modalities:
Image
Text
ArXiv:
License:
File size: 2,577 Bytes
3383315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# -- coding: utf-8 --
import h5py
import scipy
import scipy.io as io
import numpy as np
import os
import glob
from matplotlib import pyplot as plt
from scipy import spatial, ndimage
from multiprocessing import Pool
from functools import partial
import time
import json


def gaussian_filter_density(gt):
    density = np.zeros(gt.shape, dtype=np.float32)
    gt_count = np.count_nonzero(gt)
    if gt_count == 0:
        return density

    pts = np.array(list(zip(np.nonzero(gt)[1], np.nonzero(gt)[0])))
    leafsize = 2048
    # build kdtree
    tree = spatial.KDTree(pts.copy(), leafsize=leafsize)
    # query kdtree
    distances, locations = tree.query(pts, k=4)

    for i, pt in enumerate(pts):
        pt2d = np.zeros(gt.shape, dtype=np.float32)
        pt2d[pt[1], pt[0]] = 1.0
        if gt_count > 1:
            sigma = (distances[i][1] + distances[i][2] + distances[i][3]) * 0.1
        else:
            sigma = np.average(np.array(gt.shape)) / 2.0 / 2.0  # case: 1 point
        sigma = 6
        density += scipy.ndimage.filters.gaussian_filter(pt2d, sigma, mode="constant")

    return density


def process(idx, img_paths):
    start = time.time()
    img_path = img_paths[idx]
    mat_path = (
        img_path.replace(".jpg", ".mat")
        .replace("images", "ground_truth")
        .replace("img", "GT_img")
    )
    mat = io.loadmat(mat_path)
    img = plt.imread(img_path)
    k = np.zeros((int(img.shape[0] / 2), int(img.shape[1] / 2)))
    gt = mat["locations"]
    for i in range(0, len(gt)):
        if (
            int(gt[i][1] / 2) < img.shape[0] / 2
            and int(gt[i][0] / 2) < img.shape[1] / 2
        ):
            k[int(gt[i][1] / 2), int(gt[i][0] / 2)] = 1
    k = gaussian_filter_density(k)

    with h5py.File(mat_path.replace("mat", "h5"), "w") as hf:
        hf["density"] = k
    end = time.time()
    print(idx, len(img_paths), img_path, str(end - start) + "s")


if __name__ == "__main__":

    img_paths = []
    data_path = "."
    for img_path in glob.glob(os.path.join(data_path, "*/images", "*.jpg")):
        h5_path = (
            img_path.replace(".jpg", ".h5")
            .replace("images", "ground_truth")
            .replace("img", "GT_img")
        )
        if not os.path.exists(h5_path):
            img_paths.append(img_path)

    img_paths.sort()
    print(img_paths)
    print(len(img_paths))

    pool = Pool(10)
    partial = partial(process, img_paths=img_paths)
    _ = pool.map(partial, range(len(img_paths)))