Cropping an image refers to selecting and extracting a specific region of interest from an image and discarding the rest. It allows us to focus on a particular area or object within an image while removing irrelevant or unwanted portions.
To crop an image in general, you need to define the coordinates or dimensions of the region you want to keep.
Cropping an Image in Mahotas
To crop an image using Mahotas, we can use NumPy array slicing operation to select the desired region of the image. We need to define the coordinates or dimensions of the desired ROI. This can be done by specifying the starting point, width, and height of the region to be cropped.
By extracting and isolating the ROI, we can analyze, manipulate, or display only the relevant part of the image.
Example
In the following example, we are cropping the image to the desired size −
import mahotas as mh import numpy as np import matplotlib.pyplot as plt image = mh.imread(''sun.png'') cropping= image[50:1250,40:340] # 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 cropped image axes[1].imshow(cropping, cmap=''gray'') axes[1].set_title(''Cropped Image'') axes[1].axis(''off'') # Adjust the layout and display the plot plt.tight_layout() plt.show()
Output
Following is an output of the above code −
Cropping a Square Region
To crop a square region in mahotas, we need to determine the starting and ending rows and columns. Here is an approach to calculate these values −
Step 1 − Find the minimum dimension of the image.
Step 2 − Compute the starting row by subtracting the minimum dimension from the total
number of rows and dividing the result by 2.
Step 3 − Calculate the ending row by adding the starting row to the minimum dimension.
Step 4 − Compute the starting column using a similar approach.
Step 5 − Calculate the ending column by adding the starting column to the minimum dimension.
Using the calculated starting and ending rows and columns, we can crop the square region from the image. We accomplish this by indexing the image array with the appropriate row and column ranges.
Example
Here, we are trying to crop an image in a square region −
import mahotas as mh import numpy as np import matplotlib.pyplot as plt image = mh.imread(''tree.tiff'') # Get the minimum dimension size = min(image.shape[:2]) # Calculating the center of the image center = tuple(map(lambda x: x // 2, image.shape[:2])) # Cropping a square region around the center crop = image[center[0] - size // 2:center[0] + size // 2, center[1] - size // 2:center[1] + size // 2] # 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 cropped image axes[1].imshow(crop, cmap=''gray'') axes[1].set_title(''Cropped Image'') axes[1].axis(''off'') # Adjust the layout and display the plot plt.tight_layout() plt.show()
Output
After executing the above code, we get the following output −
Cropping a Circular Region
To crop the image to a circular region in mahotas, we need to determine the center coordinates and radius of the circle.
We can achieve this by calculating the center as the midpoint of the image dimensions and setting the radius as half the minimum dimension.
Next, we create a boolean mask with the same dimensions as the image, where True values indicate the pixels within the circular region.
We accomplish this by calculating the distance of each pixel from the center and setting True for pixels that fall within the specified radius.
Now that we have the circular mask, we can apply it to the image by setting the values outside the circular region to zero. Finally, we get the cropped image.
Example
Now, we are trying to crop an image in a circular region −
import mahotas as mh import numpy as np import matplotlib.pyplot as plt image = mh.imread(''sun.png'') # Calculating the center of the image center = tuple(map(lambda x: x // 2, image.shape[:2])) # Calculating the radius as half the minimum dimension radius = min(image.shape[:2]) // 2 # Creating a boolean mask of zeros mask = np.zeros(image.shape[:2], dtype=bool) # Creating meshgrid indices y, x = np.ogrid[:image.shape[0], :image.shape[1]] # Setting mask values within the circular region to True mask[(x - center[0])**2 + (y - center[1])**2 <= radius**2] = True crop = image.copy() # Setting values outside the circular region to zero crop[~mask] = 0 # Create a figure with subplots fig, axes = plt.subplots(1, 2, figsize=(7, 5)) # Display the original image axes[0].imshow(image) axes[0].set_title(''Original Image'') axes[0].axis(''off'') # Display the cropped image axes[1].imshow(crop, cmap=''gray'') axes[1].set_title(''Cropped Image'') axes[1].axis(''off'') # Adjust the layout and display the plot plt.tight_layout() plt.show()
Output
The output obtained is as shown below −