Mahotas – Image Stretch RGB Image stretching is a technique of enhancing the contrast of an image by mapping the original pixel values to a new range of values. This is generally done to improve the visibility of details and enhance the overall appearance of the image. In the case of RGB images, each pixel has three color channels− red, green, and blue. Stretching the RGB image involves independently stretching the values of each color channel to expand the range of intensities. Image Stretch RGB in Mahotas In Mahotas, RGB image stretching is performed by stretching the individual color channels (Red, Green, and Blue) of the image. The stretching process involves mapping the original pixel intensities to a new range to increase the contrast. After stretching the individual RGB channels, they need to be combined back to create the final stretched image. We can perform image stretching RGB in mahotas using the stretch() function and the stretch_rgb() function. Using the stretch() and the stretch_rgb() Functions The mahotas.stretch() and mahotas.stretch_rgb() functions stretches the pixel values in each channel of the RGB image between the specified min_value and max_value. Pixels with values below min_value will be set to min_value, and pixels with values above max_value will be set to max_value. The stretching is performed independently on each channel. Syntax Following is the basic syntax for mahotas.stretch() function − mahotas.stretch(img,arg0=None, arg1=None, dtype=<type ”numpy.uint8”>) Following is the basic syntax of mahotas.stretch_rgb() function − mahotas.stretch(img,arg0=None, arg1=None, dtype=<type ”numpy.uint8”>) Parameters Following are the parameters passed to the mahotas.stretch() function − img − It is the input image. arg0 and arg1 (optional) − These parameters specify the range within which the pixel values should be stretched. The interpretation of these arguments depends on their values − If both arg0 and arg1 are provided and are not None, they represent the minimum and maximum values that the pixel values should be stretched to. The pixel values below arg0 will be set to arg0, and pixel values above arg1 will be set to arg1. If only arg0 is provided and arg1 is None, arg0 should be a tuple or list of length 2 representing the percentile values. The pixel values below the value at the first element of arg0 will be set to that value, and pixel values above the value at the second element of arg0 will be set to that value. If both arg0 and arg1 are None, the pixel values will be stretched to the full range of the data type specified by the dtype parameter (default is numpy.uint8). dtype − It specifies the data type of the output image. The default value is numpy.uint8, which represents an unsigned 8-bit integer. Example In the following example, we are using the mahotas.stretch() function to stretch the image− import mahotas as mh import numpy as np import matplotlib.pyplot as plt image = mh.imread(”sun.png”) # Stretch image stretched = mh.stretch(image, arg0=100, arg1=280) # Create a figure with subplots fig, axes = plt.subplots(1, 2, figsize=(10, 5)) # Display the original image axes[0].imshow(image) axes[0].set_title(”Original Image”) axes[0].axis(”off”) # Display the stretched grayscale image axes[1].imshow(stretched, cmap=”gray”) axes[1].set_title(”Stretched Grayscale Image”) axes[1].axis(”off”) # Adjust the layout and display the plot plt.tight_layout() plt.show() Output Following is the output of the above code − Example In this example, we will see how to use mahotas.stretch_rgb function to stretch an image − import mahotas as mh import numpy as np import matplotlib.pyplot as plt image = mh.imread(”nature.jpeg”) # Stretch image stretched = mh.stretch_rgb(image, arg0=100, arg1=280) # Create a figure with subplots fig, axes = plt.subplots(1, 2, figsize=(10, 5)) # Display the original image axes[0].imshow(image) axes[0].set_title(”Original Image”) axes[0].axis(”off”) # Display the stretched grayscale image axes[1].imshow(stretched, cmap=”gray”) axes[1].set_title(”Stretched Grayscale Image”) axes[1].axis(”off”) # Adjust the layout and display the plot plt.tight_layout() plt.show() Output Following is the output of the above code − Stretching Image with Percentile Value To stretch an RGB image with percentile values in Mahotas, we can manually calculate the percentiles and use the stretch function individually on each color channel − Firstly, split the RGB image into individual color channels (red, green, and blue). This can be achieved by using the np.split() function from the NumPy library. Once the image is split, calculate the desired percentiles for each color channel using NumPy”s np.percentile() function. After obtaining the percentiles, use the stretch() function from Mahotas to each channel independently, using the calculated minimum and maximum values. This will stretch the pixel values within the desired percentile range for each channel. Finally, merge the stretched channels back into an RGB image by concatenating them along the color channel axis. The resulting image will be the stretched RGB image based on the specified percentiles. Example In here, we are trying to stretch an image with percentile value − import mahotas as mh import numpy as np from pylab import imshow, show image = mh.imread(”nature.jpeg”) # Splitting the RGB image into individual channels r, g, b = np.split(image, 3, axis=2) # Calculating percentiles for each channel r_min, r_max = np.percentile(r, [17, 90]) g_min, g_max = np.percentile(g, [25, 75]) b_min, b_max = np.percentile(b, [50, 99]) # Stretching each channel independently stretched_r = mh.stretch(r, r_min, r_max) stretched_g = mh.stretch(g, g_min, g_max) stretched_b = mh.stretch(b, b_min, b_max) # Merging the stretched channels back into an RGB image stretched_image = np.concatenate((stretched_r, stretched_g, stretched_b), axis=2) imshow(stretched_image) show() Output After executing the above code, we get the following output −
Category: mahotas
Mahotas – Increase Gamma Correction Let us first learn about what is gamma correction before understanding about increase gamma correction. Gamma correction adjusts the brightness of images to match how our eyes perceive light. Our eyes don”t see light in a linear way, so without correction, images may appear too dark or bright. Gamma correction applies a mathematical transformation to the brightness values, making the image look more natural by adjusting its brightness levels. Now, increasing gamma correction refers to adjusting the gamma value to make the overall image brighter. When the gamma value is increased, the dark areas appear brighter and enhance the overall contrast of the image. Increasing Gamma Correction in Mahotas In Mahotas, increasing gamma correction refers to adjusting the gamma value when changing the brightness of the pixels. The gamma is a positive value, where − A gamma value less than 1 will brighten the image. A gamma value greater than 1 will darken the image. A gamma value of 1 represents no correction and indicates a linear relationship between the pixel values and luminance. Gamma correction in Mahotas involves applying a power−law transformation to the intensity values of the image. The power−law transformation is defined as follows − new_intensity = old_intensity^gamma Here, old_intensity − It is the original intensity value of a pixel new_intensity − It is the transformed intensity value after gamma correction. The gamma determines the degree of correction applied to the image. When gamma is increased in Mahotas, it means that the intensity values are raised to a higher power. This adjustment affects the overall brightness of the image. Mahotas does not provide a direct way to do gamma correction, however it can be achieved by using mahotas with numpy library. Example In the following example, we are darkening a grayscale image by decreasing the gamma value − import mahotas as mh import numpy as np import matplotlib.pyplot as mtplt # Loading the image image = mh.imread(”sea.bmp”) # Converting it to grayscale gray_image = mh.colors.rgb2gray(image) # Decreasing gamma value corrected_gamma = 1.5 # Updating the image to use the corrected gamma value gamma_correction = np.power(gray_image, corrected_gamma) # Creating a figure and axes for subplots fig, axes = mtplt.subplots(1, 2) # Displaying the original image axes[0].imshow(gray_image, cmap=”gray”) axes[0].set_title(”Original Image”) axes[0].set_axis_off() # Displaying the gamma corrected image axes[1].imshow(gamma_correction, cmap=”gray”) axes[1].set_title(”Gamma Corrected Image”) axes[1].set_axis_off() # Adjusting spacing between subplots mtplt.tight_layout() # Showing the figures mtplt.show() Output Following is the output of the above code − Using Interactive Gamma Correction Slider An interactive gamma correction slider is a GUI element that allows users to adjust the gamma value dynamically. Users can increase or decrease the gamma value by dragging the slider, providing real−time feedback on the display. We can increase gamma correction using interactive gamma correction slider in mahotas, by first determining the desired gamma value to increase the correction. Then, apply the power−law transformation to the image by raising the pixel values to the power of the inverse gamma value. Syntax Following is the basic syntax to create an interactive slider − from matplotlib.widgets import Slider Slider(slider_axis, name, min_value, max_value, valint) where, slider_axis − It is a list that defines the position and dimensions of the slider. name − It is the name of the slider. mini_value − It is the minimum value that the slider can go to. max_value − It is the maximum value that the slider can go to. valint − It is the starting value of the slider. Example Here, we are trying to increase gamma correction using interactive gamma correction slider − import mahotas as mh import numpy as np import matplotlib.pyplot as mtplt from matplotlib.widgets import Slider # Loading the image image = mh.imread(”tree.tiff”) # Converting it to grayscale image = mh.colors.rgb2gray(image) # Creating a figure and axes for the plot fig, axis = mtplt.subplots() # Displaying the original image axis.imshow(image, cmap=”gray”) axis.set_title(”Gamma Correction”) axis.set_axis_off() # Creating a slider for gamma adjustment slider_axis = mtplt.axes([0.2, 0.05, 0.6, 0.03]) gamma_slider = Slider(slider_axis, ”Gamma”, 0.1, 5.0, valinit=1.0) # Updating the gamma correction and plot on change of slider value def update_gamma(val): gamma = gamma_slider.val corrected_image = np.power(image, gamma) axis.imshow(corrected_image, cmap=”gray”) fig.canvas.draw_idle() gamma_slider.on_changed(update_gamma) # Showing the figure mtplt.show() Output Output of the above code is as follows. First we are trying to increase the gamma correction using the slider as shown below − Now, decreasing gamma correction using the slider − Using Batch Gamma correction The batch gamma correction applies multiple gamma values to a single image. This helps in comparing the original image side−by−side at different gamma values to see the impact of increasing gamma correction. In Mahotas, we can adjust the brightness of an image using batch gamma correction by first iterating over a list of predetermined gamma values. Then applying the power−law transformation on the input image with different gamma values. Example Now, we are trying to increase gamma value using batch gamma correction − import mahotas as mh import numpy as np import matplotlib.pyplot as mtplt from matplotlib.widgets import Slider # Loading the image image = mh.imread(”sun.png”) # Converting it to grayscale image = mh.colors.rgb2gray(image) # Defining a list of gamma values gamma_values = [0.21, 0.82, 2, 5] # Creating subplots to display images for each gamma value fig, axes = mtplt.subplots(1, len(gamma_values) + 1) axes[0].imshow(image, cmap=”gray”) axes[0].set_title(”Original Image”) axes[0].set_axis_off() # Applying gamma correction for each gamma value for i, gamma in enumerate(gamma_values): corrected_image = np.power(image, gamma) axes[i + 1].imshow(corrected_image, cmap=”gray”) axes[i + 1].set_title(f”Gamma={gamma}”) axes[i + 1].set_axis_off() # Adjusting spacing between subplots mtplt.tight_layout() # Showing the figures mtplt.show() Output Following is the output of the above code −
Mahotas – Color-Space Conversion Color spaces refers to different types of color modes, used in image processing and signals and system for various purposes. Some of the common color spaces are − CMY”K− It is a subtractive color model used in printing and is represented by four color channels: Cyan (C), Magenta (M), Yellow (Y), and Key (K) for black. Y”UV− It is a color space used in video encoding and image processing. It separates the image information into luminance (Y”) and chrominance (UV) components. The Y” channel represents the brightness or grayscale information, while the U and V channels represent the color information. YIQ− It is a color space used in analog television systems, where the Y channel represents brightness and the I and Q channels represent color information. Y”CbCr− It is a color space commonly used in digital image and video encoding, where the Y” channel represents brightness and the Cb and Cr channels represent color information. The Y” channel contains the grayscale information, while the Cb and Cr channels represent the blue−difference and red−difference chroma components, respectively. HSV− HSV (Hue, Saturation, Value) is a color space used to represent colors in a way that is more perceptually meaningful to humans. In our tutorial, we will widely discuss about RGB color space. RGB Color Space RGB stands for red green and blue. It is the most widely used color space, and we will discuss about it in detail in the further chapters. The RGB model states that each color image is actually formed of three different images. Red image, Blue image, and black image. A normal grayscale image is defined by only one matrix, but a color image is actually composed of three different matrices. One color image matrix = red matrix + blue matrix + green matrix This can be best seen in this figure below − Available Functions Following are the different functions available in mahotas for color space conversion − S.No Function & Description 1 rgb2gray() This function converts an RGB image to a grayscale image. 2 rgb2grey() This function converts an RGB image to a grayscale image. 3 rgb2lab() This function converts an RGB image to L*a*b coordinates. 4 rgb2sepia() This function converts an RGB image to sepia i.e. a reddish−brown color. 5 rgb2xyz() This function converts an RGB image to XYZ color space i.e. brightness, color and intensity 6 xyz2lab() This functions converts XYZ to L*a*b color space. 7 xyz2rgb() This function converts XYZ to RGB color space. Now, lets us see examples of some of these functions. The rgb2grey() Function The rgb2grey() function is used to convert an RGB image to a grayscale image. This function assumes that the input image is a 2D NumPy array representing an RGB image, where the dimensions are (height, width, 3) for the height, width, and RGB channels, respectively. If the image is already grayscale (i.e., only has one channel), the function simply returns the image without any modifications. Example Following is the basic example of converting an RGB image to a grayscale image using the rgbtogrey() function − import mahotas as mh import numpy as np from pylab import imshow, show # Loading the image image = mh.imread(”nature.jpeg”) # Converting it to grayscale grey_image = mh.colors.rgb2grey(image) imshow(grey_image) show() Output After executing the above code, we get the following output − The rgb2sepia() Function The rgb2grey() function is used to convert an RGB image to a sepia toned image i.e. a reddish−brown color image. To convert an RGB image to sepia, the function applies a transformation to the RGB values of each pixel. This transformation involves adjusting the red, green, and blue channels to achieve the desired sepia effect. Example Here is the basic implementation of RGB color space to sepia toned image − import mahotas as mh import numpy as np from pylab import imshow, show # Loading the image image = mh.imread(”nature.jpeg”) # Converting it to grayscale sepia_image = mh.colors.rgb2sepia(image) imshow(sepia_image) show() Output Following is the output of the above code − We have discussed these functions in detail in the remaining chapters of this section.
Mahotas – Fraction of Zeros in an Image The fraction of zeros in an image refers to the proportion of zero−valued pixels compared to the total number of pixels in the image. In an image, each pixel typically represents a point in a grid, and the pixel values can range from 0 to a maximum value, depending on the image”s color depth or intensity range. A high fraction of zeros suggests that a significant portion of the image contains empty or background regions, while a low fraction of zeros indicates a denser distribution of nonzero pixel values, implying more detailed or complex content. Fraction of Zeros in an Image in Mahotas To obtain the fraction of zeroes in an image in Mahotas, we need to iterate through the entire image and divide the count of zero pixels by the total number of pixels in the image. The total number of pixels is equal to the number of rows multiplied by the number of columns in the image. Mahotas does not have direct functions for calculating fraction of zeros. However, you can use numpy and mahotas libraries to calculate it. Example In the following example, we are calculating the fraction of zero−valued pixels in the image by comparing the image array to zero, summing the True values, and dividing by the total number of pixels − import mahotas as mh import numpy as np image = mh.imread(”sun.png”) # Calculating the fraction of zeros fraction_of_zeros = np.sum(image == 0) / np.prod(image.shape) print(f”Fraction of zeros: {fraction_of_zeros}”) Output After executing the above code, we get the following output − Fraction of zeros: 0.009496713127718466 Using the count_nonzero() Function We can also calculate the fraction of zeros in an image using the count_nonzero() function in mahotas. The count_nonzero() function is used to count the number of non−zero elements in an array. It takes an array as input and returns the total count of elements that are non−zero. Syntax Following is the basic syntax of the count_nonzero() function in mahotas − count_nonzero(arr, axis=None) Where, arr − It is the input array for which non−zero elements need to be counted. axis (optional) − It is the axis or axes along which the non−zero elements are counted. If axis is not specified, all elements of the input array are considered. Example In here, we are counting the number of pixels of the image ”nature.jpeg” using the the np.count_nonzero() function − import mahotas as mh import numpy as np image = mh.imread(”nature.jpeg”) # Counting the number of zero pixels zero_count = np.count_nonzero(image == 0) # Calculating the fraction of zeros total_pixels = image.size fraction_of_zeros = zero_count / total_pixels print(“The fraction of zeros in the image is:”, {fraction_of_zeros}) Output Output of the above code is as follows − The fraction of zeros in the image is: {0.010734258862206976} Using Numpy The NumPy library provides efficient data structures and functions for working with arrays and matrices. It is widely used for tasks such as mathematical operations, data manipulation, and scientific computations due to its high performance and extensive functionality. We can also calculate the fraction of zeros using the numpy operation − Firstly, the NumPy array is compared to zero to convert the image to binary form. This comparison generates a boolean array where each element is True if the corresponding pixel value is greater than zero, and False otherwise. The boolean array is then cast to the ”np.uint8” data type resulting in a binary image where white pixels are represented by ones and black pixels by zeros. To calculate the fraction of zeros, the number of zero−valued elements in the binary image is computed. This count is divided by the total number of elements in the binary image to obtain the fraction. Example Here, we are first converting the image to a binary representation. We are then calculating the fraction of zeros of the binary image − import mahotas as mh import numpy as np image = mh.imread(”tree.tiff”) # Convert the image to binary image_binary = (image > 0).astype(np.uint8) # Calculate the fraction of zeros fraction_of_zeros = np.sum(image_binary == 0) / np.prod(image_binary.shape) print(“Fraction of zeros:”, fraction_of_zeros) Output Output of the above code is as follows − Fraction of zeros: 0.014683837192681532
Mahotas – Handling Images Mahotas is a popular Python package for handling images and performing various operations on them. It can do many things with images, like separating them into different parts, finding edges, and recognizing objects in them. With Mahotas, we can find all the faces in a set of pictures, or identify different types of flowers in a collection of images. We can also find the edges of objects in pictures, or make blurry pictures clearer in Mahotas. In this tutorial, we will take a brief overview of how to use Mahotas to handle images, including how to read, write, and display images. We will also learn how to perform common image processing tasks such as filtering, segmentation, and feature extraction. Image Handling with Mahotas One of the key features of Mahotas is its ability to handle images in various formats, such as JPEG, PNG, and BMP. Mahotas provides us with functions for reading and writing images, as well as for converting images between different formats. Let us learn how to read an image in Mahotas. Reading Images Reading images in mahotas refers to the process of loading image data from a file. To read an image in Mahotas, we can use the imread() function. This function reads an image from a file and returns a NumPy array representing the image. Example In the code below, we are trying to read a JPEG image named ”nature.jpeg” − import mahotas as ms image = ms.imread(”nature.jpeg”) print (“The image is read.”) Output This will read the image from the file ”nature.jpeg” and store it in the variable ”image” − The image is read. We can also display the image once we have read it as discussed below. Displaying an Image Once you have read an image, we can display it using the matplotlib library. The matplotlib library is used for data visualization and plotting. Example Let us display the image ”nature.jpeg, using matplotlib library as shown below − import matplotlib.pyplot as plt import mahotas as ms image = ms.imread(”nature.jpeg”) plt.imshow(image) plt.show() Output Following is the image obtained while executing the above code− Writing Images Writing images in Mahotas refers to saving the image data to a file in a specific image format such as PNG, JPEG, BMP, TIFF, etc. We can use the imsave() function to write an image in Mahotas. This function is part of the image input/output (IO) module in mahotas. Example In the code below, we are trying to save an image named ”nature.jpeg” − import mahotas as ms image = ms.imread(”nature.jpeg”) print (“The image is read.”) # Write the image to a file ms.imsave(”writing.jpeg”, image) print (“The image data is saved.”) Output This will save the image to a file ”writing.jpeg” − The image is read. The image data is saved. Image Processing with Mahotas Image processing refers to a set of techniques which is used to perform several operations on images. These techniques are helpful in improving the visual quality of images, extract useful information, or prepare them for analysis. Some common image processing tasks are filtering, segmentation, and feature extraction. In this section, we will explore some of the key image processing functions provided by Mahotas. Filtering In mahotas, filtering refers to modifying the appearance of an image or extracting useful information from it. This is done by applying a mathematical operation to an image. The filtering process is useful in removing noise, smoothening an image, enhancing edges, or performing other operations that help improve the quality or interpretability of an image. Example In the following example, we are trying to smooth an image using a Gaussian filter. The Gaussian filter blurs an image, which can be used to reduce noise or smooth an image − import mahotas as ms import numpy as np import matplotlib.pyplot as mtplt # Loading an image and converting it to grayscale image = ms.imread(”nature.jpeg”, as_grey=True) # Applying a Gaussian filter # Standard deviation sigma = 15 gaussian_filtered = ms.gaussian_filter(image, sigma) # Displaying the original image fig, axes = mtplt.subplots(1, 2, figsize=(9, 4)) axes[0].imshow(image, cmap=”gray”) axes[0].set_title(”Original Image”) axes[0].axis(”off”) # Displaying the filtered image axes[1].imshow(gaussian_filtered, cmap=”gray”) axes[1].set_title(”Gaussian Filtered”) axes[1].axis(”off”) mtplt.show() Output This will smooth the original image using a Gaussian filter with a standard deviation of 15 as shown below − Segmentation Segmentation in mahotas refers to the process of dividing an image into meaningful regions or segments based on certain characteristics or criteria. These segments can represent different objects, regions of interest, or distinct areas within the image. Example Now, let”s go through a basic example of image segmentation using thresholding with Mahotas. Thresholding is used to separate objects from the background based on pixel intensity values. It simplifies an image by converting it into a binary image where eachpixel is classified as either foreground (object) or background − import mahotas as ms import numpy as np import matplotlib.pyplot as mtplt # Loading the image image = ms.imread(”nature.jpeg”, as_grey=False) # Performing thresholding # Calculating threshold value by taking mean of image threshold = np.mean(image) # creating binary image # comparing each pixel value with the threshold binary_image = image > threshold # Perform connected component analysis # assigns a unique label to each connected region in the binary image labeled_image, num_objects = ms.label(binary_image) # Displaying the original image fig, ax = mtplt.subplots(1, 2, figsize=(9, 4)) ax[0].imshow(image, cmap=”gray”) ax[0].set_title(”Original Image”) # Displaying the segmented image ax[1].imshow(labeled_image, cmap=”rainbow”) ax[1].set_title(”Segmented Image ({} objects)”.format(num_objects)) mtplt.show() Output The output of the above code is as shown below − Feature Extraction Feature extraction in Mahotas refers to the process of extracting meaningful and informative features from an image. These features can represent various aspects of the image, such as texture, shape, or color, and can be used to describe and differentiate objects or regions within the image. Example Now, let”s see an example of how to calculate Zernike moments using Mahotas. The Zernike moments are a set of numerical values that describe the shape of an object or region within an image. They provide
Mahotas – Filtering Regions Filtering regions refers to excluding specific regions of a labeled image based on certain criteria. A commonly used criteria for filtering regions is based on their size. By specifying a size limit, regions that are either too small or too large can be excluded to get a clean output image. Another criterion for filtering regions is to check whether a region is bordered or not. By applying these filters, we can selectively remove or retain regions of interest in the image. Filtering Regions in Mahotas In Mahotas, we can convert filter regions of a labeled image by using the labeled.filter_labeled() function. This function applies filters to the selected regions of an image while leaving other regions unchanged. Using the mahotas.labeled.filter_labeled() Function The mahotas.labeled.filter_labeled() function takes a labeled image as input and removes unwanted regions based on certain properties. It identifies the regions based on the labels of an image. The resultant image consists of only regions that match the filter criterion. Syntax Following is the basic syntax of the filter_labeled() function in mahotas − mahotas.labeled.filter_labeled(labeled, remove_bordering=False, min_size=None, max_size=None) where, labeled − It is the array. remove_bordering (optional) − It defines whether to remove regions touching the border. min_size (optional) − It is the minimum size of the region that needs to be kept (default is no minimum). max_size (optional) − It is the maximum size of the region that needs to be kept (default is no maximum). Example In the following example, we are filtering a labeled image to remove border pixels. import mahotas as mh import numpy as np import matplotlib.pyplot as mtplt # Loading the image image_rgb = mh.imread(”tree.tiff”) image = image_rgb[:,:,0] # Applying gaussian filtering image = mh.gaussian_filter(image, 4) image = (image > image.mean()) # Converting it to a labeled image labeled, num_objects = mh.label(image) # Applying filters filtered_image, num_objects = mh.labeled.filter_labeled(labeled, remove_bordering=True) # Creating a figure and axes for subplots fig, axes = mtplt.subplots(1, 2) # Displaying the original RGB image axes[0].imshow(image_rgb) axes[0].set_title(”RGB Image”) axes[0].set_axis_off() # Displaying the filtered image axes[1].imshow(filtered_image) axes[1].set_title(”Filtered Image”) axes[1].set_axis_off() # Adjusting spacing between subplots mtplt.tight_layout() # Showing the figures mtplt.show() Output Following is the output of the above code − Filtering on Regions of Specific Size We can also filter regions of specific size in an image. In this way, we can remove regions from labeled images which do not fall within a specific size limit (regions that are too small or too large). In mahatos, we can achieve this by specifying values to the optional parameter min_size and max_size in the labeled.filter_label() function. Example The following example shows filtering a labeled image to remove regions of specific size. import mahotas as mh import numpy as np import matplotlib.pyplot as mtplt # Loading the image image_rgb = mh.imread(”tree.tiff”) image = image_rgb[:,:,0] # Applying gaussian filtering image = mh.gaussian_filter(image, 4) image = (image > image.mean()) # Converting to a labeled image labeled, num_objects = mh.label(image) # Applying filters filtered_image, num_objects = mh.labeled.filter_labeled(labeled, min_size=10, max_size=50000) # Create a figure and axes for subplots fig, axes = mtplt.subplots(1, 2) # Displaying the original RGB image axes[0].imshow(image_rgb) axes[0].set_title(”RGB Image”) axes[0].set_axis_off() # Displaying the filtered image axes[1].imshow(filtered_image) axes[1].set_title(”Filtered Image”) axes[1].set_axis_off() # Adjusting spacing between subplots mtplt.tight_layout() # Showing the figures mtplt.show() Output Output of the above code is as follows − Filtering on Border Regions and Regions of Specific Size We can filter bordered regions along with regions of a specific size in an image. In this, we remove regions which touch the border and regions which do not fall within a specific size limit. In mahotas, we can do this by specifying values to the optional parameter min_size and max_size and setting the optional parameter remove_bordering to True in the labeled.filter_label() function. Example In this example, a filter is applied to remove border regions and regions of specific size of a labeled image. import mahotas as mh import numpy as np import matplotlib.pyplot as mtplt # Loading the image image_rgb = mh.imread(”tree.tiff”) image = image_rgb[:,:,0] # Applying gaussian filtering image = mh.gaussian_filter(image, 4) image = (image > image.mean()) # Converting it to a labeled image labeled, num_objects = mh.label(image) # Applying filters filtered_image, num_objects = mh.labeled.filter_labeled(labeled, remove_bordering=True, min_size=1000, max_size=50000) # Creating a figure and axes for subplots fig, axes = mtplt.subplots(1, 2) # Displaying the original RGB image axes[0].imshow(image_rgb) axes[0].set_title(”RGB Image”) axes[0].set_axis_off() # Displaying the filtered image axes[1].imshow(filtered_image) axes[1].set_title(”Filtered Image”) axes[1].set_axis_off() # Adjusting spacing between subplots mtplt.tight_layout() # Showing the figures mtplt.show() Output The output produced is as shown below −
Mahotas – Creating RGB Image An RGB image is a type of digital image that uses the red, green, and blue color model to represent colors. Each pixel in an RGB image is represented by three color channels− red, green, and blue, which store the intensity values (ranging from 0 to 255) for each color. For example, a pixel with full intensity in all three channels (255, 255, 255) represents white, while a pixel with zero intensity in all three channels (0, 0, 0) represents black. Creating RGB Images in Mahotas An RGB image in Mahotas is a 3−dimensional array of shape (h,w,3); where h and w are the height and width of the image, and 3 represents the three channels: red, green, and blue. To create an RGB image using Mahotas, you need to define the dimensions of your image, create an empty numpy array with the desired dimensions, and set the pixel values for each channel. Mahotas does not have direct functions for creating RGB images. However, you can use numpy and mahotas libraries to create RGB images. Example Following is an example to create a gradient RGB image from red to green horizontally and blue to white vertically in mahotas − import mahotas as mh import numpy as np from pylab import imshow, show # Define the dimensions of the image width = 200 height = 150 # Create an empty numpy array with the desired dimensions image = np.zeros((height, width, 3), dtype=np.uint8) # Set the pixel values for each channel # Here, we”ll create a gradient from red to green horizontally and blue to white vertically for y in range(height): for x in range(width): # Red channel gradient r = int(255 * x / width) # Green channel gradient g = int(255 * (width – x) / width) # Blue channel gradient b = int(255 * y / height) # Set pixel values image[y, x] = [r, g, b] # Save the image mh.imsave(”rgb_image.png”, image) # Display the image imshow(image) show() Output Following is an output of the above code − Creating an RGB Image from Color Intensities Color intensities refer to the values that represent the strength or magnitude of each color channel in an image. Higher intensity values result in brighter or more saturated colors, while lower intensity values result in darker or less saturated colors. To create an RGB image from color intensities using Mahotas, you need to create separate arrays representing the intensities for the red, green, and blue color channels. These arrays should have the same dimensions as the desired output image. Example In the following example, we are creating a random RGB noise image from randomly generated color intensities − import mahotas as mh import numpy as np from pylab import imshow, show # Create arrays for red, green, and blue color intensities red_intensity = np.random.randint(0, 256, size=(100, 100), dtype=np.uint8) green_intensity = np.random.randint(0, 256, size=(100, 100), dtype=np.uint8) blue_intensity = np.random.randint(0, 256, size=(100, 100), dtype=np.uint8) # Stack color intensities to create an RGB image rgb_image = np.dstack((red_intensity, green_intensity, blue_intensity)) # Display the RGB image imshow(rgb_image) show() Output After executing the above code, we get the following output − Creating an RGB Image from a Single Color To create an RGB image from a single color, you can initialize an array with the desired dimensions and assign the same RGB value to each pixel. This results in a uniform color appearance throughout the image. Example In here, we are creating a single color image by setting the color to blue using the RGB values (0, 0, 255) − import mahotas as mh import numpy as np from pylab import imshow, show # Define the dimensions of the image width, height = 100, 100 # Create a single color image (blue in this case) blue_image = np.full((height, width, 3), (0, 0, 255), dtype=np.uint8) # Display the blue image imshow(blue_image) show() Output The image obtained is as follows −
Mahotas – Euler Number of an Image Imazine you have a drawing with different shapes on it. The Euler number allows us to count how many holes are in those shapes and how many separate parts they can be divided into (connected components). This can help in analyzing and characterizing the structure of the image. Mathematically, it can be defined as − E = C – H where, E is the Euler number, C is the number of connected components, and H is the number of holes in the image. Euler Number of an Image in Mahotas In Mahotas, you can calculate the Euler number using the mahotas.euler() function. This function takes a binary image as input, where the objects of interest are represented by white pixels and the background is represented by black pixels. It then calculates the Euler number based on the connectivity and holes in the objects present in the image. Using the mahotas.euler() Function The mahotas.euler() function takes a binary image as input and returns the Euler characteristic value as an integer. The Euler characteristic is a topological measure that describes the connectivity and shape of objects in an image. It is defined as the difference between the number of connected components and the number of holes in the image. Following is the basic syntax of euler() function in mahotas − mahotas.euler(f, n=8) Where, ”f” is a 2−D binary image and ”n” is the connected component in integer which is either 4 or 8 (default is 8). Example In the following example, we are computing the Euler number of a binary image ”nature.jpeg” by loading it as a grayscale image and then thresholding it to create a binary image − import mahotas as mh import numpy as np # Load binary image as a NumPy array binary_image = mh.imread(”nature.jpeg”, as_grey=True) > 0 # Compute Euler number euler_number = mh.euler(binary_image) # Print result print(“Eu ler Number:”, euler_number) Output Following is the output of the above code − Euler Number: -2.75 Euler Number with Different Connectivity We can also calculate the Euler number with different connectivity in Mahotas using the euler() function. The connectivity parameter determines which neighboring pixels are considered in the calculation. For example, using connectivity−4 considers only the immediate horizontal and vertical neighbors, while connectivity−8 includes diagonal neighbors as well. Example Here, we are calculating the Euler number with different connectivity for the “nature.jpeg” image − import mahotas as mh import numpy as np # Load the image as a grayscale image image = mh.imread(”sun.png”, as_grey=True) # Threshold the image to create a binary image thresholded_image = image > 0 # Compute the Euler number with 4-connectivity euler_number_4conn = mh.euler(thresholded_image, 4) # Compute the Euler number with 8-connectivity euler_number_8conn = mh.euler(thresholded_image, 8) # Print the results print(“Euler Number (4-connectivity):”, euler_number_4conn) print(“Euler Number (8-connectivity):”, euler_number_8conn) Output Output of the above code is as follows − Euler Number (4-connectivity): -4.75 Euler Number (8-connectivity): -4.75 Euler Number Calculation with Labelled Image A labeled image assigns unique integer labels to connected components in a binary image. In Mahotas, the euler function takes a labelled image as input and returns the Euler number for the entire image. The calculation takes into account the number of objects, holes, and tunnels between objects. Example In here, we are calculating the Euler number of a labeled image derived from the “sea.bmp” image − import mahotas as mh import numpy as np # Load the image as a grayscale image image = mh.imread(”sea.bmp”, as_grey=True) # Threshold the image to create a binary image thresholded_image = image > 0 # Label the connected components in the binary image labeled_image, num_labels = mh.label(thresholded_image) # Compute the Euler number of the labeled image euler_number = mh.euler(labeled_image) # Print the result print(“Euler Number:”, euler_number) Output After executing the above code, we get the following output − Euler Number: -44.75 Euler Number Calculation with Binary Image In Mahotas, the Euler number of a binary image can be calculated using the euler() function. By loading the binary image and converting it to a boolean format, the euler function takes the image as input and returns the Euler number as an integer. Example In the example given below, we are calculating the Euler number of a binary image created from the “nature.jpeg” image using Mahotas − import mahotas as mh # load binary image and convert to boolean format image = mh.imread(”sun.png”, as_grey= True) image = image.astype(bool) # calculate the Euler number euler_number = mh.euler(image) # print the result print(“Euler number of the binary image is:”, euler_number) Output The result obtained is as follows − Euler number of the binary image is: -4.75
Mahotas – RGB to Sepia Sepia refers to a special coloring effect that makes a picture look old−fashioned and warm. When you see a sepia−toned photo, it appears to have a reddish−brown tint. It”s like looking at an image through a nostalgic filter that gives it a vintage vibe. To convert an RGB image to sepia, you need to transform the red, green, and blue color channels of each pixel to achieve the desired sepia tone. RGB to Sepia Conversion in Mahotas In Mahotas, we can convert an RGB image to sepia−toned image using the colors.rgb2sepia() function. To understand the conversion, let”s start with the RGB color model − In RGB, an image is made up of three primary colors− red, green, and blue. Each pixel in the image has a value for these three colors, which determines its overall color. For example, if a pixel has high red and low green and blue values, it will appear as a shade of red. Now, to convert an RGB image to Sepia using mahotas, we follow a specific formula. The formula involves calculating new values for the red, green, and blue channels of each pixel. These new values create the Sepia effect by giving the image a warm, brownish tone. RGB to Sepia Conversion Steps Here”s a simple explanation of the conversion process − Start with an RGB image − An RGB image is composed of three color channels− red, green, and blue. Each pixel in the image has intensity values for these three channels, ranging from 0 to 255. Calculate the intensity of each pixel − To convert to sepia, we first need to calculate the overall intensity of each pixel. This can be done by taking a weighted average of the red, green, and blue color channels. The weights used in the average can be different depending on the desired sepia effect. Adjust the intensity values − Once we have the intensity values, we can apply some specific transformations to obtain the sepia effect. These transformations involve adjusting the levels of red, green, and blue channels in a way that mimics the sepia tone. This can be done by increasing the red channel”s intensity, decreasing the blue channel”s intensity, and keeping the green channel relatively unchanged. Clip the intensity values − After the adjustments, some intensity values may go beyond the valid range (0 to 255 for 8−bit images).To ensure the values stay within this range, we need to clip them. Values below 0 are set to 0, and values above 255 are set to 255. Reconstruct the sepia image − Finally, the adjusted intensity values are used to reconstruct the sepia image. The image now appears with the desired sepia tone, giving it a vintage look. Using the mahotas.colors.rgb2sepia() Function The mahotas.colors.rgb2sepia() function takes an RGB image as input and returns the sepia version of the image. The resulting sepia image retains the overall structure and content of the original RGB image but introduces a warm, brownish tone. Syntax Following is the basic syntax of the rgb2sepia() function in mahotas − mahotas.colors.rgb2sepia(rgb) where, rgb is the input image in RGB color space. Example In the following example, we are converting an RGB image to a sepia image using the mh.colors.rgb2sepia() function − import mahotas as mh import numpy as np import matplotlib.pyplot as mtplt # Loading the image image = mh.imread(”nature.jpeg”) # Converting it to Sepia sepia_image = mh.colors.rgb2sepia(image) # Creating a figure and axes for subplots fig, axes = mtplt.subplots(1, 2) # Displaying the original RGB image axes[0].imshow(image) axes[0].set_title(”RGB Image”) axes[0].set_axis_off() # Displaying the sepia image axes[1].imshow(sepia_image) axes[1].set_title(”Sepia Image”) axes[1].set_axis_off() # Adjusting spacing between subplots mtplt.tight_layout() # Showing the figures mtplt.show() Output Following is the output of the above code − Using Transformation Factor Another approach we can use to convert an RGB to sepia is by adjusting the intensities of each color channel using predetermined coefficients, which are based on the contribution of each channel to the final sepia image. The contribution of each channel to sepia is calculated as follows − TR = 0.393 * R + 0.769 * G + 0.189 * B TG = 0.349 * R + 0.686 * G + 0.168 * B TB = 0.272 * R + 0.534 * G + 0.131 * B where TR, TG and TB are the transformation factors of red, green, and blue respectively. Applying these transformations to each pixel in the RGB image results in the entire sepiatoned image. Example The following example shows conversion of an RGB image to sepia using transformation factors of the RGB channels − import mahotas as mh import numpy as np import matplotlib.pyplot as plt # Loading the image image = mh.imread(”sun.png”) # Getting the dimensions of the image height, width, _ = image.shape # Converting it to Sepia # Creating an empty array for the sepia image sepia_image = np.empty_like(image) for y in range(height): for x in range(width): # Geting the RGB values of the pixel r, g, b = image[y, x] # Calculating tr, tg, tb tr = int(0.393 * r + 0.769 * g + 0.189 * b) tg = int(0.349 * r + 0.686 * g + 0.168 * b) tb = int(0.272 * r + 0.534 * g + 0.131 * b) # Normalizing the values if necessary if tr > 255: tr = 255 if tg > 255: tg = 255 if tb > 255: tb = 255 # Setting the new RGB values in the sepia image array sepia_image[y, x] = [tr, tg, tb] # Creating a figure and axes for subplots fig, axes = plt.subplots(1, 2) # Displaying the original RGB image axes[0].imshow(image) axes[0].set_title(”RGB Image”) axes[0].set_axis_off() # Displaying the sepia image axes[1].imshow(sepia_image) axes[1].set_title(”Sepia Image”) axes[1].set_axis_off() # Adjusting spacing between subplots plt.tight_layout() # Showing the figures plt.show() Output Output of the above code is as follows −
Mahotas – Image Ellipse Axes An ellipse is a geometric shape which is defined as a curve in a plane surrounding two focal points, such that the sum of the distances to the two focal points is constant for every point on the curve. The major axis of an ellipse refers to the longest diameter, which passes through the two farthest points on the ellipse. The minor axis, on the other hand, is the shortest diameter and is perpendicular to the major axis, intersecting it at the center of the ellipse. These axes provide information about the size, orientation, and aspect ratio of the object or region. Image Ellipse Axes in Mahotas When dealing with ellipses in Mahotas, the axes are specified as a tuple of two values− the lengths of the semi−major and semi−minor axes. Mahotas provides the mahotas.ellipse_axes() function to easily detect ellipses in images and obtain their major and minor axes lengths. Using the ellipse.axes() Function The ellipse_axes() function in Mahotas is used to detect ellipse within images. This function accepts a binary image as input and returns the lengths of the major and minor axes. Syntax Following is the basic syntax to find the ellipse axes of an image in Mahotas − mahotas.features.ellipse_axes(bwimage) where, ”bwimage” is the single channel array of image, interpreted as Boolean. Example In the following example, we will learn how to find image ellipse axes in mahotas − import mahotas as mh import numpy as np image=mh.imread(”nature.jpeg”, as_grey = True) smajor,sminor = mh.features.ellipse_axes(image) print(smajor,sminor) Output Following is the output of the above code − 739.0056545212358 336.5943563176811 Fitting an Ellipse to a Set of Points We can also fit an ellipse to a specific points of interest by generating random points within the image. The random points are generated in a uniform distribution between 0 and 1 using the np.random.rand() function from the NumPy library. Each random number represents a coordinate value on a particular axis. To ensure that the generated points fall within the image boundaries − we multiply the randomly generated values by the shape of the image. The shape of the image represents the dimensions of the image as a tuple (height, width). By multiplying the randomly generated values by the image”s shape, we effectively scale the points to match the dimensions of the image. The resulting points are represented as (x, y) coordinates, where x represents the column index and y represents the row index of the image. Example In here, we are trying to fit an ellipse to a set of given points − import numpy as np import mahotas as mh image = mh.imread(”tree.tiff”, as_grey=True) # Generating a set of random points np.random.seed(0) points = np.random.rand(87, 2) * image.shape[:2] # Fitting an ellipse to the set of points # calculating the axes major_axis, minor_axis = mh.features.ellipse_axes(points) print(major_axis, minor_axis) Output Output of the above code is as follows − 50.226155204899634 1.0 Fitting an Ellipse to a Grayscale Image Using ROI We can fit an ellipse to a grayscale image using Region Of Interest (ROI) by generating random points of interest. Then, we need to create a binary image, where the points are set to white (pixel value 255), and the background is black (pixel value 0). We can accomplish this by − Initializing an array of zeros with the same shape as the original image. Then, setting the indices of the points of interest within the array to 255, effectively marking those locations as points of interest. This binary image allows us to isolate and focus on the specific points we want to analyze when fitting the ellipse, enabling us to estimate the estimate the ellipse”s parameters accurately based on the chosen points. Example Here, we are fitting an ellipse to a grayscale image using Region Of Interest − import numpy as np import mahotas as mh image = mh.imread(”sun.png”, as_grey=True) # Generating a binary image with points of interest np.random.seed(0) points = np.random.rand(100, 2) * image.shape[:2] points = points.astype(int) binary_image = np.zeros(image.shape, dtype=np.uint8) binary_image[points[:, 0], points[:, 1]] = 255 # Fitting an ellipse to the points of interest major_axis, minor_axis = mh.features.ellipse_axes(binary_image) print(major_axis, minor_axis) Output While executing the above code, we get the following output − 722.1261184969184 479.52790970346524