Skip to content

Commit

Permalink
Add scripts to make movies from diffraction data
Browse files Browse the repository at this point in the history
  • Loading branch information
stefsmeets committed Jun 28, 2018
1 parent 2425945 commit 611d51a
Show file tree
Hide file tree
Showing 2 changed files with 149 additions and 0 deletions.
77 changes: 77 additions & 0 deletions scripts/make_interval_movie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import sys, os

import subprocess as sp
import glob

from instamatic.formats import read_tiff
import matplotlib.pyplot as plt
import numpy as np


def printer(data):
"""Print things to stdout on one line dynamically"""
sys.stdout.write("\r\x1b[K"+data.__str__())
sys.stdout.flush()


def tiff2png(interval=10, drc="movie"):
fns1 = glob.glob("tiff\*.tif?")
fns2 = glob.glob("tiff_image\*.tif?")

if not os.path.exists(drc):
os.mkdir(drc)

j = 0

for i, fn1 in enumerate(fns1):
if i % (interval - 1) == 0:
try:
fn2 = fns2[j]
except IndexError:
break
im2, h2 = read_tiff(fn2)

im2 = im2[150:320, 150:320]

j += 1

im1, h1 = read_tiff(fn1)

fig, (ax1, ax2) = plt.subplots(1,2)

ax1.imshow(im1, vmax=np.percentile(im1, 99.0), cmap="gray")
ax2.imshow(im2, vmax=np.percentile(im1, 99.5), cmap="gray")

ax1.axis("off")
ax2.axis("off")

plt.tight_layout()

plt.savefig(f"{drc}/{i:05d}.png", bbox_inches='tight', pad_inches=0, dpi=200)
plt.close()

print(fn1, fn2)

return drc


def main():
drc = tiff2png()

out = "movie.mp4"

cmd = f"ffmpeg -r 20 -i {drc}/%05d.png -s:v 516x516 -c:v libx264 -profile:v high -crf 20 -pix_fmt yuv420p -r 24 -y movie.mp4".split()

print()
print(" ".join(cmd))
print()

sp.call(cmd)
try:
os.startfile(out) # windows
except AttributeError:
sp.call(['open', out]) # macos
# subprocess.call(['xdg-open', out]) # linux

if __name__ == '__main__':
main()
72 changes: 72 additions & 0 deletions scripts/make_serialed_movie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import os
import matplotlib.pyplot as plt
from instamatic.formats import read_image
from instamatic.tools import get_files
import tqdm, glob
import numpy as np

plt.rcParams["figure.figsize"] = 10, 10
plt.rcParams["image.cmap"] = "gray"

fns = get_files("images\image*.h5")

fontdict = {"fontsize": 30}
vmax_im = 500
vmax_diff = 1500
vmin_diff = 0

save = True

number = 0

if not os.path.isdir("movie"):
os.mkdir("movie")

for i, fn in enumerate(tqdm.tqdm(fns)):
dps = glob.glob(fn.replace("images", "data").replace(".h5", "_*.h5"))

im, h_im = read_image(fn)

crystal_coords = np.array(h_im["exp_crystal_coords"])

for j, dp in enumerate(dps):
try:
diff, h_diff = read_image(dp)
except:
print("fail")
continue

x,y = crystal_coords[j]

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(21.5, 10), sharex=True, sharey=True)

ax1.imshow(im, vmax=np.percentile(im, 99.5))
ax1.axis('off')
ax1.scatter(crystal_coords[:,1], crystal_coords[:,0], marker=".", color="red", s=100)
ax1.scatter(y,x, marker="o", color="red", s=200)
ax1.set_title(fn, fontdict)
ax2.imshow(diff, vmin=vmin_diff, vmax=vmax_diff)

ax2.axis('off')
ax2.set_title(dp, fontdict)

plt.tight_layout()

# out = dp.replace("h5", "png").replace("data\\","movie\\")
out = "movie\image_{:04d}.png".format(number)
number += 1

if save:
plt.savefig(out)
else:
plt.show()
plt.close()

print("Running ffmpeg...")

import subprocess as sp
cmd = "ffmpeg -r 5 -i movie/image_%04d.png -s:v 1280x720 -c:v libx264 -profile:v high -crf 20 -pix_fmt yuv420p -r 24 -y movie/compilation.mp4".split()
sp.call(cmd)

print("Done")

0 comments on commit 611d51a

Please sign in to comment.