如果初始图像是这样的(上方),那么我可以成功地在两行之间插入空格并获得该图像(下方)
使用下面的代码:
import os
import cv2
def space_between_lines_and_skewness_correction(file_path):
img = cv2.imread(os.path.expanduser(file_path))
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
th, threshed = cv2.threshold(grey, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
pts = cv2.findNonZero(threshed)
ret = cv2.minAreaRect(pts)
(cx, cy), (w, h), ang = ret
if w < h:
w, h = h, w
ang += 90
M = cv2.getRotationMatrix2D((cx, cy), ang, 1.0)
rotated = cv2.warpAffine(threshed, M, (img.shape[1], img.shape[0]))
hist = cv2.reduce(rotated, 1, cv2.REDUCE_AVG).reshape(-1)
th = 2
H, W = img.shape[:2]
delimeter = [y for y in range(H - 1) if hist[y] <= th < hist[y + 1]]
arr = []
y_prev = 0
y_curr = 0
for y in delimeter:
y_prev = y_curr
y_curr = y
arr.append(rotated[y_prev:y_curr, 0:W])
arr.append(rotated[y_curr:H, 0:W])
space_arr = np.zeros((10, W))
final_img = np.zeros((1, W))
for im in arr:
v = np.concatenate((space_arr, im), axis=0)
final_img = np.concatenate((final_img, v), axis=0)
return final_img
上面的代码将消除偏斜并引入空间。但是在少数情况下,上面的代码不起作用。这些是类似的情况:图像的输出是
如何处理这种情况?
注意:我尝试将尺寸调整为更大的尺寸,并逐像素迭代并为此情况构建自定义算法,但解决该问题需要花费大量时间,有时会出现内存错误。
请注意:以上代码的输入实际上是此处提供的图像的逆图像(白色背景)
也许这会有所帮助:
def detect_letters(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# just to remove noise
thresh_val, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
num_labels, _, stats, centroids = cv2.connectedComponentsWithStats(thresh)
for i in range(num_labels):
leftmost_x = stats[i, cv2.CC_STAT_LEFT]
topmost_y = stats[i, cv2.CC_STAT_TOP]
width = stats[i, cv2.CC_STAT_WIDTH]
height = stats[i, cv2.CC_STAT_HEIGHT]
# enclose all detected components in a blue rectangle
cv2.rectangle(img, (leftmost_x, topmost_y), (leftmost_x + width, topmost_y + height), (255, 0, 0), 2)
cv2.imshow("window", img)
cv2.waitKey(0) & 0xFF
输出:
上述解决方案的主要目的是在每个字母周围都包含一个封闭的矩形。
现在您要做的就是将所有这些字母移到上方或下方或任何您想要的位置。
例如,在以下链接中查看足球的变化方式:https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_core/py_basic_ops/py_basic_ops.html
您现在知道每个字母的最高和最低y坐标,您可以看到它们当前有多远,如果它们非常接近,只需按上述链接中的字母移动即可。
同一行上的字母的顶点坐标或质心几乎没有差异。您可以在允许的范围内找出所有这些字母。
如果有任何问题,请随时提问。