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. python3基础05(有关日期的使用1)

    #!/usr/bin/env python# -*- coding:utf-8 -*- import timefrom datetime import datetime,timedelta,timez ...

  2. python 学习实例(cmdMD链接)

    实例1:大学网络排名爬取 https://www.zybuluo.com/myles/note/714347

  3. HDU 1305 Immediate Decodability 可直接解码吗?

    题意:一个码如果是另一个码的前缀,则 is not immediately decodable,不可直接解码,也就是给一串二进制数字给你,你不能对其解码,因解码出来可能有多种情况. 思路:将每个码按长 ...

  4. HDU2612 BFS

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2612 , 一道比较简单的广搜(BFS)题目. 算法: 设置两个dist[][]数组,记录Y和M到几个K ...

  5. StringBuffer是可变的还是不可变的?

    前言:我们知道String类的修饰符是final,其char[] value也是由final修饰的,每次给String变量赋一个新值,都会创建一个新的String对象,很多有涉及到字符串本身的改变都是 ...

  6. POJ 3734 Blocks (线性递推)

    定义ai表示红色和绿色方块中方块数为偶数的颜色有i个,i = 0,1,2. aij表示刷到第j个方块时的方案数,这是一个线性递推关系. 可以构造递推矩阵A,用矩阵快速幂求解. /*********** ...

  7. Android(java)学习笔记101:Java程序入口和Android的APK入口

    1. Java程序的入口:static main()方法 public class welcome extends Activity { @Override public void onCreate( ...

  8. cf1151 B

    题目连接 : https://codeforces.com/contest/1151/problem/B 可能我想法有问题,我怎么感觉B题的思路不直接想出来的,我想了一会才想出来,感觉不难,但可能有更 ...

  9. javaweb基础(27)_jsp标签库实例

    一.开发标签库 1.1.开发防盗链标签 1.编写标签处理器类:RefererTag.java 1 package me.gacl.web.simpletag; 2 3 import java.io.I ...

  10. jQuery Pagination分页插件--刷新

    源码地址:https://github.com/SeaLee02/FunctionModule/blob/master/UploadFiles/WebDemo/FenYE/FenYeDemo.aspx ...