Scikit Image – Multi Images Multi Image or Multi-frame Image, in general, refers to an image format that can store and represent multiple images or frames within a single file. For instance, animated GIFs and multi-frame TIFF files are examples of multi-image formats. MultiImage class in Scikit Image The MultiImage class in the scikit-image io module is used to specifically handle multiframe TIFF images. It provides a convenient way to load and manipulate multi-frame TIFF images. When working with multi-frame TIFFs using the MultiImage class, it returns a list of image-data arrays, similar to the ImageCollection class. However, there is a difference in how they handle multi-frame images. Multi-Image stores all frames of a multi-frame TIFF image as a single element in the list, with a shape of (N, W, H), where N is the number of frames and W and H are the width and height of each frame. Following is the syntax of this class − class skimage.io.MultiImage(filename, conserve_memory=True, dtype=None, **imread_kwargs) Here are the parameters of the class − filename − A string or list of strings specifying the pattern or filenames to load. The path can be absolute or relative. conserve_memory (optional) − A boolean value. If set to True, only one image will be kept in memory at a time. If set to False, images will be cached after loading to improve subsequent access speed. Example 1 The following example demonstrates how to use the MultiImage class to load a multiframe TIFF image and obtain information about the loaded image. from skimage.io import MultiImage # Load the multi-frame TIFF image multi_image = MultiImage(”Images_/Multi_Frame.tif”) # Access and display information about the loaded image file print(multi_image) print(”Type:”,type(multi_image)) print(”Length:”,len(multi_image)) print(”Shape:”,multi_image[0].shape) Output [”Images_/Multi_Frame.tif”] Type: < class ”skimage.io.collection.MultiImage” > Length: 1 Shape: (6, 382, 363, 3) Example 2 Let”s read the same Multi-frame TIFF file, “Multi_Frame.tif” using the ImageCollection class and observe how it treats the multi-frame images compared to the MultiImage class. from skimage.io import ImageCollection # Load the multi-frame TIFF image ic = ImageCollection(”Images_/Multi_Frame.tif”) # Access and display information about the loaded image file print(ic) print(”Type:”,type(ic)) print(”Length:”,len(ic)) print(”Shape:”,ic[0].shape) Output [”Images_/Multi_Frame.tif”] Type: < class ”skimage.io.collection.ImageCollection” > Length: 6 Shape: (382, 363, 3) When working with an animated GIF image, MultiImage reads only the first frame, whereas the ImageCollection reads all frames by default. Example 3 Let”s look into the following example and observe how the MultiImage class treats the animated GIF image. from skimage.io import MultiImage # Load an animated GIF image multi_image = MultiImage(”Images/dance-cartoon.gif”) # display the multi_image object print(multi_image) print(”Type:”,type(multi_image)) print(”Length:”,len(multi_image)) for i, frame in enumerate(multi_image): print(”Image {} shape:{}”.format(i, frame.shape)) Output [”Images/dance-cartoon.gif”] Type: < class ”skimage.io.collection.MultiImage”> Length: 1 Image 0 shape:(300, 370, 4) Example 4 Let”s read the same GIF file, “dance-cartoon.gif” using the ImageCollection class and observe how it treats the animated GIF image compared to the MultiImage class. from skimage.io import ImageCollection # Load an animated GIF image ic = ImageCollection(”Images/dance-cartoon.gif”) # Access and display information about the loaded image file print(ic) print(”Type:”,type(ic)) print(”Length:”,len(ic)) for i, frame in enumerate(ic): print(”Image {} shape:{}”.format(i, frame.shape)) Input Image Output [”Images/dance-cartoon.gif”] Type: <class ”skimage.io.collection.ImageCollection”> Length: 12 Image 0 shape:(300, 370, 4) Image 1 shape:(300, 370, 4) Image 2 shape:(300, 370, 4) Image 3 shape:(300, 370, 4) Image 4 shape:(300, 370, 4) Image 5 shape:(300, 370, 4) Image 6 shape:(300, 370, 4) Image 7 shape:(300, 370, 4) Image 8 shape:(300, 370, 4) Image 9 shape:(300, 370, 4) Image 10 shape:(300, 370, 4) Image 11 shape:(300, 370, 4)
Category: scikit-image
Scikit Image – Using Matplotlib Matplotlib is a widely used plotting library in Python that offers a wide range of functions for creating different types of plots and visualizations. It is a powerful library that enables the creation of static, animated, and interactive visualizations in Python programming language. Scikit Image with Matplotlib When it comes to visualizing images in the context of image processing, Matplotlib can be combined with the scikit-image library to achieve various visualization tasks. Generally, the Scikit-image library provides functions like io.imshow() and io.show() to display images, However, we can use Matplotlib”s imshow() function to display images with additional options such as annotations, color maps, axis configuration, and more. Also, it can be helpful for creating multiple plots in a single figure (nothing but subplots) for comparing different versions of an image or displaying intermediate steps in the image processing workflow. To set up Matplotlib for use with scikit-image, you need to ensure that both libraries are installed and properly configured. It is recommended to use a package manager such as pip or conda to install Matplotlib. pip is the default package manager for Python, while Conda is a popular choice for managing packages in Anaconda environments. Installing Matplotlib using pip To install Matplotlib using pip, just run the below command in your command prompt − pip install Matplotlib This will download the Matplotlib package. Installing Matplotlib using Conda If you”re using the Anaconda distribution already in your system then you can directly use the conda package manager to install Matplotlib. Following is the command − conda install matplotlib After the successful installation, you can directly import the matplotlib.pyplot, and skimage libraries to access the required functionality In your Python script or notebook to perform the image processing tasks. Below are a few basic Python programs that demonstrate how to use the Matplotlib library along with scikit-image to perform data visualization tasks effectively. Example 1 The following example demonstrates how to use Matplotlib to display the scikit-image loaded image. from skimage import io import matplotlib.pyplot as plt # Read an image image_data = io.imread(”Images/logo-w.png”) # Display the image using Matplotlib plt.imshow(image_data) plt.title(”Logo”, fontsize=18) Output On executing the above program, you will get the following output − Example 2 The following example demonstrates how to apply a circular mask to an image using scikit-image and display the original image and the masked image side by side using Matplotlib. import matplotlib.pyplot as plt from skimage import io import numpy as np # Load the image image_path = ”Images_/Zoo.jpg” image = io.imread(image_path) image_copy = np.copy(image) # Create circular mask rows, cols, _ = image.shape row, col = np.ogrid[:rows, :cols] center_row, center_col = rows / 2, cols / 2 radius = min(rows, cols) / 2 outer_disk_mask = ((row – center_row)**2 + (col – center_col)**2 > radius**2) # Apply mask to image image[outer_disk_mask] = 0 # Display the original and masked images using Matplotlib fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 5)) axes[0].imshow(image_copy) axes[0].set_title(”Original Image”) axes[0].axis(”off”) axes[1].imshow(image) axes[1].set_title(”Masked Image”) axes[1].axis(”off”) plt.tight_layout() plt.show() Output On executing the above program, you will get the following output −
Scikit Image – Image Stack A stack, in general, refers to a collection of independent components that collaborate to enable a particular functionality of an application. On the other hand, an image stack combines a group of images that share a common reference. While the images in the stack may vary in terms of quality or content, they are organized together for efficient processing and analysis. The image stack is grouped together for analysis or processing purposes, allowing for efficient batch operations. In the scikit-image library, the io module offers functions push() and pop() specifically for working with the image stack. The Io.pop() and io.push() functions The pop() function is used to remove an image from the shared image stack. It returns the image that has been popped from the stack as a NumPy ndarray. And the push(img) function is used to add a specific image to the shared image stack. It takes a NumPy ndarray (image array) as input. Example The following example demonstrates how to push images onto the shared stack using io.push() and retrieve images from the stack using io.pop(). It will also show that attempting to pop an image from an empty stack will raise an error named IndexError. import skimage.io as io import numpy as np # Generate images with random numbers image1 = np.random.rand(2, 2) image2 = np.random.rand(1, 3) # Push all image onto the shared stack one by one io.push(image1) io.push(image2) # Pop an image from the stack popped_image_array1 = io.pop() # Display the popped image array print(“The array of popped image”,popped_image_array1) # Pop another image from the stack popped_image_array2 = io.pop() # Display the popped image array print(“The array of popped image”,popped_image_array2) popped_image_array3 = io.pop() # Output IndexError popped_image_array3 Output The array of popped image [[0.58981037 0.04246133 0.78413075]] The array of popped image [[0.47972125 0.55525751] [0.02514485 0.15683907]] ————————————————————————— IndexError Traceback (most recent call last) ~AppDataLocalTempipykernel_7922226447525.py in < module > 23 24 # will rice an IndexError —> 25 popped_image_array3 = io.pop() 26 popped_image_array3 ~anaconda3libsite-packagesskimageio_image_stack.py in pop() 33 34 “”” —> 35 return image_stack.pop() IndexError: pop from empty list The last two lines of the above example will raise an IndexError. This is because there are only two images pushed onto the shared stack using io.push(), but the third call to io.pop() attempts to pop an image from the stack, causing an IndexError since the stack is empty after the first two pops.
Scikit Image – Using Napari Scikit Image with Napari Napari is a powerful Python library for n-dimensional image visualization, annotation, and analysis. It provides a flexible and interactive environment for working with image data. Following are some key features and capabilities of Napari − Viewing and Exploring − Napari allows you to view and explore n-dimensional arrays on a canvas. It supports 2D, 3D, and higher-dimensional data, providing a responsive and interactive visualization experience. Overlay derived data − Napari enables you to overlay derived data such as points, polygons, segmentations, labels, and more. Annotation and Editing − Napari provides tools for annotating and editing the derived datasets. You can add, modify, or delete annotations interactively using a variety of tools. Napari integrates with standard data structures like NumPy or Zarr arrays, enabling efficient annotation and analysis workflows. And it is a fast, interactive viewer for multi-dimensional images in Python. Also, it provides a user-friendly interface, extensive customization options, and the ability to integrate with other scientific Python libraries. Installation of Napari To use Napari, you will need the following requirements − Python > = 3.8 − Napari requires Python version 3.8 or higher. Make sure you have a compatible version installed on your system. Ability to Install Python Packages − You should have the ability to install Python packages using either pip or conda-forge. These are package managers that allow you to easily install and manage Python libraries and dependencies. Additionally, it is recommended to have − Environment Manager (such as Conda) − While not strictly required, having an environment manager like Conda can be beneficial. Conda allows you to create isolated Python environments. It provides a convenient way to manage your Python environment and ensure compatibility with other libraries and tools. Installing Napari using pip To install Napari using pip, just run the following command in your command prompt − python -m pip install “napari[all]” Installing Napari using Conda-Forge If you”re using the Anaconda distribution already in your system then you can directly install napari from the conda-forge channel. Following is the command − conda install -c conda-forge napari Once Napari is installed, you can use it in your Python scripts. Below are a few basic Python programs that demonstrate how to use the Napari library along with scikit-image to perform data visualization tasks effectively. Example 1 The following example demonstrates how to display an image using the Viewer() method in the Napari library. import napari from skimage import io # Read an image image = io.imread(”Images/logo-w.png”) # Display the image using Napari viewer = napari.Viewer() viewer.add_image(image, name=”Tutorialspoint”) Output On executing the above program, you will get the following output − Example 2 The following example demonstrates how to apply a circular mask to an image using scikit-image and display the original image and the masked images using the Napari library. import napari from skimage import io # Load the image image_path = ”Images_/Zoo.jpg” image = io.imread(image_path) image_copy = np.copy(image) # Create circular mask rows, cols, _ = image.shape row, col = np.ogrid[:rows, :cols] center_row, center_col = rows / 2, cols / 2 radius = min(rows, cols) / 2 outer_disk_mask = ((row – center_row)**2 + (col – center_col)**2 > radius**2) # Apply mask to image image[outer_disk_mask] = 0 # Display the image using Napari viewer = napari.Viewer() viewer.add_image(image_copy, name=”Input Image”) viewer.add_image(image, name=”Output masked Image”) Output On executing the above program, you will get the following output −
Scikit Image – Displaying Images Displaying or visualizing images plays a crucial role in image processing and computer vision tasks. It is necessary to visualize images when performing image processing operations such as cropping, resizing, rotating, or applying various filters. Displaying images refers to the process of visualizing or presenting digital images on a screen or other output devices. It allows us to view and interpret the content of images in a visual format. In the scikit-image library, the io module offers functions like imshow() and show() for displaying images on a screen. These functions are useful for displaying the results of image manipulation operations. Using the io.imshow() method The skimage.io.imshow() method is used to display an image. It opens a window and displays the image using the specified or default image plugins. Following is the syntax and parameters of this method − skimage.io.imshow(arr, plugin=None, **plugin_args) Following are the parameters of this function − arr − An ndarray or a string representing image data or the name of an image file. plugin − A string specifying the name of the plugin to be used. If not provided, the function will attempt to find a suitable plugin from the available options, starting with “imageio”. **plugin_args − Additional keyword arguments that are passed to the chosen plugin. Example The following example will display the image using the default image plugin. from skimage import io # Displaying image using the image name io.imshow(”Images/logo-w.png”) Output Running the above code gives us the following result − <matplotlib.image.AxesImage at 0x20980099d30 > Using the io.show() method The skimage.io.show() function is used to display pending images in scikit-image. It launches the event loop of the current GUI plugin and shows all images that have been queued for display using the imshow() function. This is particularly useful when working with non-interactive scripts. Following is the syntax of this method − skimage.io.show() Note, If you are working in an interactive environment, such as Jupyter Notebook or an interactive Python shell, you can simply use imshow() to display the image. However, if you are running a non-interactive script, it is best to include show() at the end to ensure that all images are displayed before the script terminates. Example 1 The following example will display an image using the imshow() and show() methods. from skimage import io # Read the image from an URL image = io.imread(”https://www.tutorialspoint.com/images/logo.png”) # Display an image io.imshow(image) io.show() Output Running the above code gives us the following result − Example 2 The following example will display the 2 images using the imshow() and show() methods. from skimage import io import numpy as np import time image1 = np.random.randint(0, 256, size=(50, 50, 3), dtype=np.uint8) image2 = np.random.randint(0, 256, size=(50, 50), dtype=np.uint8) # Displaying the image1 io.imshow(image1) io.show() # Displaying the image2 io.imshow(image2) io.show() Output The above program generates the following output − Following is the second image −
Scikit Image – Using Plugins A plugin refers to an extension or external software component that can enhance the functionality of the program by adding specific features to it thus improving its functionality. Plugins in Python Scikit Image The Python scikit-image (skimage) library comes with a variety of plugins that can be used to handle image IO operations, such as reading, writing, and displaying images. The available plugins in the scikit-image library include popular libraries like Matplotlib, PIL (Python Imaging Library), GDAL, SimpleITK, tifffile, PyFITS, and ImageIO. Each plugin specializes in a specific image IO operation. The scikit-image library loads the plugins as needed, to ensure optimal performance, and to allow efficient resource utilization. This means that plugins are only loaded when explicitly required or when set as default. This dynamic loading mechanism ensures that only the necessary plugins are loaded, depending on the specific image I/O operation. Also, the scikit-image library provides a range of functional tools to handle and operate plugins. These tools allow users to customize their image IO operations, let’s discuss some key plugin functions available in the skimage.io module. Listing the available plugins The function io.find_available_plugins(loaded=False) is used to list the available plugins in scikit-image (skimage.io). And it returns a dictionary with plugin names as keys and exposed functions as values. Following is the syntax of this function − skimage.io.find_available_plugins(loaded=False) The parameter “loaded” takes a boolean value. If it is set to True, only the loaded plugins will be shown. By default, all plugins are displayed. Example 1 The following example demonstrates the use of io.find_available_plugins() function to list all the available plugins and their corresponding exposed functions. import skimage.io as io # List all available plugins available_plugins = io.find_available_plugins() # Display the plugin names and their exposed functions for plugin_name, exposed_functions in available_plugins.items(): print(”Plugin:”, plugin_name) print(“Exposed Functions:”, exposed_functions) print() Output Plugin: fits Exposed Functions: [”imread”, ”imread_collection”] Plugin: gdal Exposed Functions: [”imread”, ”imread_collection”] Plugin: gtk Exposed Functions: [”imshow”] Plugin: imageio Exposed Functions: [”imread”, ”imsave”, ”imread_collection”] Plugin: imread Exposed Functions: [”imread”, ”imsave”, ”imread_collection”] Plugin: matplotlib Exposed Functions: [”imshow”, ”imread”, ”imshow_collection”, ”imread_collection”] Plugin: pil Exposed Functions: [”imread”, ”imsave”, ”imread_collection”] Plugin: qt Exposed Functions: [”imshow”, ”imsave”, ”imread”, ”imread_collection”] Plugin: simpleitk Exposed Functions: [”imread”, ”imsave”, ”imread_collection”] Plugin: tifffile Exposed Functions: [”imread”, ”imsave”, ”imread_collection”] Example 2 Let”s get the information about loaded plugins only. from skimage import io # List loaded plugins only available_plugins = io.find_available_plugins(loaded=True) # Display the loaded plugin names and their exposed functions for plugin_name, exposed_functions in available_plugins.items(): print(”Plugin:”, plugin_name) print(“Exposed Functions:”, exposed_functions) print() Output Plugin: imageio Exposed Functions: [”imread”, ”imsave”, ”imread_collection”] Plugin: matplotlib Exposed Functions: [”imshow”, ”imread”, ”imshow_collection”, ”imread_collection”] Plugin: tifffile Exposed Functions: [”imread”, ”imsave”, ”imread_collection”] Retrieving Info about a specific plugin The function io.plugin_info(plugin) is used to retrieve information about a specific plugin. It returns a dictionary containing information about the plugin, such as the description, and provides nothing but available function names. Following is the syntax of this function − skimage.io.plugin_info(plugin) The parameter “plugin” takes a string representing the name of the plugin for which you want to retrieve information. Example 1 The following example demonstrates how to use the io.plugin_info() function to retrieve the information about the ”pil” plugin. from skimage import io # Get information about the ”pil” plugin plugin_info = io.plugin_info(”pil”) # Print the plugin information print(“Description:”, plugin_info[”description”]) print(“Available Functions:”, plugin_info[”provides”]) print() Output Description: Image reading via the Python Imaging Library Available Functions: imread, imsave Example 2 In this example, we will get information about the ”matplotlib” plugin. from skimage import io # Get information about the ”matplotlib” plugin plugin_info = io.plugin_info(”matplotlib”) # Print the plugin information print(“Description:”, plugin_info[”description”]) print(“Available Functions:”, plugin_info[”provides”]) print() Output Description: Display or save images using Matplotlib Available Functions: imshow, imread, imshow_collection, _app_show Retrieving the plugin order The io.plugin_order() function is used to obtain the currently preferred plugin order. Following is the syntax of this function − skimage.io.plugin_order() The function returns a dictionary with function names as keys and the corresponding values are lists of plugins in the order of preference. Example Following is an example of using the plugin_order() function to obtain the currently preferred plugin order. from skimage import io # Get the currently preferred plugin order order_dict = io.plugin_order() # Print the plugin loading order print(“Preferred Plugin Order:”) for function_name, plugins in order_dict.items(): print(“Function:”, function_name) print(“Plugins in order of preference:”, plugins) print() Output Preferred Plugin Order: Function: imread Plugins in order of preference: [”imageio”, ”matplotlib”] Function: imsave Plugins in order of preference: [”imageio”] Function: imshow Plugins in order of preference: [”matplotlib”] Function: imread_collection Plugins in order of preference: [”imageio”, ”matplotlib”] Function: imshow_collection Plugins in order of preference: [”matplotlib”] Function: _app_show Plugins in order of preference: [”matplotlib”] Setting the default plugin The io.use_plugin() function is used to set the default plugin for a specified operation. The specified plugin will be loaded if it hasn”t been loaded already. Following is the syntax of this function − skimage.io.use_plugin(name, kind=None) Here are the parameters of this function − name − A string representing the name of the plugin is to be set as the default. kind (optional) − A string represents the specific function for which the plugin is being set. It can take one of the following values: ”imsave”, ”imread”, ”imshow”, ”imread_collection”, ”imshow_collection”. By default, the plugin is set for all functions. Example The following example shows the change in the plugin loading order after setting the default plugin. from skimage import io # Get the currently preferred plugin order order_dict_1 = io.plugin_order() # Print the plugin loading order print(“Plugin Order before Setting the default plugin:”) for function_name, plugins in order_dict_1.items(): print(function_name) print(“Plugin order:”, plugins) print() # Set the default plugin for all functions io.use_plugin(”qt”) # Get the preferred plugin order after setting the default plugin order_dict_2 = io.plugin_order() # Print the plugin loading order print(“Plugin Order after setting the default plugin: “) for function_name, plugins in order_dict_2.items(): print(function_name) print(“Plugin order:”, plugins) print() Output Plugin Order before Setting the default plugin: imread Plugin order: [”imageio”, ”matplotlib”] imsave Plugin order: [”imageio”] imshow Plugin order: [”matplotlib”] imread_collection Plugin
Scikit Image – Writing Images Writing or Saving images play a crucial role in image processing and computer vision tasks. It is necessary to save images when performing image processing operations such as cropping, resizing, rotating, or applying various filters. Writing an image refers to the process of saving or storing an image as an external file on a disk or in memory. During this process, we usually specify the desired file format (such as JPEG, PNG, TIFF, etc.) and provide the file name or path. In the scikit-image library, the io module offers a function called imsave() specifically for writing and storing images as external files. This function is useful for saving the results of image manipulation operations. The io.imsave() method By using imsave() method, writing the image to an external file with the desired file format, file name, and desired location can be possible. Following is the syntax of this method − skimage.io.imsave(fname, arr, plugin=None, check_contrast=True, **plugin_args) The function takes the following parameters − fname − A string representing the file name or path where the image will be saved. The format of the file is obtained from the extension of file name. arr − The NumPy array of shape (M,N) or (M,N,3) or (M,N,4) containing the image data to be saved. plugin (optional) − A string specifying the plugin to use for saving the image. If the plugin parameter is not provided, the function will automatically try different plugins, starting with imageio, until a suitable one is found. However, if the file name (fname) has a “.tiff” extension, the tifffile plugin will be used by default. check_contrast (optional) − A boolean indicating whether to check the contrast of the image and print warning. The default value is True. **plugin_args (optional) − Additional keyword arguments that are passed to the specified plugin. Example 1 The following example writes an array of random data to an external image file (.jpg) using the imsave() method. import numpy as np from skimage import io # Generate an image with random numbers image_data = np.random.randint(0, 256, size=(256, 256, 3), dtype=np.uint8) # Save the random image as a JPG file io.imsave(”Output/Random_image.jpg”, image_data) print(“The image was saved successfully.”) Output The image was saved successfully. If we navigate to the directory where the image was saved, we will be able to observe the saved “Random_image.jpg” image as shown below − Example 2 The following example writes an image array to a TIFF file (.tiff) using the imsave() method. import numpy as np from skimage import io # Read an image image_data = io.imread(”Images/logo-w.png”) print(“The input image properties:”) print(”Type:”, type(image_data)) print(”Shape:”, image_data.shape) # Save the image as a tiff file io.imsave(”Output/logo.tiff”, image_data) print(“The image was saved successfully…”) Output The input image properties: Type: < class ”numpy.ndarray” > Shape: (225, 225, 4) The image was saved successfully… The following image represents the saved “logo.tiff” file in the directory where the image was saved. Example 3 The following example demonstrates how to save an image to a JPEG file (.jpeg) with low quality using the imsave() method. import numpy as np from skimage import io # Read an image image = io.imread(”Images/Flower1.jpg”) # Save the image as a JPEG file io.imsave(”Output/flower.jpeg”, image, plugin=”pil”, quality=10) # Display the image array properties print(“The input image properties:”) print(”Type:”, type(image)) print(”Shape:”, image.shape) print(“The image was saved successfully…”) Output The input image properties: Type: < class ”numpy.ndarray”> Shape: (4000, 6000, 3) The image was saved successfully… The following images represent details of both input (Flower1.jpg) and saved (flower.jpeg) files in the respective directories. Input file Saved file
Scikit Image – Image Collections In computer vision and image processing, an image collection is a term used to describe a group or set of images that are considered together as a single entity for the purpose of managing and processing multiple images simultaneously. It can be used to store and manage a group of related images, such as a sequence of frames from a video, or a collection of images from various sources. And it simplifies the management and processing of multiple images, making it easier to handle image processing and computer vision tasks. ImageCollection class in skimage In the scikit-image library, the image collection is represented by an ImageCollection class that provides functionality for loading, managing, and manipulating a collection of image files. It allows you to specify a pattern or a list of filenames, load the corresponding images into memory, and access them conveniently. Following is the syntax of this class − class skimage.io.ImageCollection(load_pattern, conserve_memory=True, load_func=None, **load_func_kwargs) Here are the parameters of the class − load_pattern − A string or a list of strings representing the pattern of the file name to load. The filename path can be absolute or relative. conserve_memory (optional) − A boolean value. If set to True, only one image will be kept in memory at a time. If set to False, images will be cached after loading to improve subsequent access speed. load_func (optional) − A callable object that is used to read the image files. By default, it uses the imread function from the scikit-image library. However, you can specify a different function if needed. **load_func_kwargs (optional) − Additional keyword arguments that are passed to the load_func function. It creates an ImageCollection object that allows you to perform various operations on the loaded images, such as iterating over the collection, accessing individual images, and applying operations to the entire collection. Example 1 The following example will demonstrate how to load all the JPEG files in the specified directory. And the resulting ImageCollection object will be stored in the collection variable. from skimage import io # Load all the JPEG files in a directory collection = io.ImageCollection(”Images_/*.jpg”) print(”Type:”,type(collection)) print(”Total loaded JPEG files are”,len(collection)) Output The output shows the type of the collection object and the number of loaded JPEG files. Type: < class ”skimage.io.collection.ImageCollection”> Total loaded JPEG files are 5 Example 2 The following example demonstrate how to access the expanded file names using the files attribute of the ImageCollection object. from skimage import io # Load all the JPEG and PNG files in a directory collection = io.ImageCollection([”Images_/*.jpg”, ”Images_/*.png”]) # Access the expanded file list file_list = collection.files # Print the list of files one by one print(“Files:”) for image in file_list: print(image) Output Files: Images_Blank.png Images_Blank_img.png Images_ColorDots.png Images_Trees.jpg Images_WhiteDots2.jpg Images_WhiteDots4.jpg Images_Zoo.jpg Images_balloons_noisy.png Images_binary image.png Images_tree.jpg You can also use a direct function called io.imread_collection() in the skimage.io module for reading the collection of images. The imread_collection() function The imread_collection() function is used to load a collection of images. and it will return an ImageCollection object, representing the loaded image collection. Here”s the syntax and the parameters of the function − skimage.io.imread_collection(load_pattern, conserve_memory=True, plugin=None, **plugin_args) Following are the parameters of this function − load_pattern − A string or a list of strings representing the pattern of the file name to load. The filename path can be absolute or relative. conserve_memory (optional) − A Boolean value. If set to True, only one image will be kept in memory at a time. If set to False, images will be cached after loading to improve subsequent access speed. plugin_args (optional) − Additional keyword arguments that will be passed to the chosen plugin. The imread_collection() is a convenient wrapper function that internally creates an ImageCollection object for loading a collection of images. Other than using the ImageCollection class directly, It is good to use the imread_collection() function for simple use cases when you need to quickly load images based on a pattern or a list of filenames. Example 1 The following example demonstrates how to load all the tiff files in a specific directory. from skimage import io # Load all the tiff images collection = io.imread_collection(”Images_/*.tiff”, plugin=”tifffile”) print(”Dipaly the tifffile collection:”) print(collection) Output Dipaly the tifffile collection: [”Images_\file_example_TIFF_1MB.tiff”, ”Images_\file_example_TIFF_10MB.tiff”] Example 2 The following example will load a collection of tiff and JPEG images by specifying the list of strings(patterns). from skimage import io # Load a collection of JPEG and tifffile images collection = io.imread_collection([”Image Collection/*.jpg”, ”Image Collection/*.tiff”]) print(”Dipaly the JPEG and tifffile collection:”) print(collection) Output Dipaly the JPEG and tifffile collection: [”Image Collection\Trees.jpg”, ”Image Collection\WhiteDots2.jpg”, ”Image Collection\WhiteDots4.jpg”, ”Image Collection\Zoo.jpg”, ”Image Collection\file_example_TIFF_1MB.tiff”, ”Image Collection\file_example_TIFF_10MB.tiff”, ”Image Collection\tree.jpg”] The Imread_collection_wrapper() function The imread_collection_wrapper is a decorator function, that is used to create a custom version of the imread_collection() function. This wrapper function encapsulates the logic of creating an ImageCollection object with the specified image reading function. Following is the syntax of this Function − skimage.io.imread_collection_wrapper(imread) The imshow_collection() function The imshow_collection() function is used to display a collection of images. It takes an ImageCollection object as input and displays the images contained in the collection. Here, the syntax and the parameters of the function − skimage.io.imshow_collection(ic, plugin=None, **plugin_args) Following are the parameters − ic − An ImageCollection object representing the collection of images to display. plugin (optional) − A string specifying the name of the plugin to use for image display. By default, different plugins are attempted until a suitable one is found. plugin_args − Additional keyword arguments that are passed to the selected plugin for image display. Example The following example demonstrates how to use the imshow_collection() function to display a collection of images. from skimage import io # Load all the JPEG and PNG files in a directory collection = io.ImageCollection(”Images_/*.jpg”) # Access the expanded file list file_list = collection.files # Print the list of files one by one print(“Files:”) for image in file_list: print(image) # Display the collection of images io.imshow_collection(collection) io.show() Output Running the above code gives us the following result −
Scikit Image – Image Processing Image processing, in general, refers to the analysis and manipulation of digital images to enhance their quality, extract useful information, or perform various operations on the image data. It involves applying algorithms and techniques to images in order to alter or extract features, remove noise, or enhance visual appearance. The tasks involved in image processing include − Input/Output and Image Display − This involves handling the input and output of images, as well as displaying them on a screen or other output devices. Basic Image Manipulations − This includes fundamental operations such as cropping, flipping, rotating, and other similar transformations. Image Filtering − This task involves applying filters to images to achieve specific effects. Common filtering operations include denoising (removing noise), sharpening (enhancing the edges and details), and other similar operations. Image Segmentation − It focuses on dividing an image into different regions or objects. It involves labeling each pixel or group of pixels to identify which object they belong to. This is useful for tasks like object detection or boundary extraction. Classification − Image classification involves categorizing or labeling images based on their content. This task uses machine learning or pattern recognition algorithms to automatically assign images to predefined classes or categories. Feature Extraction − Extracting meaningful characteristics or patterns from images, such as edges, textures, or color features. These are the fundamental tasks in image processing and are used extensively in various applications such as computer vision, medical imaging, remote sensing, and many other fields. Image processing in Python Image processing in Python can be performed using various libraries and tools. Following are some popular packages for Python image processing − scikit-image − It is an open-source library that provides a wide range of algorithms for image-processing tasks such as filtering, segmentation, feature extraction, and more. It is designed to be user-friendly and integrates well with other scientific Python libraries. scipy.ndimage − This package, part of the SciPy library, offers various functions for n-dimensional image processing. It includes operations like filtering, interpolation, morphology, and measurements. It is particularly useful for scientific and medical image analysis. OpenCV − Open Source Computer Vision Library, is a highly popular and extensive computer vision library that provides a great collection of image processing and computer vision algorithms. And it is widely used for tasks like object detection, image recognition, and video processing. Pillow − Pillow is a powerful Python imaging library that provides a wide range of image processing functionalities. It supports image reading and writing in various formats, basic manipulations, filters, color space conversions, and more. scipy.ndimage − This package, part of the SciPy library, offers various functions for n-dimensional image processing. It includes operations like filtering, interpolation, morphology, and measurements. It is particularly useful for scientific and medical image analysis. These libraries provide a wide range of tools and algorithms for image processing in Python. Depending on your specific requirements, you can choose the most suitable library or combine multiple libraries to achieve your desired image processing tasks.
Scikit Image – Image datatypes A datatype, in the context of computer programming, refers to the classification or categorization of data based on its properties and the operations that can be performed on it. It determines how the computer interprets, stores, and manipulates the data. Different programming languages have their own set of data types, and each data type has its properties. Common data types include integers, floating-point numbers, characters, strings, booleans, and arrays. Datatypes in Python Scikit Image In scikit-image, images are represented as numpy arrays and support a variety of data types, also known as “dtypes.” The library sets certain ranges for dtype to avoid distorting image intensities. The following are the commonly used dtypes and their corresponding ranges in scikit-image − uint8 − Unsigned 8-bit integer, ranging from 0 to 255. uint16 − Unsigned 16-bit integer, ranging from 0 to 65535. uint32 − Unsigned 32-bit integer, ranging from 0 to 2^32 – 1. float − Floating-point values, typically ranging from -1 to 1 or 0 to 1. int8 − Signed 8-bit integer, ranging from -128 to 127. int16 − Signed 16-bit integer, ranging from -32768 to 32767. int32 − Signed 32-bit integer, ranging from -2^31 to 2^31 – 1. Note that float images should typically be restricted to the range -1 to 1, even though the float dtype itself can exceed this range. On the other hand, integer dtypes can span the entire range of their respective data types. It”s important to stick to these ranges to avoid data loss or incorrect interpretations of pixel intensities. Image data type conversion functions In scikit-image, there are few functions available in skimage.util module to convert image data types and ensure the proper rescaling of image intensities. These functions are designed to handle the conversion and rescaling while preserving the data range of the image. Following are the image data type conversion functions in scikit-image − Img_as_float Img_as_ubyte Img_as_uint Img_as_int These functions provide a convenient way to convert images to the desired data type while maintaining the correct range of intensities. Also, it is important to avoid using the astype function directly on an image, as it can violate assumptions about the dtype range. Instead, you can use the above conversion functions to ensure proper dtype conversion and intensity rescaling. Example 1 The following example demonstrates the difference between using the astype() method and the img_as_float() function for converting the data type of an image array in scikit-image. from skimage import util import numpy as np # Create an image with 8-bit unsigned integers image = np.random.randint(0, 256, size=(1, 4), dtype=np.uint8) print(“Image array:”, image) # Convert the image to float using astype() print(”Converted to float using astype :”,image.astype(float)) # These float values are out of range. # Convert the image to float using img_as_float() print(“Converted to float using img_as_float:”,util.img_as_float(image)) Output Image array: [[173 104 167 25]] Converted to float using astype : [[173. 104. 167. 25.]] Converted to float using img_as_float: [[0.67843137 0.40784314 0.65490196 0.09803922]] By using the img_as_float() function, the image array is correctly converted to the floating point data type with the intensity values properly scaled within the valid range. This ensures proper datatype conversion and intensity rescaling. Example 2 The following example demonstrates the conversion of a floating-point image array to an 8-bit unsigned integer representation using the img_as_ubyte() function from the skimage.util module. from skimage import util import numpy as np # Create an image with floating point numbers image = np.array([0, 0.1, 0, 0.8, 0.3, 1], dtype=float) print(“Image array:”, image) # Convert the image data to 8-bit Unsigned integers print(“Converted to 8-bit uint using img_as_ubyte:”,util.img_as_ubyte(image)) Output Image array: [0. 0.1 0. 0.8 0.3 1.] Converted to 8-bit uint using img_as_ubyte: [0 26 0 204 76 255]