How to make boundaries of an object well defined?

927 views Asked by At

Is there any tool to make the boundaries to be well defined in an image. I am using Python-OpenCV. Does it have any methods for this functionality?

For eg.

Let my input image be like this.

enter image description here

You can see some disturbances on the boundaries. Some pixels are just projecting from boundary. Boundaries are not perfect straight lines.

Desired output is some thing like this.

enter image description here

2

There are 2 answers

2
Andrey  Smorodov On

You can do OCR, then print the result with desired font. No other way to transform your input image to perfect desired shape.

0
alkasm On

You could detect contours in the image with cv2.findContours() and then approximate the contours with lines. See the contour approximation section on the OpenCV contours tutorial. Notice in the tutorial that the parts that shoot inside the box could be a bit jagged, but the contour approximation just gives nice straight lines to draw. You can think of the K the same way, the overall contours are like a box but with pieces dipping inside.

This seemed to work well:

import cv2
import numpy as np

img = cv2.imread('k.png', 0)  # read as grayscale
img = 255 - img  # flip black and white

# find contours in the image
bin_img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1]
mode = cv2.RETR_EXTERNAL
method = cv2.CHAIN_APPROX_SIMPLE
contours = cv2.findContours(bin_img, mode, method)[1]

# take largest contour, approximate it
contour = contours[0]  
epsilon = 0.005 * cv2.arcLength(contour, True)
approx_contour = cv2.approxPolyDP(contour, epsilon, True)

contour_img = np.zeros_like(img)
contour_img = cv2.fillPoly(contour_img, [approx_contour], 255)
contour_img = 255 - contour_img  # flip back black and white

cv2.imshow('Fixed k', contour_img)
cv2.waitKey()

Input: Input K

Output: Approximated contours of K