Beispiel #1
0
def example2():
    data_1 = load_data_from_file("test_data.txt")
    data_2 = load_data_from_file("test_data2.txt")

    hm = HeatMap(data_1)
    hit_img = hm.clickmap()
    hm2 = HeatMap(data_2)
    hit_img2 = hm2.clickmap(base=hit_img, color=(0, 0, 255, 255))
    hit_img2.save("hit2.png")
Beispiel #2
0
def main():
    # download test data
    # url = "https://raw.github.com/oldj/pyheatmap/master/examples/test_data.txt"
    # sdata = urllib.request.urlopen(url).read().split("\n")

    with open("test_data.txt", 'r') as f:
        sdata = [line.replace("\n", "") for line in f.readlines()]
    data = []
    for ln in sdata:
        a = ln.split(",")
        if len(a) != 2:
            continue
        a = [int(i) for i in a]
        data.append(a)

    # data = get_test_data()

    # list -> np.ndarray
    data = np.array(data)
    bg_image = get_bg()

    starttime = datetime.datetime.now()

    # start painting
    for i in range(5):
        hm = HeatMap(data, )
        doHeatmap(hm, base=bg_image)

    endtime = datetime.datetime.now()
    print(f"It costs {(endtime - starttime).seconds}s.")
Beispiel #3
0
def test():

    print("load data..")
    mins = []
    data = []

    url = 'http://apluspre.taobao.ali.com/aplus/pub/udataResult.htm?spmId=1.6659421&action=udataAction&event_submit_do_getHotData=y'
    sdata = urllib.urlopen(url).read().split("\n")
    for ln in sdata:
        a = ln.split(",")
        if len(a) != 3 or abs(int(a[0])) > 700 or int(a[1]) > 10000:
            continue
        mins.append(int(a[0]))

    imin = min(mins)
    if imin >= 0:
        imin = 0

    for ln in sdata:
        a = ln.split(",")
        if len(a) != 3:
            continue
        a = [int(a[0]) - imin, int(a[1]), int(a[2])]
        data.append(a)

    starttime = time.clock()
    print("painting..")
    hm = HeatMap(data, None, 1400, 10000)
    hm.heatmap(save_as="heat.png")
    endtime = time.clock()
    print(endtime - starttime)
    print("done.")
Beispiel #4
0
def heatmap(img, output, img_num, num_ppl):
    print('generating heat map for img', img_num)
    out_cpu = output.cpu().detach()
    den = out_cpu[0].permute(1, 2, 0).numpy()
    den = den[:, :, 0]
    print('output shape:{}'.format(den.shape))

    den_resized = np.zeros(
        (den.shape[0] * SCALING_FACTOR, den.shape[1] * SCALING_FACTOR))
    for i in range(den_resized.shape[0]):
        for j in range(den_resized.shape[1]):
            den_resized[i][j] = den[int(i / SCALING_FACTOR)][int(
                j / SCALING_FACTOR)] / (SCALING_FACTOR * SCALING_FACTOR)
    den = den_resized
    den = den * 10 / np.max(den)

    img_text = write_text(img, num_ppl)
    img_path = "out/" + str(img_num) + ".jpg"
    cv2.imwrite(img_path, img_text)

    w = img.shape[1]
    h = img.shape[0]

    data = []
    for j in range(len(den)):
        for i in range(len(den[0])):
            for k in range(int(den[j][i])):
                data.append([i + 1, j + 1])
    hm = HeatMap(data, base=img_path)
    hm.heatmap(save_as='out/' + 'heat_' + '_' + str(img_num) + '_' +
               str(int(num_ppl)) + '.jpg')
Beispiel #5
0
def getHeatMap(request):

    url = "https://raw.github.com/oldj/pyheatmap/master/examples/test_data.txt"
    sdata = urllib.urlopen(url).read().split("\n")
    mins = []
    data = []
    for ln in sdata:
        a = ln.split(",")
        if len(a) != 3:
            continue
        mins.append(int(a[0]))

    imin = min(mins)

    for ln in sdata:
        a = ln.split(",")
        if len(a) != 3:
            continue
        a = [int(a[0]) + imin, int(a[1]), int(a[2])]
        data.append(a)

    hm = HeatMap(data, None, 1400, 10000)
    hm.heatmap(save_as="heat.png")

    return HttpResponse("complete")
