How to sharpen the edges in opencv python

I am learning image processing in which I am trying to sharpen the edges of the images using opencv in python , i have reduced the noise as much as i could but now i want to make the edges of the image more clear , i have tried cv2.Canny() but it didn’t work out as much.

this is the image

enter image description here

After applying c2.Canny()

enter image description here

but I am trying to more sharp the words border or edges

this is my code

import cv2
import matplotlib.pyplot as plt
img_1 = cv2.imread('noise/1.png',cv2.IMREAD_GRAYSCALE)
edges = cv2.Canny(img_1,200,200)
plt.imshow(edges)

Answer

Here is one way to handle that in Python/OpenCV.

  • Read the input as grayscale
  • Threshold it to be sure it is binary
  • Apply morphology close
  • Find contours and removal all small areas in the input by drawing black over them
  • Apply Canny edge detection
  • Save the results

Input:

enter image description here

import cv2
import numpy as np

# read image as grayscale
img = cv2.imread('K.png', cv2.IMREAD_GRAYSCALE)

# threshold to binary
thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY)[1]

# apply morphology
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
morph = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)

# find contours - write black over all small contours
letter = morph.copy()
cntrs = cv2.findContours(morph, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]
for c in cntrs:
    area = cv2.contourArea(c)
    if area < 100:
        cv2.drawContours(letter,[c],0,(0,0,0),-1)

# do canny edge detection
edges = cv2.Canny(letter, 200, 200)

# write results
cv2.imwrite("K_thresh.png", thresh)
cv2.imwrite("K_morph.png", morph)
cv2.imwrite("K_letter.png", letter)
cv2.imwrite("K_edges.png", edges)

# show results
cv2.imshow("K_thresh", thresh)
cv2.imshow("K_morph", morph)
cv2.imshow("K_letter", letter)
cv2.imshow("K_edges", edges)
cv2.waitKey(0)


Thresholded image:

enter image description here

Morphology Open applied:

enter image description here

Small areas removed:

enter image description here

Canny edges:

enter image description here

Leave a Reply

Your email address will not be published. Required fields are marked *