You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用OpenCV获取所有垂直白线的坐标列表

获取垂直白线的坐标列表

你可以在现有提取垂直线条的代码基础上,通过轮廓检测提取线条坐标,具体实现如下:

修改后的完整代码

import cv2
import numpy as np
from google.colab.patches import cv2_imshow
from PIL import Image 

document_img = cv2.imread("2.jpg")
table_list = [np.array(document_img, copy=True)]

for each_table in table_list:
    img = cv2.cvtColor(each_table, cv2.COLOR_BGR2GRAY)
    img_height, img_width = img.shape
    thresh, img_bin = cv2.threshold(img, 180, 255, cv2.THRESH_BINARY)
    img_bin_inv = 255 - img_bin
    kernel_len_ver = max(10, img_height // 50)
    ver_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, kernel_len_ver))
    
    # 提取垂直线条
    image_1 = cv2.erode(img_bin_inv, ver_kernel, iterations=3)
    vertical_lines = cv2.dilate(image_1, ver_kernel, iterations=4)
    cv2_imshow(vertical_lines)

    # --- 新增:提取垂直线条坐标 ---
    # 寻找轮廓
    contours, _ = cv2.findContours(vertical_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    vertical_coords = []
    seen_x = set()  # 去重同一位置的线条
    
    for cnt in contours:
        x, y, w, h = cv2.boundingRect(cnt)
        # 过滤窄长的垂直轮廓(参数可根据实际图像调整)
        if w < 5 and h > img_height * 0.5:
            # 记录线条的x坐标及上下端点
            line_info = {
                "x": x,
                "start_point": (x, y),
                "end_point": (x, y + h)
            }
            if x not in seen_x:
                seen_x.add(x)
                vertical_coords.append(line_info)
    
    # 按x坐标排序,让结果更规整
    vertical_coords.sort(key=lambda item: item["x"])
    
    # 输出结果
    print("垂直白线坐标列表:")
    for idx, line in enumerate(vertical_coords):
        print(f"线条{idx+1}: x={line['x']}, 起点{line['start_point']}, 终点{line['end_point']}")

    # 若仅需x坐标列表,可直接生成
    vertical_x_list = [line["x"] for line in vertical_coords]
    print("垂直白线x坐标列表:", vertical_x_list)

关键步骤说明

  • cv2.findContours:从二值化的垂直线条图像中提取最外层轮廓,用CHAIN_APPROX_SIMPLE压缩冗余的轮廓点
  • 过滤条件w <5 and h > img_height*0.5:确保只保留窄且长度足够的垂直线条,可根据图像实际情况调整宽度、高度阈值
  • seen_x集合:避免重复提取同一位置的线条(膨胀操作可能导致同一条线产生多个小轮廓)
  • 按x坐标排序:让最终的坐标列表按从左到右的顺序排列,更符合视觉逻辑

内容的提问来源于stack exchange,提问作者ReaL_HyDRA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 09:27:36