Beispiel #6
0
def heatmap(den, img):
    den_resized = np.zeros((den.shape[0] * 4, den.shape[1] * 4))
    for i in range(den_resized.shape[0]):
        for j in range(den_resized.shape[1]):
            den_resized[i][j] = den[int(i / 4)][int(j / 4)] / 16
    den = den_resized

    count = np.sum(den)

    data2 = np.asarray(den * 25)

    histogram = np.sum(data2, axis=0)
    histogram[histogram < 0] = 0
    histogram = np.around(histogram)

    x_range = [np.min(histogram), np.max(histogram)]
    plt.xlabel("Position along the frame width")
    plt.ylabel("Number of People")
    plt.plot(list(range(data2.shape[1])), histogram)
    plt.savefig('./test/count_plot.jpg')
    den = den * 10 / np.max(den)
    w = img.shape[1]
    h = img.shape[0]

    data = []

    for j in range(len(den)):
        for i in range(len(den[0])):
            for k in range(int(den[j][i])):
                data.append([i + 1, j + 1])

    hm = HeatMap(data, base='./test/img.jpg')

    return hm
def heatmap(den, img_num, dataset, info):
    print('generating heat map for img', img_num)
    print('shape:', den.shape)

    if info == 'pre':
        den_resized = np.zeros((den.shape[0] * 4, den.shape[1] * 4))
        for i in range(den_resized.shape[0]):
            for j in range(den_resized.shape[1]):
                den_resized[i][j] = den[int(i / 4)][int(j / 4)] / 16
        den = den_resized

    img_path = './data/original/shanghaitech/part_' + dataset + '_final/test_data/images/'
    count = np.sum(den)
    den = den * 10 / np.max(den)
    img = cv2.imread(img_path + 'IMG_' + str(img_num) + '.jpg', 1)

    w = img.shape[1]
    h = img.shape[0]

    data = []
    for j in range(len(den)):
        for i in range(len(den[0])):
            for k in range(int(den[j][i])):
                data.append([i + 1, j + 1])
    hm = HeatMap(data, base=img_path + 'IMG_' + str(img_num) + '.jpg')
Beispiel #8
0
def density_heatmap(width, height, box_centers, r=4):
    '''
    制作热力图
    '''
    hm = HeatMap(box_centers, width=width, height=height)
    heatmap_img = hm.heatmap(r=r)
    # 将PIL转opencv
    heatmap_img = cv2.cvtColor(np.asarray(heatmap_img), cv2.COLOR_RGB2BGR)
    return heatmap_img
Beispiel #9
0
def example1():

    # 加载测试数据
    data = loadDataFromFile("test_data.txt")

    # 开始绘制
    hm = HeatMap(data)
    hm.clickmap(save_as="hit.png")
    hm.heatmap(save_as="heat.png")
Beispiel #10
0
def save_heatmap(density_map,
                 img,
                 img_name,
                 output_dir,
                 down_sample=True,
                 gt=False):
    """
    生成热力图并保存
    :param density_map: 2d-array, 密度图
    :param img: numpy [B,H,W,1]
    :param img_name: "abc.jpg"
    :param output_dir: 结果保存目录
    :param down_sample: bool, 是否有下采样
    :param gt: bool, 是否生成gt的热力图
    :return:
    """
    counts = int(np.sum(density_map))  # 人数
    print('generating heatmap for', img_name)

    # 如果密度图进行下采样4倍, 则需要还原到原始大小

    if down_sample:
        h, w = density_map.shape
        den_resized = np.zeros((h * 4, w * 4))
        for i in range(h * 4):
            for j in range(w * 4):
                den_resized[i][j] = density_map[int(i / 4)][int(j / 4)] / 16
        density_map = den_resized

    density_map = density_map * 1000
    data = []
    h, w = img.shape[1:3]
    for row in range(h):
        for col in range(w):
            try:
                for k in range(int(density_map[row][col])):
                    data.append([col + 1, row + 1])
            except IndexError:
                continue
    # 生成heatmap
    hm = HeatMap(data, width=w, height=h)
    # 保存heatmap
    hm_name = 'heatmap_' + img_name.split('.')[0] + '.png'
    hm.heatmap(save_as=os.path.join(output_dir, hm_name))

    # 使用蓝色填充heatmap背景, 并显示人群数量
    im = Image.open(os.path.join(output_dir, hm_name))
    x, y = im.size
    bg = Image.new('RGBA', im.size, (0, 0, 139))
    bg.paste(im, (0, 0, x, y), im)
    im_arr = np.array(bg)
    text = 'GT Count: {}'.format(counts) if gt else 'Est Count: {}'.format(
        counts)
    cv2.putText(im_arr, text, (10, y - 20), cv2.FONT_HERSHEY_PLAIN, 1,
                (0, 0, 0), 1)
    im = Image.fromarray(im_arr)
    im.save(os.path.join(output_dir, hm_name))
