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. COGS 2769. mk去撸串

    [题目描述] 今天 mk 去撸串 ,恰逢店里活动 ,如果吃一种串串超过记录, 可以 赠送 328, 所以 mk 想知道他吃的串串中吃的最多的种类是什么. [输入格式] 第一行一个整数 1<=n& ...

  2. NYOJ-198-数数

    原题地址 数数 时间限制:3000 ms  |  内存限制:65535 KB 难度:2   描述 我们平时数数都是喜欢从左向右数的,但是我们的小白同学最近听说德国人数数和我们有些不同,他们正好和我们相 ...

  3. JS获取本地文件并且解析文件内容(XML,TXT)

    $(function(){ $("body").on("change", "#file", function (event) { uploa ...

  4. vuejs属性绑定和双向绑定

    属性绑定 html <div v-bind:title="title">hello world</div> js new Vue({ el:'#root', ...

  5. 启动tomcat的Cannot find ./catalina.sh 的问题

    从终端进入tomcat的bin目录,然后执行startup.sh Cannot find bin/catalina.sh The file is absent or does not have exe ...

  6. java Html&JavaScript面试题:HTML 的 form 提交之前如何验证数值文本框的内容全部为数字? 否则的话提示用户并终止提交?

    提交的验证方法(通过单个字符比较): <!DOCTYPE html> <html> <head> <meta charset="UTF-8" ...

  7. XML格式与实体类的转换

    背景 本人头一回写博客,请大家多多关照.通过读取XML文件获取用户管理权限,其中涉及三部分: 1.XML文件的生成: 2.XML文件的读取: 3.XML文件的保存: 如何做 第一步:自己先将XML文件 ...

  8. python 实现无序列表

    # -*- coding:utf-8 -*- class Node: def __init__(self, initdata): self.data = initdata self.next = No ...

  9. JZOJ 4722. 跳楼机

    Description  DJL为了避免成为一只咸鱼,来找srwudi学习压代码的技巧.Srwudi的家是一幢h层的摩天大楼.由于前来学习的蒟蒻越来越多,srwudi改造了一个跳楼机,使得访客可以更方 ...

  10. makefile学习(1)

    GNU Make / Makefile 学习资料 GNU Make学习总结(一) GNU Make学习总结(二) 这篇学习总结,从一个简单的小例子开始,逐步加深,来讲解Makefile的用法. 最后用 ...