Created
November 4, 2024 11:01
-
-
Save habi/31378c7cc44a7644f35aa91a1afc9246 to your computer and use it in GitHub Desktop.
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
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