Skip to content

Instantly share code, notes, and snippets.

Created May 28, 2020 21:23
What would you like to do?
Inspect labeled objects in an image touching either a horizontal or vertical center line. Information is printed to the console.
import os
import numpy as np
import matplotlib.pyplot as plt
from skimage import io
from skimage.measure import regionprops
# ----------------------------------------------------------
# Input
wdir = os.path.dirname('<DIRECTORY_CONTAINING_IMAGES>')
fname = '<LABELED_IMAGE_NAME>.tif'
vertical = True # If False, a horizontal line is used
# ----------------------------------------------------------
masks = io.imread(os.path.join(wdir, fname))
masks_filtered = np.zeros(shape=masks.shape, dtype=masks.dtype)
fig, ax = plt.subplots(1, 2)
ax[0].set_title('Labels from Aivia')
if vertical is True:
line_idx = int(masks.shape[1]/2)
line_arr = masks[:, line_idx]
line_idx = int(masks.shape[0]/2)
line_arr = masks[line_idx, :]
values_on_line = np.unique(line_arr)
for v in values_on_line:
if v==0:
masks_filtered = masks_filtered + np.where(masks==v, v, 0)
masks_filtered = masks_filtered.astype(masks.dtype)
measurements = regionprops(masks_filtered)
ax[1].set_title('Labels Touching Line')
if vertical is True:
ax[0].axvline(line_idx, color='r')
ax[1].axvline(line_idx, color='r')
ax[0].axhline(line_idx, color='r')
ax[1].axhline(line_idx, color='r')
# ----------------------------------------------------------
# Output
print(f"{len(measurements)} objects found.")
for prop in measurements:
length = prop.major_axis_length
breadth = prop.minor_axis_length
aspect_ratio = length / breadth
circularity = (4 * np.pi * prop.area) / (prop.perimeter**2)
print(f"Summary for object {prop.label}")
print(f"Length : {length:.2f}")
print(f"Breadth : {breadth:.2f}")
print(f"Aspect ratio : {aspect_ratio:.2f}")
print(f"Circularity : {circularity:.2f}")
# ----------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment