Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

python - Error while drawing animation of seaborn heatmap for 3D volume

Trying to visualize the cross-correlation between two volumes, img_3D, and mask_3D, using Seaborn heatmap, and animation from Matplotlib to visualize the 3D cross-correlation result as a progressive animation of 2D images, but I was facing an error, can you please tell me how to get rid of this error, and visualize the heatmaps correctly?

Thanks in advance.

Traceback (most recent call last):
  File "C:UsersUserAppDataLocalProgramsPythonPython37libkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:UsersUserAppDataLocalProgramsPythonPython37libsite-packagesmatplotlibackends\_backend_tk.py", line 259, in resize
    self.draw()
  File "C:UsersUserAppDataLocalProgramsPythonPython37libsite-packagesmatplotlibackendsackend_tkagg.py", line 9, in draw
    super(FigureCanvasTkAgg, self).draw()
  File "C:UsersUserAppDataLocalProgramsPythonPython37libsite-packagesmatplotlibackendsackend_agg.py", line 392, in draw
    else nullcontext()):
  File "C:UsersUserAppDataLocalProgramsPythonPython37libcontextlib.py", line 112, in __enter__
    return next(self.gen)
  File "C:UsersUserAppDataLocalProgramsPythonPython37libsite-packagesmatplotlibackend_bases.py", line 2788, in _wait_cursor_for_draw_cm
    self.set_cursor(self._lastCursor)
  File "C:UsersUserAppDataLocalProgramsPythonPython37libsite-packagesmatplotlibackends\_backend_tk.py", line 544, in set_cursor
    window.configure(cursor=cursord[cursor])
  File "C:UsersUserAppDataLocalProgramsPythonPython37libkinter\__init__.py", line 1485, in configure
    return self._configure('configure', cnf, kw)
  File "C:UsersUserAppDataLocalProgramsPythonPython37libkinter\__init__.py", line 1476, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: invalid command name "."

The code used is :

# Import Libraries
#====================================
import numpy as np
np.random.seed(0)
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import nibabel as nib
from scipy.signal import correlate

import seaborn as sns
sns.set()
#===================================

img = np.load('img.npy')
act = np.load('act.npy')

# Mode : 'full', 'valid', 'same'

result = correlate(img, act,mode='same')

print(img.shape, act.shape, result.shape)

def updatefig(sl):
    for sl in range(result.shape[2]):
        print(sl,' / ',result.shape[2])
        sns.heatmap(result[...,sl],cbar=False)
        ax.set_title("frame {}".format(sl))
        # Note that using time.sleep does *not* work here!
        plt.pause(0.1)
fig, ax = plt.subplots()

ani = FuncAnimation(fig, updatefig, frames=range(result.shape[2]), interval=5, blit=True)

plt.show()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Check this code:

import numpy as np
np.random.seed(0)
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from scipy.signal import correlate
import seaborn as sns
sns.set()

img = np.load('img.npy')
act = np.load('act.npy')

result = correlate(img, act, mode = 'same')

def updatefig(sl):
    ax.cla()
    print(sl + 1, ' / ', result.shape[2])
    sns.heatmap(result[..., sl], cbar = False)
    ax.set_title("frame {}".format(sl + 1))
    ax.axis('off')

fig, ax = plt.subplots()
ani = FuncAnimation(fig, updatefig, frames = result.shape[2], interval = 5)

plt.show()

which gives me this animation (I halved the animation reported below to reduce the file size under 2 MB, the code above reproduce all 40 frames):

enter image description here


EDIT

In order to add a fixed colorbar to the heatmap, check this code:

import numpy as np
np.random.seed(0)
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from scipy.signal import correlate
import seaborn as sns
sns.set()

img = np.load('img.npy')
act = np.load('act.npy')

result = correlate(img, act, mode = 'same')

def updatefig(sl):
    ax.cla()
    print(sl + 1, ' / ', result.shape[2])
    sns.heatmap(result[..., sl],
                ax = ax,
                cbar = True,
                cbar_ax = cbar_ax,
                vmin = result.min(),
                vmax = result.max())
    ax.set_title("frame {}".format(sl + 1))
    ax.axis('off')

grid_kws = {'width_ratios': (0.9, 0.05), 'wspace': 0.2}
fig, (ax, cbar_ax) = plt.subplots(1, 2, gridspec_kw = grid_kws, figsize = (10, 8))
ani = FuncAnimation(fig, updatefig, frames = result.shape[2], interval = 5)

plt.show()

which produces this animation (cut as the previous one):

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...