如何利用Canny边缘检测去除背景

2024-04-25 18:26:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想删除背景并锐化以下类型的图像: image 1

image 2

这两个都是签名。我希望能够删除除签名本身以外的所有内容,并锐化签名线条。 我能够得到一个面具使用坎尼边缘检测使用以下代码

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()

这些是我得到的面具; mask

但是我不知道下一步要执行什么图像处理操作

附言:这些签名是相同的(不是伪造的),下一步就是找出它们之间的相似之处


Tags: path图像image类型内容forcv2color
1条回答
网友
1楼 · 发布于 2024-04-25 18:26:19

试试这个

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()

相关问题 更多 >