Image marker recognition, threshold, opening, connected components and centroid calculation
""" | |
Detect markers in image and display results | |
""" | |
import time | |
import numpy as np | |
import matplotlib.pyplot as plt | |
from scipy import ndimage | |
from skimage import io | |
from skimage import morphology | |
def do_threshold(array, value): | |
return (array >= value) * array | |
def difference_ms(prev_t): | |
return round((time.time() - prev_t) * 1000, 1) | |
def main(path): | |
original = io.imread(path) | |
threshold = 160 | |
opening_size = 5 | |
t0 = time.time() | |
thresholded = do_threshold(original, threshold) # very slow | |
print(f'Threshold:\t{difference_ms(t0)}ms') | |
t1 = time.time() | |
structure = morphology.disk(opening_size) | |
opened = ndimage.binary_opening(thresholded, structure) # quite slow | |
structure = np.ones((3, 3), dtype=np.int) | |
print(f'Opening:\t\t{difference_ms(t1)}ms') | |
t2 = time.time() | |
labels, ncomponents = ndimage.label(opened) # fast | |
print(f'Connect:\t\t{difference_ms(t2)}ms') | |
t3 = time.time() | |
centers = ndimage.measurements.center_of_mass(opened, labels, range(1, ncomponents + 1)) # fast | |
# Note, performing moment calculation on masked image may be faster (parallelizable). | |
print(f'Center:\t\t\t{difference_ms(t3)}ms') | |
total_ms = difference_ms(t0) | |
print(f'Total:\t\t\t{total_ms}ms') | |
print(f'ncomponents: {ncomponents}') | |
print(f'centers: {centers}') | |
# | |
# Plot | |
# | |
fig, axes = plt.subplots(2, 2, figsize=(8, 8), sharex=True, sharey=True) | |
axis = axes[0, 0] | |
axis.imshow(original, cmap=plt.cm.gray) | |
axis.set_title('original') | |
axis.axis('off') | |
axis = axes[0, 1] | |
axis.imshow(thresholded, cmap=plt.cm.gray) | |
axis.set_title(f'threshold: {threshold}') | |
axis.axis('off') | |
axis = axes[1, 0] | |
axis.imshow(opened, cmap=plt.cm.gray) | |
axis.set_title(f'opening; disk r={opening_size}') | |
axis.axis('off') | |
axis = axes[1, 1] | |
axis.imshow(original, cmap=plt.cm.gray) | |
axis.set_title(f'{ncomponents} center(s)') | |
axis.scatter(np.array(centers)[:, 1], np.array(centers)[:, 0], s=50, c='red', marker='+') | |
axis.axis('off') | |
# fig.suptitle(f'Total {total_ms}ms', fontsize=12) | |
# fig.tight_layout(rect=[0, 0.03, 1, 0.95]) | |
plt.savefig('plot.png', bbox_inches='tight') | |
plt.show() | |
fig, axis = plt.subplots(1, 1, figsize=(8, 8), sharex=True, sharey=True) | |
axis.imshow(original, cmap=plt.cm.gray) | |
axis.scatter(np.array(centers)[:, 1], np.array(centers)[:, 0], s=50, c='red', marker='+') | |
axis.axis('off') | |
plt.savefig('result.png', bbox_inches='tight') | |
if __name__ == "__main__": | |
path = 'luminance_raw_with_IR_light.jpg' | |
path = 'more-marker-raw_IR_light.jpg' | |
main(path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment