Detect Vertical&Horizontal Segments By OpenCV,and Save the data to csv.

Steps:

  1. Using adaptiveThreshold to generate thresholded image.
  2. Using threshold to find lines.
  3. Save the data to csv by convert it to json.
 # coding=gbk
import cv2
import numpy as np
import json
import csv
import os def find_lines(threshold, regions=None, direction='horizontal',
line_scale=15, iterations=0):
"""Finds horizontal and vertical lines by applying morphological
transformations on an image. Parameters
----------
threshold : object
numpy.ndarray representing the thresholded image.
regions : list, optional (default: None)
List of page regions that may contain tables of the form x1,y1,x2,y2
where (x1, y1) -> left-top and (x2, y2) -> right-bottom
in image coordinate space.
direction : string, optional (default: 'horizontal')
Specifies whether to find vertical or horizontal lines.
line_scale : int, optional (default: 15)
Factor by which the page dimensions will be divided to get
smallest length of lines that should be detected. The larger this value, smaller the detected lines. Making it
too large will lead to text being detected as lines.
iterations : int, optional (default: 0)
Number of times for erosion/dilation is applied. For more information, refer `OpenCV's dilate <https://docs.opencv.org/2.4/modules/imgproc/doc/filtering.html#dilate>`_. Returns
-------
dmask : object
numpy.ndarray representing pixels where vertical/horizontal
lines lie.
lines : list
List of tuples representing vertical/horizontal lines with
coordinates relative to a left-top origin in
image coordinate space. """
lines = [] if direction == 'vertical':
size = threshold.shape[0] // line_scale
el = cv2.getStructuringElement(cv2.MORPH_RECT, (1, size))
elif direction == 'horizontal':
size = threshold.shape[1] // line_scale
el = cv2.getStructuringElement(cv2.MORPH_RECT, (size, 1))
elif direction is None:
raise ValueError("Specify direction as either 'vertical' or"
" 'horizontal'") if regions is not None:
region_mask = np.zeros(threshold.shape)
for region in regions:
x, y, w, h = region
region_mask[y : y + h, x : x + w] = 1
threshold = np.multiply(threshold, region_mask) threshold = cv2.erode(threshold, el)
threshold = cv2.dilate(threshold, el)
dmask = cv2.dilate(threshold, el, iterations=iterations) try:
_, contours, _ = cv2.findContours(
threshold.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
except ValueError:
# for opencv backward compatibility
contours, _ = cv2.findContours(
threshold.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for c in contours:
x, y, w, h = cv2.boundingRect(c)
x1, x2 = x, x + w
y1, y2 = y, y + h
if direction == 'vertical':
lines.append(((x1 + x2) // 2, y2, (x1 + x2) // 2, y1))
elif direction == 'horizontal':
lines.append((x1, (y1 + y2) // 2, x2, (y1 + y2) // 2)) return dmask, lines def adaptive_threshold(imagename, process_background=False, blocksize=15, c=-2):
"""Thresholds an image using OpenCV's adaptiveThreshold. Parameters
----------
imagename : string
Path to image file.
process_background : bool, optional (default: False)
Whether or not to process lines that are in background.
blocksize : int, optional (default: 15)
Size of a pixel neighborhood that is used to calculate a
threshold value for the pixel: 3, 5, 7, and so on. For more information, refer `OpenCV's adaptiveThreshold <https://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html#adaptivethreshold>`_.
c : int, optional (default: -2)
Constant subtracted from the mean or weighted mean.
Normally, it is positive but may be zero or negative as well. For more information, refer `OpenCV's adaptiveThreshold <https://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html#adaptivethreshold>`_. Returns
-------
img : object
numpy.ndarray representing the original image.
threshold : object
numpy.ndarray representing the thresholded image. """
img = cv2.imread(imagename)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if process_background:
threshold = cv2.adaptiveThreshold(
gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, blocksize, c)
else:
threshold = cv2.adaptiveThreshold(
np.invert(gray), 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, blocksize, c)
return img, threshold count = 0
root = 'E:/VGID_Text/Mycode/linelabel/PDF_JPG/'
rows=[]
for root, dirs, files in os.walk(root):
for img in files:
if img.endswith('jpg'):
img_path = root+'/'+img
image, threshold = adaptive_threshold(img_path)
find_lines(threshold)
vertical_mask, vertical_segments = find_lines(threshold, direction='vertical')
horizontal_mask, horizontal_segments = find_lines(threshold, direction='horizontal')
lines_list = vertical_segments + horizontal_segments
objects = []
lines_dict = {"objects":objects}
for line in lines_list:
point1 = {"x": line[0], "y": line[1]}
point2 = {"x": line[2], "y": line[3]}
ptList = [point1,point2]
polygon = {"ptList":ptList}
line_dict ={"polygon":polygon,
"name": "line",
"type": 4,
"color": "#aa40bf",
"id": "6173cf75-ea09-4ff4-a75e-5cc99a5ea40e",
"cur": 0,
"lineStyle": "solid"
}
objects.append(line_dict)
lines_json = json.dumps(lines_dict)
print(count, lines_json)
row = [img_path, lines_json]
rows.append(row)
count = count + 1
with open('E:/线条标注3k+.csv', 'w', newline='') as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerow(['image_path','lines'])
for row in rows:
csv_writer.writerow(row)

Reference:Camelot:https://camelot-py.readthedocs.io/en/master/

Detect Vertical&Horizontal Segments By OpenCV的更多相关文章

  1. How to Detect and Track Object With OpenCV

    http://www.intorobotics.com/how-to-detect-and-track-object-with-opencv/

  2. OpenCV中GPU函数

    The OpenCV GPU module is a set of classes and functions to utilize GPU computational capabilities. I ...

  3. (中等) POJ 1436 Horizontally Visible Segments , 线段树+区间更新。

    Description There is a number of disjoint vertical line segments in the plane. We say that two segme ...

  4. 【opencv基础】图像翻转cv::flip详解

    前言 在opencv中cv::flip函数用于图像翻转和镜像变换. 具体调用形式 void cv::flip( cv::InputArray src, // 输入图像 cv::OutputArray ...

  5. POJ 1436 Horizontally Visible Segments (线段树&#183;区间染色)

    题意   在坐标系中有n条平行于y轴的线段  当一条线段与还有一条线段之间能够连一条平行与x轴的线不与其他线段相交  就视为它们是可见的  问有多少组三条线段两两相互可见 先把全部线段存下来  并按x ...

  6. OpenCV代码提取:flip函数的实现

    OpenCV中实现图像翻转的函数flip,公式为: 目前fbc_cv库中也实现了flip函数,支持多通道,uchar和float两种数据类型,经测试,与OpenCV3.1结果完全一致. 实现代码fli ...

  7. 【37%】【poj1436】Horizontally Visible Segments

    Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 5200   Accepted: 1903 Description There ...

  8. Opencv学习笔记------Harris角点检测

    image算法测试iteratoralgorithmfeatures 原创文章,转载请注明出处:http://blog.csdn.net/crzy_sparrow/article/details/73 ...

  9. [转载] Conv Nets: A Modular Perspective

    原文地址:http://colah.github.io/posts/2014-07-Conv-Nets-Modular/ Conv Nets: A Modular Perspective Posted ...

随机推荐

  1. iBrand 教程:Xshell 软件安装过程截图及配置

    下载 教程中使用的相关软件下载网盘: https://pan.baidu.com/s/1bqVD5MJ 密码:4lku 安装 请右键以管理员身份运行进行软件安装,安装过程如下: 配置 安装完成并运行软 ...

  2. 【总结】Oracle sql 中的字符(串)替换与转换

    1.REPLACE 语法:REPLACE(char, search_string,replacement_string) 用法:将char中的字符串search_string全部转换为字符串repla ...

  3. UVA Live Archive 4015 Cave (树形dp,分组背包)

    和Heroes Of Might And Magic 相似,题目的询问是dp的一个副产物. 距离是不好表示成状态的,但是可以换一个角度想,如果知道了从一个点向子树走k个结点的最短距离, 那么就可以回答 ...

  4. 【BZOJ2730】[HNOI2012] 矿场搭建(找割点)

    点此看题面 大致题意: 一张无向图,要求你在去掉任意一个节点之后,剩余的每个节点都能到达一个救援出口,问至少需要几个救援出口. 第一步:\(Tarjan\)求割点 首先,我们要跑一遍\(Tarjan\ ...

  5. centos 通用开发工具及库安装 有了它不用愁了

    通用开发工具及库:# yum groupinstall "Development Tools" "Development Libraries"

  6. Bootstrap 警告框(Alert)插件

    警告消息大多来是用来向终端用户提示警告或确认的消息,使用警告框插件,您可以向所有的警告框消息添加取消功能. 用法 您有以下两种方式启用警告框的可取消功能. 1.通过data属性:通过数据添加可取消功能 ...

  7. VS Code 用户自定义代码片段(React)

    VS Code 用户自定义代码片段(React) .jsxReact组件模板:javascriptreact.json { "Import React": { "pref ...

  8. 2018.11.7 Nescafe29 T1 穿越七色虹

    题目 题目背景 在 Nescafe27 和 28 中,讲述了一支探险队前往 Nescafe 之塔探险的故事…… 当两位探险队员以最快的时间把礼物放到每个木箱里之后,精灵们变身为一缕缕金带似的光,簇簇光 ...

  9. Mycat高可用解决方案三(读写分离)

    Mycat高可用解决方案三(读写分离) 一.系统部署规划 名称 IP 主机名称 配置 192.168.199.112 mycat01 2核/2G Mysql主节点 192.168.199.110 my ...

  10. Shell脚本使用汇总整理——文件夹及子文件备份脚本

    Shell脚本使用汇总整理——文件夹及子文件备份脚本 Shell脚本使用的基本知识点汇总详情见连接: https://www.cnblogs.com/lsy-blogs/p/9223477.html ...