Remove spurious small islands of noise in an image - Python OpenCV

Remove spurious small islands of noise in an image - Python OpenCV

To remove small islands of noise (also known as "salt and pepper" noise) in an image using Python and OpenCV, you can use morphological operations like erosion and dilation. These operations help in removing small isolated white or black pixels that do not belong to the main structures in the image.

Here's how you can do it:

import cv2 import numpy as np # Load the image image = cv2.imread('input_image.jpg', cv2.IMREAD_GRAYSCALE) # Define kernel for morphological operations kernel = np.ones((3, 3), np.uint8) # Apply morphological opening (erosion followed by dilation) to remove small islands opened_image = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel) # Save the result cv2.imwrite('output_image.jpg', opened_image) 

In this example, we use the morphological opening operation (cv2.morphologyEx()) to remove small isolated white regions in the image. The kernel defines the shape of the structuring element used for the operations.

The larger the structuring element, the more aggressive the noise reduction. You can adjust the kernel size based on the size of the noise you want to remove.

Remember to replace 'input_image.jpg' with the path to your input image and 'output_image.jpg' with the desired output path.

Note that morphological operations like opening and closing can also alter the shapes and boundaries of the main structures in the image. If that's a concern, you might need to experiment with the kernel size or explore other noise reduction techniques like median filtering or Gaussian blurring before applying morphological operations.