Beispiel #11
0
def example1():
    # 加载测试数据
    data = load_data_from_file("test_data.txt")

    # 开始绘制
    hm = HeatMap(data)
    hm.clickmap(save_as="hit.png")
    # hm.heatmap(save_as="heat.png", r=20) # 这儿可以传入 r 参数,指定热图半径,默认 r=10
    # hm.heatmap(save_as="heat.png", base="/var/tmp/test_base.png")
    hm.heatmap(save_as="heat.png")
Beispiel #12
0
def generate_heatmap(array, percentile=0.5, sign=''):
    per = np.percentile(array, 1 - percentile)
    height, width = array.shape
    hdata = []
    for i in range(height):
        for j in range(width):
            if (array[i][j] > per):
                hdata.append([i, j])
    hm = HeatMap(hdata)
    hm.clickmap(save_as='hit' + str(sign) + '.png')
    hm.heatmap(save_as='heat' + str(sign) + '.png')
Beispiel #13
0
def main(opt):
    minus = np.array([[0, 1, 0], [0, -1, 0], [1, 0, 0], [-1, 0, 0]])

    # Gets all data points, and transformed into (x,y)
    pos = []
    with open(opt.input, 'r') as file:
        for line in file.readlines():
            r, theta = map(lambda x: float(x), line[:-1].split(','))
            pos.append([
                int(opt.scale * r * math.cos(toPhi(theta))),
                int(-opt.scale * r * math.sin(toPhi(theta)))
            ])

    pos = np.asarray(pos)
    minimum = -np.min(pos)
    pos = pos - np.min(pos)
    # pos = np.apply_along_axis(lambda l: np.append(l, opt.duplicate), 1, pos)
    ans = np.copy(pos)
    if SHIFT:
        for i in range(minus.shape[0]):
            ans = np.concatenate(
                (ans, np.apply_along_axis(lambda l: l - minus[i], 1, pos)))
    print(ans.shape)

    hm = HeatMap(ans.tolist())

    # ------------ Draw all points ------------
    hm.clickmap(save_as=opt.input + "_hit.png")

    img = hm.heatmap()

    draw = ImageDraw.Draw(img)

    unit = 5
    font = ImageFont.truetype("/Library/Fonts/Arial.ttf", size=40)
    for i in range(5):
        radius = unit * i * opt.scale
        draw.ellipse((minimum - radius, minimum - radius, minimum + radius,
                      minimum + radius),
                     outline='black')
        draw.text(toxy((minimum, minimum), radius, 130),
                  "%d\u00B0" % (unit * i),
                  'black',
                  font=font)

    halfline = 5 * unit * opt.scale
    draw.line([(minimum - halfline, minimum), (minimum + halfline, minimum)],
              fill='black')
    draw.line([(minimum, minimum - halfline), (minimum, minimum + halfline)],
              fill='black')

    img.save(opt.input + "_heat.png")

    print("Two files generated!")
