PederBG
PederBG

Reputation: 138

OpenCV - Find contours of area without clear borders

I'm having some images where I want to filter out the black areas using OpenCV with python. The problem is that these images comes from satellite footage and have no clear borders.

In the images added above, the first is the original image while the second is a blurred version, i'm interested in the small dark area in the middle. Ultimately I want to have this area marked as a singe contour area.

My main problem seems to be that when I use the OpenCV findContours function, I get a lot of small contours instead of one (or two) big ones.

I'm fairly new to OpenCV so any help would be appreciated!

Upvotes: 2

Views: 2927

Answers (1)

Jack Gold
Jack Gold

Reputation: 201

Here are just some rough results I have been able to obtain with a simple pipeline: enter image description here The code is fairly self-explanatory too

import cv2
import numpy as np

def nothing(x):
    pass

cv2.namedWindow('image')
cv2.createTrackbar('high','image',0,255,nothing)
cv2.createTrackbar('low','image',0,255,nothing)
cv2.namedWindow('Edges')

while(1):
    image = cv2.imread("PATH TO IMAGE HERE")
    imgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    high = cv2.getTrackbarPos('high', 'image')
    low = cv2.getTrackbarPos('low', 'image')

    edges = cv2.Canny(imgray, low, high)
    kernel = np.ones((8, 8), np.uint8)
    closing = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)

    cv2.imshow('Edges', closing)

    ret,thresh = cv2.threshold(closing,low,high,0)
    im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    largest_area = 0
    largest_contour_index = 0
    counter = 0
    for i in contours:
        area = cv2.contourArea(i)
        if (area > largest_area):
            largest_area = area
            largest_contour_index = counter

        counter = counter + 1

    cv2.drawContours(image, contours, largest_contour_index, (0,255,0), 1)

    cv2.imshow('image', image)

    k = cv2.waitKey(1) & 0xFF
    if k == 27:
        break 

The pipeline is as follows:

  1. Read smooth image
  2. Convert to grayscale
  3. Apply the morphological operation closing (8x8 mask)
  4. Find contours
  5. Find the largest contour (area wise)

Upvotes: 3

Related Questions