Skip to content

Instantly share code, notes, and snippets.

@habi
Created November 4, 2024 11:01
Show Gist options
  • Save habi/31378c7cc44a7644f35aa91a1afc9246 to your computer and use it in GitHub Desktop.
Save habi/31378c7cc44a7644f35aa91a1afc9246 to your computer and use it in GitHub Desktop.
def centralizeslice(image, threshold=None, verbose=False):
'''
Move detected region centroid to center of image
This function can successively be applied to 'verticalize' slices of a tomographic dataset of a cylindrical object not scanned perfectly vertical
'''
if not threshold:
print('Calculating threshold')
threshold = skimage.filters.threshold_otsu(image)
label_img = skimage.measure.label(image > threshold)
# Detect centroid
try:
regions = skimage.measure.regionprops(label_img)[0]
# roll image to the detected centerdata
# to do so, we roll to half the image size on both axes
shifted = numpy.roll(image,
shift=(image.shape[0] / 2 - regions.centroid[0], image.shape[1] / 2 - regions.centroid[1]),
axis=(0,1))
except IndexError:
# If no regions are found in the image, juyt return the original (empty) image
shifted = image
if verbose:
plt.imshow(image)
plt.imshow(shifted, cmap='viridis', alpha=0.5)
try:
plt.scatter(regions.centroid[1], regions.centroid[0], c='white')
except UnboundLocalError:
# No region, nothing to plot
pass
plt.axis('off')
plt.show()
return(shifted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment