how to superimpose a python df heatmap over an existing image without distortion

13 Views Asked by At

I have an existing image, from where I know the pixel size. And I know the location of my "source" (the orange cross in the blueprint) in x,y pixel coordinates using Paint. I calculate the source strength based on distance to source and drop this in a dataframe of which I make a heatmap. However the location of the source after overlaying both images is off in both x and y direction (to high and to the right) and as well the source strength pattern should be circular which is not the case.

How can I avoid the heatmap getting distorted and have the source in the original image match with the hotspot in the heatmap?

code I used:

width, height = Image.open(image_path1).size

tmp_strengths = []
# location of source(s) in pixel values:
xs = [934]
ys = [710]
sourcestrength = [10000]

my_dpi=96
plt.figure(figsize=(width/my_dpi, height/my_dpi), dpi=my_dpi)

# create 2D array and fill it up with "1" values - value is unimportant at this point:
x = np.full((width, height), 1)

for i in range(len(x[0])):
    for j in range(len(x[0])):
        # for z sources do:
        for z in range(len(xs)):
            #source strength = source strength - distance²
            strength = sourcestrength[z] - (math.sqrt(((ys[z]-j)**2)+((xs[z]-i)**2)))**2
            if strength < 0:
                strength = 0
                
            tmp_strengths.append(strength)
        
        x[j][i] = sum(tmp_strengths)
        
        # clean the tmp strength list again for the next i/j pairs
        tmp_strengths = []     
        

df = pd.DataFrame(x)
p1 = sns.heatmap(df, xticklabels=False, yticklabels=False, cbar=False, cmap = sns.cm.rocket_r)
p1.figure.savefig(heatmap_path,bbox_inches='tight', pad_inches=0, dpi=my_dpi)

img = Image.open(heatmap_path)
newsize = (width, height)
img = img.resize(newsize)
img.save(str(heatmap_path).replace('.jpg','_2.jpg'))

background = Image.open(image_path1)
overlay = Image.open(image_path2)

background = background.convert("RGBA")
overlay = overlay.convert("RGBA")

new_img = Image.blend(background, overlay, 0.5)
new_img.save(r"C:\Superimposed.png","PNG")

Keeping the color bar makes the distortion effect less, but then of course the overlap of the heatmap itself with the original image doesn't match anymore.

Even though I used plt.figure(figsize=(width/my_dpi, height/my_dpi), dpi=my_dpi) I still had to resize the image afterwards because the created image (1162x921pixels) did not match the pixel size of the original image (1500x1220pixels).

superposed images with color bar

superposed images without color bar

Any ideas would be welcome.

0

There are 0 best solutions below