I try to create a 2D heatmap (black & white) with this algorithm :
- I choose a random position on the grid
- I draw a circle around the position
- Mostly the grid is close to the center and mostly, it's close to 1.0
- If the current position has already a value, I add it
It works pretty well but I got one big issue :
On intersect, the color is not correct.
So I decide to use matplotlib to understand the problem :
I think the problem come from the center of the graph :
I need to smooth the center, how can I do that ?
My code :
import random as rnd
import numpy as np
import matplotlib.pyplot as plt
import math
from PIL import Image
def normalize(value, minn, maxn):
return (value - minn) / (maxn - minn)
def clamp(n, minn, maxn):
return max(min(maxn, n), minn)
def add_hot_spot(grid, cx, cy, radius):
for x, y in np.ndindex(grid.shape):
dist = math.dist((cx, cy), (x, y))
if dist < radius:
factor = 1 - normalize(dist, 0, radius)
grid[x, y] = clamp(grid[x, y] + factor, 0, 1)
def generate_heatmap(grid, count, radius_range = (1, 1), tolerance_range = (0, 1)):
while count > 0:
# choix de la position
x, y, r = rnd.randrange(0, w), rnd.randrange(0, h), rnd.randrange(*radius_range)
# choix d'une tolérance
k = rnd.uniform(*tolerance_range)
while grid[x][y] > k:
x, y = rnd.randrange(0, w), rnd.randrange(0, h)
# ajout d'un hot spot (position, radius)
add_hot_spot(grid, x, y, r)
count -= 1
def generate_noise(grid):
im = Image.new('RGB', (w, h), color='black')
for x, y in np.ndindex(grid.shape):
factor = grid[x, y]
sample = int(255 * factor)
im.putpixel((x, y), (sample, sample, sample))
return im
# génération de la grid à 0
w, h = 100, 100
grid = np.zeros((w, h))
# génération de la heatmap
# generate_heatmap(grid, 20, (1, 10), (0, 1))
add_hot_spot(grid, 25, 50, 50)
add_hot_spot(grid, 75, 50, 50)
# génération de l'image
im = generate_noise(grid)
im.show()
plt.plot(grid)
plt.show()
Aucun commentaire:
Enregistrer un commentaire