Beispiel #14
0
def heatmap(den, num, dataset, info):
    ###################################################
    #img_num = num + 600

    print('generating heat map for img', img_num)
    print('shape:', den.shape)

    if info == 'pre':
        den_resized = np.zeros((den.shape[0] * 8, den.shape[1] * 8))
        for i in range(den_resized.shape[0]):
            for j in range(den_resized.shape[1]):
                den_resized[i][j] = den[int(i / 8)][int(j / 8)] / 64
        den = den_resized

    #img_path = './data/original/shanghaitech/part_' + dataset + '_final/test_data/images/'
    img_path = './data/ucsd/test/'

    count = np.sum(den)
    den = den * 10 / np.max(den)
    img = cv2.imread(img_path + 'mall_IMG_' + str(img_num) + '.jpg', 1)

    w = img.shape[1]
    h = img.shape[0]

    data = []
    for j in range(len(den)):
        for i in range(len(den[0])):
            for k in range(int(den[j][i])):
                data.append([i + 1, j + 1])
    hm = HeatMap(data, base=img_path + 'IMG_' + str(img_num) + '.jpg')
    hm.heatmap(save_as='heat_' + dataset + '_' + str(img_num) + '_' + info +
               '_' + str(int(count)) + '.png')

    hm2 = HeatMap(data)
    hm2.heatmap(save_as='heatalone_' + dataset + '_' + str(img_num) + '_' +
                info + '_' + str(int(count)) + '.png')
Beispiel #15
0
def main():

    url = "https://raw.github.com/oldj/pyheatmap/master/examples/test_data.txt"
    print "begin"
    sdata = urllib.urlopen(url).read().split("\n")
    data = []
    for ln in sdata:
        a = ln.split(",")
        if len(a) != 2:
            continue
        a = [int(i) for i in a]
        data.append(a)

    hm = HeatMap(data)
    hm.heatmap(save_as="heat.png")
Beispiel #16
0
def main():

    data = []
    # download test data
    url = "https://raw.github.com/oldj/pyheatmap/master/examples/test_data.txt"
    for line in urllib.request.urlopen(url):
        line_str = str(line, encoding='utf-8').split("\n")
        for ln in line_str:
            if ',' in ln:
                a = ln.split(",")
                a = [int(i) for i in a]
                data.append(a)

    hm = HeatMap(data)
    hm.clickmap(save_as="hit.png")
    hm.heatmap(save_as="heat.png")
Beispiel #17
0
def main():
    # url = "https://raw.github.com/oldj/pyheatmap/master/examples/test_data.txt"
    ff = open('./test_data.txt', 'r')
    sdata = ff.read().split("\n")
    data = []
    for ln in sdata:
        a = ln.split(",")
        if len(a) != 2:
            continue
        a = [int(i) for i in a]
        data.append(a)

    # 开始绘制
    hm = HeatMap(data)
    hm.clickmap(save_as="hit.png")
    hm.heatmap(save_as="heat.png")
Beispiel #18
0
def main(srcUrl, clkMap, heatMap, width, height):

    # url = "https://raw.github.com/oldj/pyheatmap/master/examples/test_data.txt"
    # sdata = urllib.urlopen(url).read().split("\n")
    # url = "D:/DEV/GitHub/Sokaris_View3D/Sokaris_View3D/IntersectionsHN.ini"
    sdata = open(srcUrl, 'r').read().split('\n')

    data = []
    for ln in sdata:
        a = ln.split(" ")
        if len(a) != 2:
            continue
        a = [int(i) for i in a]
        data.append(a)

    hm = HeatMap(data=data, width=width, height=height)
    hm.clickmap(save_as=clkMap)
    hm.heatmap(save_as=heatMap)
Beispiel #19
0
def heatmap(den, base_img_path, n, save_path):
    print('generating heatmap for ' + base_img_path)

    den_resized = np.zeros((den.shape[0] * n, den.shape[1] * n))
    for i in range(den_resized.shape[0]):
        for j in range(den_resized.shape[1]):
            den_resized[i][j] = den[int(i / n)][int(j / n)] / (n**2)
    den = den_resized
    den = den * 10 / np.max(den)

    data = []
    for j in range(len(den)):
        for i in range(len(den[0])):
            for k in range(int(den[j][i])):
                data.append([i + 1, j + 1])
    hm = HeatMap(data, base=base_img_path)
    hm.heatmap(save_as=save_path)
    print('done generating heatmap')