Examples

  1. Remove Small Noise Islands in Binary Images with OpenCV

    • Description: This query seeks to remove small noise islands from a binary image by eliminating connected components below a certain size.
    • Code:
      import cv2 import numpy as np # Load a binary image binary_image = cv2.imread("image.png", cv2.IMREAD_GRAYSCALE) # Label connected components and keep only large ones num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(binary_image) # Minimum size for connected components min_size = 100 # Filter out small components new_image = np.zeros(binary_image.shape, dtype=np.uint8) for i in range(1, num_labels): if stats[i, cv2.CC_STAT_AREA] >= min_size: new_image[labels == i] = 255 # Keep large components cv2.imwrite("filtered_image.png", new_image) 
  2. Use Morphological Operations to Remove Small Islands in OpenCV

    • Description: This query focuses on using morphological operations, like opening, to remove small noise islands.
    • Code:
      import cv2 import numpy as np # Load a binary image binary_image = cv2.imread("image.png", cv2.IMREAD_GRAYSCALE) # Define a kernel for morphological operations kernel = np.ones((3, 3), np.uint8) # Apply opening to remove small noise islands cleaned_image = cv2.morphologyEx(binary_image, cv2.MORPH_OPEN, kernel, iterations=2) cv2.imwrite("opened_image.png", cleaned_image) 
  3. Filter Small Contours to Remove Noise Islands with OpenCV

    • Description: This query is about finding contours and filtering out those smaller than a given area.
    • Code:
      import cv2 import numpy as np # Load a binary image binary_image = cv2.imread("image.png", cv2.IMREAD_GRAYSCALE) # Find all contours in the image contours, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Filter contours by size min_area = 100 large_contours = [c for c in contours if cv2.contourArea(c) >= min_area] # Create a new image with only large contours filtered_image = np.zeros(binary_image.shape, dtype=np.uint8) cv2.drawContours(filtered_image, large_contours, -1, (255), thickness=cv2.FILLED) cv2.imwrite("filtered_contours.png", filtered_image) 
  4. Remove Small Noise Islands in Grayscale Images with OpenCV

    • Description: This query discusses removing small noise islands from a grayscale image, typically using adaptive thresholding.
    • Code:
      import cv2 import numpy as np # Load a grayscale image gray_image = cv2.imread("image.png", cv2.IMREAD_GRAYSCALE) # Apply adaptive thresholding to create a binary image binary_image = cv2.adaptiveThreshold( gray_image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 2 ) # Use connected components to remove small islands num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(binary_image) min_size = 100 cleaned_image = np.zeros(binary_image.shape, dtype=np.uint8) for i in range(1, num_labels): if stats[i, cv2.CC_STAT_AREA] >= min_size: cleaned_image[labels == i] = 255 cv2.imwrite("cleaned_image.png", cleaned_image) 
  5. Use Region Properties to Remove Noise Islands with OpenCV

    • Description: This query uses region properties to identify and remove noise islands by considering their geometrical properties.
    • Code:
      import cv2 import numpy as np # Load a binary image binary_image = cv2.imread("image.png", cv2.IMREAD_GRAYSCALE) # Get connected components and their stats num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(binary_image) # Filter components by bounding box dimensions min_width = 5 min_height = 5 cleaned_image = np.zeros(binary_image.shape, dtype=np.uint8) for i in range(1, num_labels): if stats[i, cv2.CC_STAT_WIDTH] >= min_width and stats[i, cv2.CC_STAT_HEIGHT] >= min_height: cleaned_image[labels == i] = 255 cv2.imwrite("region_filtered.png", cleaned_image) 
  6. Remove Spurious Noise Using Morphological Closing in OpenCV

    • Description: This query discusses using morphological closing to remove small gaps or noise in images.
    • Code:
      import cv2 import numpy as np # Load a binary image binary_image = cv2.imread("image.png", cv2.IMREAD_GRAYSCALE) # Define a kernel for morphological operations kernel = np.ones((3, 3), np.uint8) # Apply closing to remove small gaps or noise cleaned_image = cv2.morphologyEx(binary_image, cv2.MORPH_CLOSE, kernel, iterations=2) cv2.imwrite("closed_image.png", cleaned_image) 
  7. Remove Small Noise Islands in Color Images with OpenCV

    • Description: This query deals with removing noise islands from color images by converting to grayscale and applying filters.
    • Code:
      import cv2 import numpy as np # Load a color image color_image = cv2.imread("image.png") # Convert to grayscale gray_image = cv2.cvtColor(color_image, cv2.COLOR_BGR2GRAY) # Apply adaptive thresholding to create a binary image binary_image = cv2.adaptiveThreshold( gray_image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 2 ) # Use connected components to remove small islands num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(binary_image) min_size = 100 cleaned_image = np.zeros(binary_image.shape, dtype=np.uint8) for i in range(1, num_labels): if stats[i, cv2.CC_STAT_AREA] >= min_size: cleaned_image[labels == i] = 255 cv2.imwrite("cleaned_color_image.png", cleaned_image) 
  8. Isolate and Remove Specific Noise Components in OpenCV

    • Description: This query targets isolating specific noise components based on their shape or other region properties.
    • Code:
      import cv2 import numpy as np # Load a binary image binary_image = cv2.imread("image.png", cv2.IMREAD_GRAYSCALE) # Get connected components and their stats num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(binary_image) # Consider a specific property, like the solidity of the components cleaned_image = np.zeros(binary_image.shape, dtype=np.uint8) for i in range(1, num_labels): area = stats[i, cv2.CC_STAT_AREA] hull = cv2.convexHull(np.column_stack(np.where(labels == i))) hull_area = cv2.contourArea(hull) solidity = area / hull_area if hull_area > 0 else 0 # Retain only components with a solidity above a certain threshold if solidity >= 0.8: cleaned_image[labels == i] = 255 cv2.imwrite("solidity_filtered.png", cleaned_image) 
  9. Use Edge Detection to Remove Small Noise Islands in OpenCV

    • Description: This query focuses on using edge detection techniques to isolate and remove noise islands by identifying prominent edges.
    • Code:
      import cv2 import numpy as np # Load a grayscale image gray_image = cv2.imread("image.png", cv2.IMREAD_GRAYSCALE) # Apply Canny edge detection edges = cv2.Canny(gray_image, 50, 150) # Apply dilation to connect edges kernel = np.ones((3, 3), np.uint8) edges_dilated = cv2.dilate(edges, kernel, iterations=1) # Use the dilated edges to isolate regions cleaned_image = cv2.bitwise_and(gray_image, edges_dilated) cv2.imwrite("edge_filtered.png", cleaned_image) 
  10. Use Median Blurring to Reduce Noise Islands in OpenCV

    • Description: This query uses median blurring to reduce noise by replacing each pixel's value with the median of the neighboring pixels.
    • Code:
      import cv2 import numpy as np # Load a grayscale image gray_image = cv2.imread("image.png", cv2.IMREAD_GRAYSCALE) # Apply median blurring to reduce noise blurred_image = cv2.medianBlur(gray_image, 5) # 5x5 kernel cv2.imwrite("median_blurred.png", blurred_image) 

More Tags

image-segmentation fastlane sections spring-kafka android-source spacy http-options-method line-intersection createjs apache-commons-httpclient

More Python Questions

More Animal pregnancy Calculators

More Organic chemistry Calculators

More Dog Calculators

More Internet Calculators