0
votes

I want to remove background and sharpen the images of following type: image 1

image 2

Both of these are signatures. I want to be able to remove everything except the signature itself and sharpen the lines of signature. I am able to get a mask using Canny edge detection using following code

import cv2
im_path  = r'test2.png'
image = cv2.imread(im_path) #args["image"]
image = cv2.resize(image, (680, 460))
#rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

cv2.imshow('thresh', thresh) ###for showing 

cv2.imwrite('thresh.jpg', thresh) ###for saving
cv2.waitKey()

And these are masks I get; mask

But Im clueless about what Image processing operations to perform next.

PS: These signatures are same (not forged) and next step would be to find similarity between them.

1
You don’t have a Canny edge detection in that code. What is your goal?Do you want to set the background to be all white? What must happen to the blurriness at the edges of the signature in the input image? What is the intended use of the output?Cris Luengo
@CrisLuengo I want to be able to match two images. Nothing fancy. Just need to be able to tell if two signatures are similar or not.Fatima Arshad

1 Answers

1
votes

Try this

import cv2
import numpy as np

image = cv2.imread("r'test2.png'")
original = image.copy()
mask = np.zeros(image.shape, dtype=np.uint8)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=3)

cnts = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
for c in cnts:
    cv2.drawContours(mask, [c], -1, (255,255,255), -1)
    break

close = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=4)
close = cv2.cvtColor(close, cv2.COLOR_BGR2GRAY)
result = cv2.bitwise_and(original, original, mask=close)
result[close==0] = (255,255,255)

cv2.imshow('result', result)
cv2.waitKey()