Beispiel #20
0
def apply_heatmap(image, data):
    '''image是原图,data是坐标'''
    '''创建一个新的与原图大小一致的图像,color为0背景为黑色。这里这样做是因为在绘制热力图的时候如果不选择背景图,画出来的图与原图大小不一致(根据点的坐标来的),导致无法对热力图和原图进行加权叠加,因此,这里我新建了一张背景图。'''
    background = Image.new("RGB", (image.shape[1], image.shape[0]), color=0)
    # 开始绘制热度图
    hm = HeatMap(data)
    hit_img = hm.heatmap(base=background, r=100)  # background为背景图片,r是半径,默认为10
    # ~ plt.figure()
    # ~ plt.imshow(hit_img)
    # ~ plt.show()
    #hit_img.save('out_' + image_name + '.jpeg')
    hit_img = cv2.cvtColor(np.asarray(hit_img),
                           cv2.COLOR_RGB2BGR)  #Image格式转换成cv2格式
    overlay = image.copy()
    alpha = 0.5  # 设置覆盖图片的透明度
    cv2.rectangle(overlay, (0, 0), (image.shape[1], image.shape[0]),
                  (255, 0, 0), -1)  # 设置蓝色为热度图基本色蓝色
    image = cv2.addWeighted(overlay, alpha, image, 1 - alpha, 0)  # 将背景热度图覆盖到原图
    image = cv2.addWeighted(hit_img, alpha, image, 1 - alpha, 0)  # 将热度图覆盖到原图
Beispiel #21
0
def test():
    u"""测试方法"""

    print("load data..")
    data = []
    f = open("../examples/test_data.txt")
    for ln in f:
        a = ln.split(",")
        if len(a) != 2:
            continue
        x, y = int(a[0]), int(a[1])
        data.append([x, y])
    f.close()

    print("painting..")
    # 开始绘制
    hm = HeatMap(data)
    hm.clickmap(save_as="hit.png")
    hm.heatmap(save_as="heat.png")

    print("done.")
import numpy as np
import datetime
import function_2 as func_2
import main_1
import matplotlib.pyplot as plt
from pyheatmap.heatmap import HeatMap

# Get accident location and plot scatter diagram and heat map
acc_origin_path = r'C:/Users/lkr/Desktop/graduate/previous_data/accident_2015.csv'  # path for address descriptions
acc_new_path = r'C:/Users/lkr/Desktop/graduate/previous_data/accident_longitude_latitude.csv'  # path for longitudes and latitudes
func_2.get_location(acc_origin_path, acc_new_path)
acc_location = pd.read_csv(
    r'C:/Users/lkr/Desktop/graduate/previous_data/accident_longitude_latitude.csv'
)
plt.scatter(acc_location, s=20, c='b')  # plot scatter diagram
hm = HeatMap(acc_location)  # plot heat map
hm.clickmap(save_as='hit.png')
hm.heatmap(save_as='heat.png')

# Accidents-Sample points match
sp_location = pd.read_csv(
    r'C:/Users/lkr/Desktop/graduate/previous_data/sample_points_location.csv')
sp_match = []
for i in acc_location:
    dist = 99999
    sp = [-1, -1]
    for j in sp_location:
        if dist > func_2.mhd_distance(i, j) > 0.001:
            dist = func_2.mhd_distance(i, j)
            sp = j
    sp_match = [sp_match, sp]
    print(np.max(den))

    den = den * 500
    #print(den)

    pic = cv2.imread('IMG_' + str(img) + '.jpg', 0)
    w = pic.shape[1]
    h = pic.shape[0]

    data = []
    for j in range(len(den)):
        for i in range(len(den[0])):
            for k in range(int(den[j][i])):
                data.append([i + 1, j + 1])
    #print(data)
    hm = HeatMap(data, base='IMG_' + str(img) + '.jpg')
    hm.heatmap(save_as='heat_' + str(img) + '_with_base.png')

    hm = HeatMap(data, width=w, height=h)
    hm.heatmap(save_as='heat_' + str(img) + '.png')


def heatmap(den, img_num, dataset, info):
    print('generating heat map for img', img_num)
    print('shape:', den.shape)

    if info == 'pre':
        den_resized = np.zeros((den.shape[0] * 4, den.shape[1] * 4))
        for i in range(den_resized.shape[0]):
            for j in range(den_resized.shape[1]):
                den_resized[i][j] = den[int(i / 4)][int(j / 4)] / 16
