Skip to content
Snippets Groups Projects
Commit 317313cd authored by Vedrana Andersen Dahl's avatar Vedrana Andersen Dahl
Browse files

week 1

parent 8af630cb
Branches
No related tags found
No related merge requests found
**/.DS_Store
**/__pycache__*
Source diff could not be displayed: it is too large. Options to address this: view the blob.
%% Cell type:markdown id: tags:
# Boundary length exercise
%% Cell type:code id: tags:
``` python
# %% Boundary length exercise
import numpy as np
import skimage.io
import matplotlib.pyplot as plt
# Read data
in_dir = '../data/week1/fuel_cells/'
imgs = [skimage.io.imread(in_dir + f'fuel_cell_{i}.tif') for i in range(1, 4)]
fig, ax = plt.subplots(1, 3, figsize=(15, 5))
for i in range(3):
ax[i].imshow(imgs[i], cmap='gray')
```
%% Output
%% Cell type:markdown id: tags:
### Task 1
Just to show how it can be done, we solve the task by looping. It is better (more efficient, easier to read, more compact code) to use numpy vectorization as shown below.
%% Cell type:code id: tags:
``` python
for im in imgs:
length = 0
for i in range(im.shape[0]-1):
for j in range(im.shape[1]):
length += (im[i,j]!= im[i+1,j])
for i in range(im.shape[0]):
for j in range(im.shape[1]-1):
length += (im[i,j]!= im[i,j+1])
print(f'Boundary length: {length}')
```
%% Output
Boundary length: 16328
Boundary length: 10801
Boundary length: 8084
%% Cell type:markdown id: tags:
### Task 2 Vectorization
%% Cell type:code id: tags:
``` python
#%% Section 1.1.2 - Task 2: Boundary length (vectorized)
for im in imgs:
length = (im[:-1] != im[1:]).sum() + (im[:,:-1] != im[:,1:]).sum()
print(f'Boundary length: {length}')
```
%% Output
Boundary length: 16328
Boundary length: 10801
Boundary length: 8084
%% Cell type:markdown id: tags:
### Task 3 Dedicated function
%% Cell type:code id: tags:
``` python
# %% Section 1.1.2 - Task 3: Boundary length function
def boundary_length(im):
'''
Computes the boundary length of an image.
Parameters
----------
im : ndarray
Image.
Returns
-------
bl : float
Boundary length.
'''
return (im[:-1] != im[1:]).sum() + (im[:,:-1] != im[:,1:]).sum()
for im in imgs:
print(f'Boundary length: {boundary_length(im)}')
for i in range(3):
L = boundary_length(imgs[i])
ax[i].imshow(imgs[i], cmap='gray')
ax[i].set_title(f'L={L}')
```
%% Output
Boundary length: 16328
Boundary length: 10801
Boundary length: 8084
%% Cell type:code id: tags:
``` python
```
Source diff could not be displayed: it is too large. Options to address this: view the blob.
Source diff could not be displayed: it is too large. Options to address this: view the blob.
Source diff could not be displayed: it is too large. Options to address this: view the blob.
%% Cell type:markdown id: tags:
# Movie exercise
Estimate growth of listeria bacteria from the movie.
%% Cell type:code id: tags:
``` python
from imageio import get_reader
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
from scipy.ndimage import gaussian_gradient_magnitude as ggm
```
%% Cell type:code id: tags:
``` python
# Read data
in_dir = '../data/week1/'
vid = get_reader(in_dir + 'listeria_movie.mp4', 'ffmpeg')
frames = []
for v in vid.iter_data():
frames.append(rgb2gray(v))
fig, ax = plt.subplots(1, 5)
for i in range(5):
k = int(i * (len(frames) - 1) / 4)
ax[i].imshow(frames[k], cmap='gray')
ax[i].set_title(f'Frame {k}')
plt.show()
```
%% Output
%% Cell type:code id: tags:
``` python
# Find parameters which give a good result
sigma = 2
threshold = 0.003
fig, ax = plt.subplots(1, 5)
for i in range(5):
k = int(i * (len(frames) - 1) / 4)
im_l = ggm(frames[k], sigma)
ax[i].imshow(im_l > threshold)
ax[i].set_title(f'Frame {k}')
plt.show()
```
%% Output
%% Cell type:code id: tags:
``` python
# Count bacteria for each frame in the movie
bacteria = [(ggm(f, sigma) > threshold).mean() for f in frames]
# Show the results
fig, ax = plt.subplots()
ax.plot(bacteria)
ax.set_xlabel('Frame number')
ax.set_ylabel('Bacteria count')
ax.set_title('Bacteria growth - sigmoid shape')
plt.show()
```
%% Output
Source diff could not be displayed: it is too large. Options to address this: view the blob.
%% Cell type:markdown id: tags:
# Total variation exercise
%% Cell type:code id: tags:
``` python
import numpy as np
import skimage.io
from scipy.ndimage import gaussian_filter
```
%% Cell type:code id: tags:
``` python
# Function to compute total variation
def total_variation(im):
'''
Computes the total variation of an image.
Parameters
----------
im : ndarray
Image.
Returns
-------
float
Total variation of the image.
'''
return np.abs(im[:-1] - im[1:]).sum() + np.abs(im[:,:-1] - im[:,1:]).sum()
```
%% Cell type:code id: tags:
``` python
# Read data
in_dir = '../data/week1/'
im = skimage.io.imread(in_dir + 'fibres_xcth.png').astype(float)
# Compute total variation
tv_im = total_variation(im)
# Smooth the image
sigma = 2
im_g = gaussian_filter(im, sigma)
# Compute total variation
tv_im_g = total_variation(im_g)
# Print the results
print(f'Total variation of original image: {tv_im:0.4g}')
print(f'Total variation of smoothed image: {tv_im_g:0.4g}')
print(f'Total variation is reduced by: {tv_im-tv_im_g:0.4g}')
```
%% Output
Total variation of original image: 4.766e+09
Total variation of smoothed image: 1.606e+09
Total variation is reduced by: 3.16e+09
Source diff could not be displayed: it is too large. Options to address this: view the blob.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment