去除渐变的一种方法是使用cv2.medianBlur() 通过获取内核下所有像素的中值来平滑图像。然后提取字母,可以执行cv2.adaptiveThreshold()。
模糊消除了大部分梯度噪声。您可以更改内核大小以删除更多内容,但它也会删除字母的详细信息
自适应阈值图像提取字符。从您的原始图像来看,似乎在字母c、x 和z 上添加了渐变噪点,使其与背景融为一体。
接下来我们可以执行cv2.Canny()来检测边缘并得到这个
然后我们可以用cv2.morphologyEx()做形态开环,清理小噪点,增强细节
现在我们使用cv2.dilate() 进行扩张以获得单个轮廓
从这里,我们使用cv2.findContours() 找到轮廓。我们使用具有最小和最大区域的cv2.contourArea() 遍历每个轮廓和过滤器以获得边界框。根据您的图像,您可能需要调整最小/最大区域过滤器。这是结果
import cv2
import numpy as np
image = cv2.imread('1.png')
blur = cv2.medianBlur(image, 7)
gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,3)
canny = cv2.Canny(thresh, 120, 255, 1)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
opening = cv2.morphologyEx(canny, cv2.MORPH_CLOSE, kernel)
dilate = cv2.dilate(opening, kernel, iterations=2)
cnts = cv2.findContours(dilate, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
min_area = 500
max_area = 7000
for c in cnts:
area = cv2.contourArea(c)
if area > min_area and area < max_area:
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
cv2.imshow('blur', blur)
cv2.imshow('thresh', thresh)
cv2.imshow('canny', canny)
cv2.imshow('opening', opening)
cv2.imshow('dilate', dilate)
cv2.imshow('image', image)
cv2.waitKey(0)