Beispiel #24
0
def heat_map(combine_data):
    map_data = excel_table_index(file)
    media_names = map_data[0]
    resolution = map_data[1]
    gaze_points_x = map_data[2]
    gaze_points_y = map_data[3]
    # GazeEventDuration = map_data[4]

    check_name = media_names[0]

    image_size = [[0, 0], [resolution[0][0], resolution[0][1]]]

    index = 0
    point = []
    pointslist = []
    for name in media_names:
        if check_name is not name:
            print(check_name)
            pointslist.extend(image_size)
            image_size.remove(image_size[1])
            image_size.append([resolution[index][0], resolution[index][1]])

            if combine_data:
                for cindex in range(len(combine_data[0])):
                    if combine_data[0][cindex] == check_name:
                        pointslist.append([
                            int(combine_data[1][cindex]),
                            int(combine_data[2][cindex])
                        ])

            hm = HeatMap(pointslist)
            hm_names = check_name.split(".")
            hm_name = hm_names[0]
            # hm.clickmap(save_as=outputpath + hm_name + "_hit.png")
            hm.heatmap(save_as=output_path + hm_name + "_heat.png")
            pointslist = []
            check_name = name

        point.append(gaze_points_x[index])
        point.append(gaze_points_y[index])
        pointslist.append(point)
        point = []

        if index == len(media_names) - 1:
            print(check_name)
            pointslist.extend(image_size)

            if combine_data:
                for cindex in range(len(combine_data[0])):
                    if combine_data[0][cindex] == check_name:
                        pointslist.append([
                            int(combine_data[1][cindex]),
                            int(combine_data[2][cindex])
                        ])

            hm = HeatMap(pointslist)
            hm_names = name.split(".")
            hm_name = hm_names[0]
            # hm.clickmap(save_as=outputpath + hm_name + "_hit.png")
            hm.heatmap(save_as=output_path + hm_name + "_heat.png")
            break

        index += 1
Beispiel #25
0
from pyheatmap.heatmap import HeatMap
from PIL import Image

import csv
import math

data = []
minx = 0
miny = 0
basewidth = 500

with open('test.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in reader:
        sp = row[0].split(",")
        r = float(sp[0])
        t = float(sp[1])
        x = int(r * math.cos(t))
        y = int(r * math.sin(t))
        minx = min(x, minx)
        miny = min(y, miny)
        print(minx, miny)
        data.append([x - minx, y - miny])
    hm = HeatMap(data)
    hm.clickmap(save_as="hit.png")
    hm.heatmap(save_as="heat.png")
    im = Image.open("heat.png")
    im = im.rotate(270)
    print(im.format, im.size, im.mode)
    im.save("heat_resize.png", "PNG")
Beispiel #26
0
from pyheatmap.heatmap import HeatMap
import matplotlib.pyplot as plt

# file=np.load('COCO_train2014_000000001580.npy','r')
file = np.load('COCO_train2014_000000014537.npy', 'r')
# file=np.load('COCO_val2014_000000000294.npy','r')

f = []

for i in range(640):
    s = []
    for j in range(502):
        s.append(file[i][j][6])
    f.append(s)

hm = HeatMap(f)
hm.clickmap(save_as="hit.png")
hm.heatmap(save_as="heat.png")


def apply_heatmap(image, data):
    '''image是原图,data是坐标'''
    '''创建一个新的与原图大小一致的图像,color为0背景为黑色。这里这样做是因为在绘制热力图的时候如果不选择背景图,画出来的图与原图大小不一致(根据点的坐标来的),导致无法对热力图和原图进行加权叠加,因此,这里我新建了一张背景图。'''
    background = Image.new("RGB", (image.shape[1], image.shape[0]), color=0)
    # 开始绘制热度图
    hm = HeatMap(data)
    hit_img = hm.heatmap(base=background, r=100)  # background为背景图片,r是半径,默认为10
    # ~ plt.figure()
    # ~ plt.imshow(hit_img)
    # ~ plt.show()
    #hit_img.save('out_' + image_name + '.jpeg')