python - 在python中使用openCV查找文档中打印区域(文本或图像)的X和Y坐标

标签 python opencv image-processing

我有输入图像Input Image。我想找到“文本”区域的文档布局。我尝试使用“凸包”

当我做“凸包”并为其绘制计数器时。输出是
Output Image

它没有标记文档的打印区域。我们如何找到它的X和Y坐标

下面是代码

import cv2
# Load the image
img1 = cv2.imread(r'TestImage.jpg')
# Convert it to greyscale
img = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
# Threshold the image
ret, thresh = cv2.threshold(img,50,255,0)
# Find the contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# For each contour, find the convex hull and draw it
# on the original image.
hull=[]
for i in range(len(contours)):
    hullv=cv2.convexHull(contours[i])
    hull.append(cv2.convexHull(contours[i]))
    # print(hull)
    cv2.drawContours(img1, [hullv], -1, (255, 0, 0), 2)

cv2.imwrite(r"contours1.png",img1)

最佳答案

如果您所有文档的右上角都有图像,而其余的是文本,那么您可以执行的一种方法是将图像转换为黑白图像,进行某种形态上的闭合以弥合与图像之间的空白。文字并总结每一行。然后,您可以找到一个非常大的峰值的点,该峰值指示文本的开始位置。之所以起作用,是因为文本覆盖了每一行图像中的大部分列,而图像仅覆盖了一小部分列。当您遍历每一行并计算每一行中非零像素的总数时,您将获得相对较小的总和,直到遇到第一行文本为止,这将使您的总和配置文件发生很大的变化。发生此更改的地方是您的文本开始的地方。您可以从该点开始裁剪到文档末尾。我想指出的一件事是,您的文字在浅色背景上是深色的。当转换为二进制时,我们需要将其反转,以便白色文本位于深色背景上,以使行求和逻辑起作用。

这样的事情可以工作:

import cv2
import numpy as np

# Read in image, convert to grayscale, then convert to binary
im = cv2.imread('OghQo.jpg') # Downloaded from Stack Overflow and read offline
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
_, im_bw = cv2.threshold(im_gray, 5, 255, cv2.THRESH_BINARY_INV)

# Performing morphological closing
se = np.ones((20, 30), dtype=np.uint8)
im_bw2 = cv2.morphologyEx(im_bw, cv2.MORPH_CLOSE, se)

# Calculate row sums
row_sums = im_bw2.sum(axis=1)

# Find the row which exceeds the threshold
threshold_row = 80000
row_index = np.argmax(row_sums > threshold_row)

# Crop the image with a bit of breathing room
buffer_size = 10
crop = im[row_index - buffer_size:]

# Show the image
cv2.imshow("Cropped", crop)
cv2.waitKey(0)
cv2.destroyAllWindows()

在我掌握合理的条件之前,我一直在玩这个阈值。现在我们得到:

enter image description here

关于python - 在python中使用openCV查找文档中打印区域(文本或图像)的X和Y坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60721039/

相关文章:

python - OpenCV和Python:knnMatch参数问题

c++ - cv::cuda::Stream 选择线程默认流

python - imread_collection() 加载模式 (scikit-images Python)

python - 调用嵌套 Serializer 的 .update() 方法

python - 系列的第一个元素在 numpy 中跨越阈值,处理永不跨越的系列

python - brew install python 安装 python2

python - 如何获取tqdm的当前值?

c++ - 使用 OpenCV 找到没有狭窄瓶颈的连续区域

ios - GPU 内存因 GPUImage 而崩溃

python - 在图像对齐之前先进行亮度/对比度校正,反之亦然?