gpt4 book ai didi

python - 如何在OpenCV中构造二值图像的水平投影

转载 作者:行者123 更新时间:2023-12-02 16:46:26 30 4
gpt4 key购买 nike

我正在为学校做一个文本分割项目。我需要对二进制图像进行水平图像投影。我想要的结果是这样的:

Example from quora[1] .

我在 Python 中使用 OpenCV。我使用 x_sum = cv2.reduce(img, 0, cv2.REDUCE_SUM, dtype=cv2.CV_32S) 来获取总和数组,正如这个问题所建议的:horizontal and vertical projection of an image这个问题:Horizontal Histogram in OpenCV .

我尝试使用cv2.calcHist 获取水平投影图像,但我得到的只是一条水平线。我的代码如下:

image = cv2.imread(file_name)
x_sum = cv2.reduce(image, 0, cv2.REDUCE_SUM, dtype=cv2.CV_32S)
horizontal_projection=cv2.calcHist(x_sum,[0],None,[256],[0,256])
cv2.imwrite("image2.png", horizontal_projection)

请帮助并告诉我我做错了什么。我需要我的水平投影结果就像 Quora 示例一样。

最佳答案

在计算投影时,您基本上想要对图像每一行的像素求和。但是,您的文本是黑色的,它被编码为零,因此您会在一行中有很多文本的地方得到小数字,而在一行中文本很少的地方得到大数字 - 这与您想要的相反 - 所以你需要反转:

import cv2
import numpy as np

# Load as greyscale
im = cv2.imread('text.png', cv2.IMREAD_GRAYSCALE)

# Invert
im = 255 - im

# Calculate horizontal projection
proj = np.sum(im,1)

数组 proj 现在有 141 行高,每行对应于图像该行中的文本量:

array([    0,     0,     0,     0,    40,    44,   144,   182,   264,
326, 425, 1193, 2718, 5396, 9272, 11880, 13266, 13597,
12906, 11962, 10791, 9647, 8554, 20469, 45426, 65714, 81397,
81675, 66590, 58714, 58046, 60516, 66136, 71794, 77552, 78555,
74868, 72083, 70139, 70160, 72174, 76409, 82854, 88962, 94721,
88105, 69126, 47753, 23966, 13845, 17406, 19145, 19079, 16548,
11524, 8511, 7465, 7042, 7197, 6577, 5022, 3476, 1797,
809, 450, 309, 348, 351, 250, 232, 271, 279,
251, 628, 1419, 3259, 6187, 8272, 9551, 9825, 9119,
7984, 6444, 5305, 4596, 13385, 31647, 46330, 57459, 56139,
42402, 34928, 33729, 35055, 38874, 41649, 43394, 43265, 41291,
40126, 39767, 40515, 42390, 44478, 46793, 47881, 47743, 43983,
36644, 28054, 18242, 15583, 20047, 22038, 21569, 17751, 10571,
6830, 6580, 6231, 5681, 4595, 2879, 1642, 771, 365,
320, 282, 105, 88, 76, 76, 28, 28, 28,
28, 0, 0, 0, 0, 0], dtype=uint64)

我将您的图片裁剪为 819x141 像素,如下所示:

enter image description here


有很多方法可以进行可视化。这是一个:

#!/usr/bin/env python3

import cv2
import numpy as np

# Load as greyscale
im = cv2.imread('text.png', cv2.IMREAD_GRAYSCALE)

# Invert
im = 255 - im

# Calculate horizontal projection
proj = np.sum(im,1)

# Create output image same height as text, 500 px wide
m = np.max(proj)
w = 500
result = np.zeros((proj.shape[0],500))

# Draw a line for each row
for row in range(im.shape[0]):
cv2.line(result, (0,row), (int(proj[row]*w/m),row), (255,255,255), 1)

# Save result
cv2.imwrite('result.png', result)

enter image description here

关于python - 如何在OpenCV中构造二值图像的水平投影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54285839/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com