# Defocus and contrast inversion¶

In this notebook, we will use prysm to show how contrast inversion occurs as the image is swept out of focus. We begin by importing the relevant libraries and pieces of prysm:

[1]:

import numpy as np

from prysm import NollZernike, PSF, MTF, SiemensStar

from matplotlib import pyplot as plt, animation

from IPython.display import Video


Now we create the source object to be blurred and a sequence of defocus values to interrogate, as well as some matplotlib code:

[2]:

defocus_values = np.linspace(-2, 2, 100)  # 100 defocus values, spanning +/-4 waves of OPD (zernikes are 2r^2)
source_img = SiemensStar(64, sinusoidal=False)  # 64 spoke, square bar target Siemens Star

Writer = animation.writers['ffmpeg']
writer = Writer(fps=12)


All that is left is to write the plot loop, which will generate a view of the pupil, MTF, PSF, and blurred image:

[3]:

def plot_loop(idx):
for ax in axs:
ax.cla()

pu = NollZernike(Z4=defocus_values[idx])
ps = PSF.from_pupil(pu, 4, norm='radiometric')  # pu defaults to diameter of 1, this makes F/4
mt = MTF.from_psf(ps)
blurred = source_img.conv(ps)
blurred.data /= 4500  # arbitrary normalization to get the Siemens Star about the right brightness

# use a faster interpolation to be a bit nicer to RTD servers
pu.plot2d(fig=fig, ax=axs[0], clim=2, show_colorbar=False, interp_method='bilinear')
mt.plot_tan_sag(fig=fig, ax=axs[1])
ps.plot2d(fig=fig, ax=axs[2], axlim=50, show_colorbar=False)
blurred.show(fig=fig, ax=axs[3], show_colorbar=False)

axs[0].set_title('Pupil OPD')
axs[1].set_title('MTF')
axs[2].set_title('PSF')
axs[3].set_title('Image')

fig.tight_layout()

fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(10,10), dpi=72)  # ~720p
axs = axs.ravel()
ani = animation.FuncAnimation(fig, plot_loop, frames=100, repeat=True)
ani.save('../_static/defocus-contrast-inversion.mp4')
plt.close(fig)


Most of these lines are devoted to plotting, but we:

1. Create a new pupil instance with a specified amount of defocus (Z4)

2. Propagate that to a PSF at F/4

3. Compute the MTF associated with this PSF

4. Blur an image with the PSF

5. Plot all of these things

We can see that as the image moves out of focus, annuli of zero contrast form at increaingly large radii, and in at each the position of the white and black bars reverse. We also see that the PSF is quite structured, and has many rings of high and low intensity. This structure in the PSF is a consequence of interference, and is the source of the contrast inversions in the Siemens Star.