【问题标题】:Locating X&Y of horizontal lines in PDF or JPG在 PDF 或 JPG 中定位水平线的 X&Y
【发布时间】:2021-01-06 17:47:49
【问题描述】:

我正在尝试定位 PDF 文档中所有水平线的 X&Y。 我在这里使用代码: code to detect horizontal lines

这段代码很好地标记了水平线,但我无法在文档中提取它们的坐标。

这是我的代码:

def DetectLine(pageNum):
    # Convert to grayscale and adaptive threshold to obtain a binary image
    img = cv2.imread(outpath + 'page_' + str(pageNum) + '.jpg')
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
    # Then we create a kernel and perform morphological transformations to isolate horizontal lines
    horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15,1))
    detected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
    # detect lines find contours and draw the result
    cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    for c in cnts:
        cv2.drawContours(img, [c], -1, (36,255,12), 3)
    cv2.imshow('image_' + str(pageNum), img)

此函数获取页码并读取特定页面的预先准备好的JPG。

如何退回 Xs 和 Ys?

【问题讨论】:

    标签: python cv2 pypdf2 pypdf


    【解决方案1】:

    如果只需要积分: 您可以使用以下方法提取它:

    第 1 点:c[0][0]cnts[num]c[0][0]

    第 2 点:c[1][0]cnts[num]c[1][0]

    其中 num 是轮廓的索引

    中点 解决方案是:

    (cnts[0][1][0][0]+cnts[0][0][0][0])//2,cnts[0][0][0][1]
    

    由于get的每一行或countour有两个点,你可以用平均公式计算中间点。 例如: x1=10 和 x2=90,则中点为 (10+90)/2

    完整代码如下:

    import cv2
    
    image = cv2.imread('2.png')
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
    
    horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15,1))
    detected_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel,     iterations=2)
    
    cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL,     cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    
    for c in cnts:
        x,y=(c[1][0][0]+c[0][0][0])//2,c[0][0][1]
        print(f'The middle point is: x: {x}, y: {y}')
        cv2.drawContours(image, [c], -1, (36,255,12), 3)
        cv2.circle(image, (x,y), radius=5, color=(0, 0, 255), thickness=-1)
    
    cv2.imshow('thresh', thresh)
    cv2.imshow('detected_lines', detected_lines)
    cv2.imshow('image', image)
    cv2.waitKey()
    

    结果图像如下:

    【讨论】:

    • 谢谢! Howeer,现在我有一个不同的问题。查找水平线的目的是获取 Xs 和 Ys 并通过 PyPDF2 库操作 PDF 文件。但是如果我在带有 PyPDF 的 PDF 上使用它们,我从 CV2 获得的 Xs 和 Ys 与位置不匹配......有什么想法吗?
    • openCV 得到的 X 和 Y 不匹配哪个?你在找什么积分?
    • 我正在使用 x,y 使用 PyPDF2 在 PDF(图像来源)上添加文本。但是我得到的位置是错误的
    • 你可以使用它,如果你想把文本放在行的上方,你可以在 y 坐标上增加 10 或 15 个像素。然后将文本放入(x,y-15)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 2021-05-31
    相关资源
    最近更新 更多