代码可能会进行很多优化(大麦从编程开始)并且速度非常慢,但它可能对您的情况有所帮助或只是给您一个想法。我所做的是找到所有轮廓并将它们绘制在空白蒙版上。然后您可以使用cv2.findNonZero 确定轮廓的所有非黑色(零)像素。之后,您可以搜索所有相似点,例如具有相同 x 坐标和略有不同 y 坐标的点(在示例图片中 +-2) - 这代表您的空白区域。之后,您可以简单地用cv2.line() 绘制线条,它将填充空白区域。然后只需再次搜索轮廓并绘制边界框。希望能帮助到你。干杯!
示例代码:
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)
输入图像(黑色文本,用白线将其分成两半):
结果: