用空白pix检测轮廓

2024-04-26 11:47:33 发布

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

我目前正在尝试使用opencv在python中的图像中检测字符的轮廓,并围绕这些特定的轮廓绘制一个边界矩形。在

问题是我有一个字符“<;”,其中包括扫描时产生的噪声,中间有一条1像素的空白线。得到的轮廓找到了2个不同的轮廓。在

这是字符:problem

(在检测轮廓之前,我应用了二进制阈值)

有没有一种方法可以指示opencv连接两个过于接近的轮廓?在

干杯, 阿斯特鲁斯


Tags: 方法图像lt二进制绘制阈值像素字符
2条回答

代码可能会被优化很多(barey是从编程开始的),速度非常慢,但可能对您的情况有帮助,或者只是给您一个想法。我所做的就是找到所有的轮廓,然后在一个空白的面具上画出来。然后可以使用cv2.findNonZero确定轮廓的所有非黑色(零)像素。之后,你可以搜索所有类似的点,比如那些x坐标相同,y坐标稍有不同的点(在示例图片+-2中),这代表你的空白。之后,您可以简单地用^ {CD2}}绘制线条,并填充空白空间。然后只需再次搜索轮廓并绘制边界框。希望有帮助。干杯!在

示例代码:

import cv2
import numpy as np

img  = cv2.imread('seperated_example.png')
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray_image,170,255,cv2.THRESH_BINARY_INV)
_, contours, _ = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
mask = np.zeros(gray_image.shape,np.uint8)
cv2.drawContours(mask, contours, -1, 255, -1)
pixelpoints = cv2.findNonZero(mask)

for i in pixelpoints:
    for j in pixelpoints:
        if int(i[:,0]) == int(j[:,0]) and int(i[:,1]) == int(j[:,1]):
            pass
        else:
            if int(i[:,0]) == int(j[:,0]) and int(j[:,1])-2 <= int(i[:,1]) <= int(j[:,1])+2:
                cv2.line(img, (int(i[:,0]), int(i[:,1])), (int(j[:,0]), int(j[:,1])), (0,0,0), 1)

cv2.imwrite('seperated_result.png', img)
cv2.imshow('img', img)

img = cv2.imread('seperated_result.png')
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray_image,170,255,cv2.THRESH_BINARY_INV)
_, contours, _ = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

for i in contours:
    cnt = i
    x,y,w,h = cv2.boundingRect(cnt)
    cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),1)

cv2.imwrite('seperated_result2.png', img)
cv2.imshow('img2', img)

输入图像(黑色文本,白线一分为二):

enter image description here

结果:

enter image description here

enter image description here

使用尺寸至少为3x3的中值过滤器。在

相关问题 更多 >