Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

only algos #1391

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
666 changes: 0 additions & 666 deletions bin/caiman_gui.py

This file was deleted.

2 changes: 1 addition & 1 deletion caiman/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python

import pkg_resources
from caiman.base.movies import movie, load, load_movie_chain, _load_behavior, play_movie
from caiman.base.movies import movie, load, load_movie_chain, _load_behavior
from caiman.base.timeseries import concatenate
from caiman.cluster import start_server, stop_server
from caiman.mmapping import load_memmap, save_memmap, save_memmap_each, save_memmap_join
Expand Down
337 changes: 1 addition & 336 deletions caiman/base/movies.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@
import cv2
from functools import partial
import h5py
from IPython.display import display, Image
import ipywidgets as widgets
from IPython.display import Image
import logging
import matplotlib
import matplotlib.pyplot as plt
Expand All @@ -22,7 +21,6 @@
import skimage
import sklearn
import sys
import threading
import tifffile
from tqdm import tqdm
from typing import Any, Optional, Union
Expand All @@ -35,7 +33,6 @@
import caiman.mmapping
import caiman.summary_images
import caiman.utils.sbx_utils
import caiman.utils.visualization

try:
cv2.setNumThreads(0)
Expand Down Expand Up @@ -1098,65 +1095,6 @@ def zproject(self, method: str = 'mean', cmap=matplotlib.cm.gray, aspect='auto',
plt.imshow(zp, cmap=cmap, aspect=aspect, **kwargs)
return zp

def play(self,
gain: float = 1,
fr=None,
magnification: float = 1,
offset: float = 0,
interpolation=cv2.INTER_LINEAR,
backend: str = 'opencv',
do_loop: bool = False,
bord_px=None,
q_max: float = 99.75,
q_min: float = 1,
plot_text: bool = False,
save_movie: bool = False,
opencv_codec: str = 'H264',
movie_name: str = 'movie.avi') -> None:
"""
Play the movie using opencv

Args:
gain: adjust movie brightness

fr: framerate, playing speed if different from original (inter frame interval in seconds)

magnification: float
magnification factor

offset: (undocumented)

interpolation:
interpolation method for 'opencv' and 'embed_opencv' backends

backend: 'opencv', 'embed_opencv', 'pyplot', 'notebook': the first two are much faster

do_loop: Whether to loop the video

bord_px: int
truncate pixels from the borders

q_max, q_min: float in [0, 100]
percentile for maximum/minimum plotting value

plot_text: bool
show some text

save_movie: bool
flag to save an avi file of the movie

opencv_codec: str
FourCC video codec for saving movie. Check http://www.fourcc.org/codecs.php

movie_name: str
name of saved file

Raises:
Exception 'Unknown backend!'
"""
play_movie(self, gain, fr, magnification, offset, interpolation, backend, do_loop, bord_px,
q_max, q_min, plot_text, save_movie, opencv_codec, movie_name)


def load(file_name: Union[str, list[str]],
fr: float = 30,
Expand Down Expand Up @@ -2052,279 +1990,6 @@ def get_file_size(file_name, var_name_hdf5:str='mov') -> tuple[tuple, Union[int,
raise Exception('Unknown input type')
return dims, T

################################

def play_movie(movie,
gain:float = 1.0,
fr=None,
magnification:float = 1.0,
offset:float = 0.0,
interpolation=cv2.INTER_LINEAR,
backend:str = 'opencv',
do_loop:bool = False,
bord_px=None,
q_max:float = 99.75,
q_min:float = 1.0,
plot_text:bool = False,
save_movie:bool = False,
opencv_codec:str = 'H264',
movie_name:str = 'movie.avi', # why?
var_name_hdf5:str = 'mov',
subindices = slice(None),
tsub: int = 1) -> None:
"""
Play the movie using opencv

Args:
movie: movie object, or filename or list of filenames

gain: adjust movie brightness

fr: framerate, playing speed if different from original (inter frame interval in seconds)

magnification: float
magnification factor

offset: (undocumented)

interpolation:
interpolation method for 'opencv' and 'embed_opencv' backends

backend: 'opencv', 'embed_opencv', 'pyplot', or 'notebook': the first two are much faster

do_loop: Whether to loop the video

bord_px: int
truncate pixels from the borders

q_max, q_min: float in [0, 100]
percentile for maximum/minimum plotting value

plot_text: bool
show some text

save_movie: bool
flag to save an avi file of the movie

opencv_codec: str
FourCC video codec for saving movie. Check http://www.fourcc.org/codecs.php

movie_name: str
name of saved file

var_name_hdf5: str
if loading from hdf5/n5 name of the dataset inside the file to load (ignored if the file only has one dataset)

subindices: iterable indexes
for playing only a portion of the movie

tsub: int
temporal downsampling factor

Raises:
Exception 'Unknown backend!'
"""
logger = logging.getLogger("caiman")

# todo: todocument
if isinstance(movie, list) or isinstance(movie, tuple) or isinstance(movie, str):
it = True
else:
it = False

if backend == 'pyplot':
logger.warning('Using pyplot back end: not recommended. Using opencv will yield faster, higher-quality results.')

gain = float(gain) # convert to float in case we were passed an int
if q_max < 100:
maxmov = np.nanpercentile(load(movie, subindices=slice(0,10), var_name_hdf5=var_name_hdf5) if it else movie[0:10], q_max)
else:
if it:
maxmov = -np.inf
for frame in load_iter(movie, var_name_hdf5=var_name_hdf5):
maxmov = max(maxmov, np.nanmax(frame))
else:
maxmov = np.nanmax(movie)

if q_min > 0:
minmov = np.nanpercentile(load(movie, subindices=slice(0,10), var_name_hdf5=var_name_hdf5) if it else movie[0:10], q_min)
else:
if it:
minmov = np.inf
for frame in load_iter(movie, var_name_hdf5=var_name_hdf5):
minmov = min(minmov, np.nanmin(frame))
else:
minmov = np.nanmin(movie)

def process_frame(iddxx, frame, bord_px, magnification, interpolation, minmov, maxmov, gain, offset, plot_text):
if bord_px is not None and np.sum(bord_px) > 0:
frame = frame[bord_px:-bord_px, bord_px:-bord_px]
if magnification != 1:
frame = cv2.resize(frame, None, fx=magnification, fy=magnification, interpolation=interpolation)
frame = (offset + frame - minmov) * gain / (maxmov - minmov)

if plot_text == True:
text_width, text_height = cv2.getTextSize('Frame = ' + str(iddxx),
fontFace=5,
fontScale=0.8,
thickness=1)[0]
cv2.putText(frame,
'Frame = ' + str(iddxx),
((frame.shape[1] - text_width) // 2, frame.shape[0] - (text_height + 5)),
fontFace=5,
fontScale=0.8,
color=(255, 255, 255),
thickness=1)
return frame

if backend == 'pyplot':
plt.ion()
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.set_title("Play Movie")
im = ax.imshow((offset + (load(movie, subindices=slice(0,2), var_name_hdf5=var_name_hdf5) if it else movie)[0] - minmov) * gain / (maxmov - minmov + offset),
cmap=plt.cm.gray,
vmin=0,
vmax=1,
interpolation='none') # Blank starting image
fig.show()
im.axes.figure.canvas.draw()
plt.pause(1)

elif backend == 'notebook':
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
im = plt.imshow(next(load_iter(movie, subindices=slice(0,1), var_name_hdf5=var_name_hdf5))\
if it else movie[0], interpolation='None', cmap=matplotlib.cm.gray)
plt.axis('off')

if it:
m_iter = load_iter(movie, subindices, var_name_hdf5)
def animate(i):
try:
frame_sum = 0
for _ in range(tsub):
frame_sum += next(m_iter)
im.set_data(frame_sum / tsub)
except StopIteration:
pass
return im,
else:
def animate(i):
im.set_data(movie[i*tsub:(i+1)*tsub].mean(0))
return im,

# call the animator. blit=True means only re-draw the parts that have changed.
frames = get_file_size(movie)[-1] if it else movie.shape[0]
frames = int(np.ceil(frames / tsub))
anim = matplotlib.animation.FuncAnimation(fig, animate, frames=frames, interval=1, blit=True)

# call our new function to display the animation
return caiman.utils.visualization.display_animation(anim, fps=fr)

elif backend == 'embed_opencv':
stopButton = widgets.ToggleButton(
value=False,
description='Stop',
disabled=False,
button_style='danger', # 'success', 'info', 'warning', 'danger' or ''
tooltip='Description',
icon='square' # (FontAwesome names without the `fa-` prefix)
)
def view(button):
display_handle=display(None, display_id=True)
frame_sum = 0
for iddxx, frame in enumerate(load_iter(movie, subindices, var_name_hdf5) if it else movie[subindices]):
frame_sum += frame
if (iddxx+1) % tsub == 0:
frame = process_frame(iddxx, frame_sum/tsub, bord_px, magnification, interpolation, minmov, maxmov, gain, offset, plot_text)
frame_sum = 0
display_handle.update(Image(data=cv2.imencode(
'.jpg', np.clip((frame * 255.), 0, 255).astype('u1'))[1].tobytes()))
plt.pause(1. / fr)
if stopButton.value==True:
break
display(stopButton)
thread = threading.Thread(target=view, args=(stopButton,))
thread.start()

if fr is None:
try:
fr = movie.fr
except AttributeError:
raise Exception('Argument fr is None. You must provide the framerate for playing the movie.')

looping = True
terminated = False
if save_movie:
fourcc = cv2.VideoWriter_fourcc(*opencv_codec)
frame_in = next(load_iter(movie, subindices=slice(0,1), var_name_hdf5=var_name_hdf5))\
if it else movie[0]
if bord_px is not None and np.sum(bord_px) > 0:
frame_in = frame_in[bord_px:-bord_px, bord_px:-bord_px]
out = cv2.VideoWriter(movie_name, fourcc, 30.,
tuple([int(magnification * s) for s in frame_in.shape[1::-1]]))
while looping:
frame_sum = 0
for iddxx, frame in enumerate(load_iter(movie, subindices, var_name_hdf5) if it else movie[subindices]):
frame_sum += frame
if (iddxx+1) % tsub == 0:
frame = frame_sum / tsub
frame_sum *= 0

if backend == 'opencv' or (backend == 'embed_opencv' and save_movie):
frame = process_frame(iddxx, frame, bord_px, magnification, interpolation, minmov, maxmov, gain, offset, plot_text)
if backend == 'opencv':
cv2.imshow('frame', frame)
if save_movie:
if frame.ndim < 3:
frame = np.repeat(frame[:, :, None], 3, axis=-1)
frame = frame.astype('u1')
out.write(frame)
if backend == 'opencv' and (cv2.waitKey(int(1. / fr * 1000)) & 0xFF == ord('q')):
looping = False
terminated = True
break

elif backend == 'embed_opencv' and not save_movie:
break

elif backend == 'pyplot':
if bord_px is not None and np.sum(bord_px) > 0:
frame = frame[bord_px:-bord_px, bord_px:-bord_px]
im.set_data((offset + frame) * gain / maxmov)
ax.set_title(str(iddxx))
plt.axis('off')
fig.canvas.draw()
plt.pause(1. / fr * .5)
ev = plt.waitforbuttonpress(1. / fr * .5)
if ev is not None:
plt.close()
break

elif backend == 'notebook':
break

else:
raise Exception('Unknown backend!')

if terminated:
break

if save_movie:
out.release()
save_movie = False

if do_loop:
looping = True
else:
looping = False

if backend == 'opencv':
cv2.waitKey(100)
cv2.destroyAllWindows()
for i in range(10):
cv2.waitKey(100)

def rgb2gray(rgb):
# Standard mathematical conversion
Expand Down
Loading
Loading