Created
May 28, 2020 21:23
-
-
Save tlancon/28f67a004cae4985f97f4c5b5f77d5f9 to your computer and use it in GitHub Desktop.
Inspect labeled objects in an image touching either a horizontal or vertical center line. Information is printed to the console.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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].imshow(masks) | |
ax[0].set_title('Labels from Aivia') | |
if vertical is True: | |
line_idx = int(masks.shape[1]/2) | |
line_arr = masks[:, line_idx] | |
else: | |
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: | |
pass | |
else: | |
masks_filtered = masks_filtered + np.where(masks==v, v, 0) | |
masks_filtered = masks_filtered.astype(masks.dtype) | |
measurements = regionprops(masks_filtered) | |
ax[1].imshow(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') | |
else: | |
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('\n') | |
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}") | |
plt.show() | |
# ---------------------------------------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment