How to fit a jagged binary image with a straight line?

Viewed 132

I have a binary image like the following: The binary image has jagged edge on the lower part

I want to find a straight line to fit the jagged edge, like this: enter image description here

What will be a good way to do it? The fitting does not need to be precise, and speed is more critical in my case.

1 Answers

In order to find corners in your image you can use the goodFeaturesToTrack function in CV2.

When you find the corners, you should consider the corners close to the jagged edge.

Then, you can draw a straight line between:

  1. If the jagged edge is horizontal - the left most corner to the right.
  2. If the edge is vertical - from the highest to lowest corner.
# Required libraries
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt

# First, read the image
img = cv2.imread("kitT9.png", cv2.COLOR_BGR2GRAY)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

# Order the parameters for the `cv.goodFeaturesToTrack` function
input_img = gray
maxCorners = 20
qualityLevel = 0.01
minDistance = 1
corners = cv.goodFeaturesToTrack(input_img, maxCorners, qualityLevel, minDistance)

# This is useful for debugging: draws the corners on the image.
corners = np.int0(corners)
for i in corners:
    x, y = i.ravel()
    cv.circle(img, (x, y), 3, 255, -1)

# This part sorts the corners from left to right.
def sorter(x):
    return x[0][0]


corners = sorted(corners, key=sorter)

# Extract the coordinates of the leftmost and rightmost corners
left_corner = corners[0]
right_corner = corners[-1]
x1 = left_corner[0][0]
y1 = left_corner[0][1]
x2 = right_corner[0][0]
y2 = right_corner[0][1]

# Draw the required line!
line_thickness = 2
img = cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), thickness=line_thickness)

# In a notebook, show the final result 
plt.imshow(img), plt.show()

The output result

Related