咨询:Skimage 0.10.1版本中如何使用try_all_threshold阈值函数?
try_all_threshold Missing Issue in scikit-image 0.10.1 First things first: the try_all_threshold function simply doesn't exist in scikit-image 0.10.1. This handy utility was added in much later versions (around 0.14.x and beyond) under the skimage.filters module—so no matter how you try to import it in 0.10.1, you'll hit those import/attribute errors.
Here are two solid solutions to get the functionality you need:
Option 1: Upgrade scikit-image (Easiest Fix)
This is the most straightforward approach. Just upgrade to a version that supports try_all_threshold by running this command in your terminal:
pip install --upgrade scikit-image
Once upgraded, you can use the function exactly as intended:
from skimage.filters import try_all_threshold import matplotlib.pyplot as plt # Assume `gray` is your grayscale image fig, ax = try_all_threshold(gray, figsize=(10, 8), verbose=False) plt.show()
Option 2: Manually Replicate try_all_threshold (No Upgrade Needed)
If you can't upgrade for some reason, you can easily build a similar function yourself by looping through all the threshold methods available in 0.10.1.
First, let's list out all the threshold functions in your version's skimage.filter module (note: newer versions use skimage.filters, but 0.10.1 uses filter):
import skimage.filter as sf # Grab all functions starting with "threshold_" threshold_functions = [func for func in dir(sf) if func.startswith('threshold_')] print(threshold_functions)
In 0.10.1, you'll see functions like threshold_otsu, threshold_yen, threshold_li, threshold_isodata, threshold_minimum, and threshold_mean.
Now, here's a custom function that mimics try_all_threshold's behavior:
import matplotlib.pyplot as plt def custom_try_all_threshold(gray_image): import skimage.filter as sf # Get all threshold functions and their names funcs = [getattr(sf, name) for name in dir(sf) if name.startswith('threshold_')] func_names = [f.__name__ for f in funcs] # Set up subplots num_funcs = len(funcs) fig, axes = plt.subplots(2, (num_funcs + 1) // 2, figsize=(15, 8)) axes = axes.ravel() # Show original image axes[0].imshow(gray_image, cmap='gray') axes[0].set_title('Original Image') axes[0].axis('off') # Iterate through each threshold method for ax, func, name in zip(axes[1:], funcs, func_names): threshold = func(gray_image) binary_img = gray_image > threshold ax.imshow(binary_img, cmap='gray') ax.set_title(f'{name}\nThreshold: {threshold:.2f}') ax.axis('off') plt.tight_layout() return fig, axes # Use it like this (replace `gray` with your actual grayscale image) fig, axes = custom_try_all_threshold(gray) plt.show()
This code will display the original image alongside binary versions generated by every threshold method in your skimage version, just like try_all_threshold does in newer releases.
内容的提问来源于stack exchange,提问作者user10750892

