PyOCR_test

  • PyOCR은 Python 용 광학 문자 인식 (OCR) 도구 래퍼입니다. 즉, 파이썬 프로그램에서 다양한 OCR 도구를 사용하는 데 도움이됩니다.

특징

  • jpeg, png, gif, bmp, tiff 등을 포함하여 Pillow 에서 지원하는 모든 이미지 형식을 지원 합니다.
  • 다양한 출력 유형 : 텍스트 만, 경계 상자 등
  • 방향 감지 (Tesseract 및 Litesseract 만 해당)
  • 숫자에만 집중할 수 있습니다 (Tesseract 및 libtesseract 만 해당)
  • 상자를 hOCR 형식으로 저장하고 다시로드 할 수 있습니다
  • PDF 생성 (libtesseract 만 해당)

한계

  • hOCR : 사양의 일부만 지원됩니다. 예를 들어, 페이지와 단락 위치는 저장되지 않습니다.

설치

In [1]:
!pip install pyocr
Requirement already satisfied: pyocr in c:\users\bowlmin\anaconda3\envs\py36\lib\site-packages (0.7.2)
Requirement already satisfied: Pillow in c:\users\bowlmin\anaconda3\envs\py36\lib\site-packages (from pyocr) (5.4.1)

초기화

In [2]:
from PIL import Image
import sys
import pyocr
import pyocr.builders
In [3]:
# 툴 가져오기
tools = pyocr.get_available_tools()
In [4]:
# 툴이 있는지 확인
if len(tools) == 0:
    print("No OCR tool found")
    sys.exit(1)
In [11]:
# 권장되는 순서대로 툴 반환
tool = tools[0]
print("Will use tool '%s'" % (tool.get_name()))
Will use tool 'Tesseract (sh)'
In [12]:
# 사용할 수 있는 언어 출력
langs = tool.get_available_languages()
print("Available languages: %s" % ", ".join(langs))
Available languages: eng, kor, osd
In [14]:
# 한국어 사용
lang = langs[1]
print("Will use lang '%s'" % (lang))
Will use lang 'kor'

텍스트 이미지

  • 인수 'lang'은 선택 사항입니다. 기본값은 사용 된 도구에 따라 다릅니다.
  • 인수 'builder'는 선택 사항입니다. 기본값은 builders.TextBuilder ()입니다.
  • OCR이 실패하면 예외 pyocr.PyocrException가 발생합니다.
  • 입력 이미지에 텍스트가 전혀 없으면 예외가 발생할 수 있습니다 (OCR 도구 동작에 따라 다름).
In [17]:
txt = tool.image_to_string(
    Image.open('hanpage_1.jpg'),
    lang=lang,
    builder=pyocr.builders.TextBuilder()
)
print(txt)
기본사항
지원본부/직무 ㅣ 인턴                         국적      대한민국
성 명                               색티퀴일    1995/06/18
영문성명      100119 1410                       1/1010116      010-9473-9051
『-131|      120141231@0-버키.2011417.00.1                 033)261-0312
주 소    강원도 춘천시 석사동 퇴계주공 아파트 303동 1002호

 

  

 

기간
(/7/"\/0007~\5\77/7/00)
고교 ㅣ|2011/03~2014/02

학교명             저모            성적/만점      졸업여부    소재지

 

 

 

 

 

 

 

 

 

대학         2014/03~
~                                                              /
경력사항
회사명                는우기애                   직위                 담당업무                소재지

(/////0001~///0ㅁ000)

 

 

 

 

 

0표
」요
스
0앞

 

 

 

 

 

 

 

 

 

 

 

 

 

 

군필여부           0       계급             면제사유
0///7/0000~///0000)

군필            2015/07~2017~04     육군               병장
자격사항

자격명                 취득일                  발급처                 등록번호
"14105: 24000552016        2019/05/02                                   44/사1-×\
"105: 『ㅁ0\4600012016 ㅣ 2019/06/03                                   41\7-하24
6 제(  )회 공인회계사 2차 시험 합격 (        년)
외국어능력

외국어명             수준            공인시험명          점수(급수)        점수(급수)쥐득일
영어                                70티16              595            2019/03/23
취업보호대상여부
보훈여부                       보훈번호                       장애여부

근무관련사항

근무시작가능일                     근무형태                       8 비어

2019/07/12            『81ㄴ81176
In [20]:
word_boxes = tool.image_to_string(
    Image.open('hanpage_1.jpg'),
    lang="kor",
    builder=pyocr.builders.WordBoxBuilder()
)
print(word_boxes[0])
  314 769 3893 778
In [22]:
line_and_word_boxes = tool.image_to_string(
    Image.open('hanpage_1.jpg'), lang="kor",
    builder=pyocr.builders.LineBoxBuilder()
)
print(line_and_word_boxes[0])
[
    314 769 3893 778
] 314 769 3893 778
In [23]:
digits = tool.image_to_string(
    Image.open('hanpage_1.jpg'),
    lang=lang,
    builder=pyocr.tesseract.DigitBuilder()
)
print(digits[0])
1

방향 감지

  • 현재 Tesseract 또는 Libtesseract에서만 사용 가능합니다.
  • 각도는도 단위로 표시됩니다 (범위 : [0-360 [)). 가능한 가능한 값은 사용 된 도구에 따라 다릅니다. Tesseract는 각도 = 0, 90, 180, 270 만 반환합니다.
  • 신뢰도는 도구에 의해 임의로 정의 된 점수입니다. 반환되지 않을 수도 있습니다.
  • detect_orientation () 이미지에서 텍스트가 감지되지 않으면 예외가 발생할 수 있습니다.
In [25]:
if tool.can_detect_orientation():
    try:
        orientation = tool.detect_orientation(
            Image.open('hanpage_1.jpg'),
            lang='kor'
        )
    except pyocr.PyocrException as exc:
        print("Orientation detection failed: {}".format(exc))
        #return
    print("Orientation: {}".format(orientation))
Orientation: {'angle': 0, 'confidence': 16.13}

텍스트 파일 쓰기 및 읽기

쓰기:

In [26]:
import codecs
import pyocr
import pyocr.builders
In [27]:
tool = pyocr.get_available_tools()[0]
In [28]:
builder = pyocr.builders.TextBuilder()
In [29]:
txt = tool.image_to_string(
    Image.open('hanpage_1.jpg'),
    lang=lang,
    builder=builder
)
print(txt)
기본사항
지원본부/직무 ㅣ 인턴                         국적      대한민국
성 명                               색티퀴일    1995/06/18
영문성명      100119 1410                       1/1010116      010-9473-9051
『-131|      120141231@0-버키.2011417.00.1                 033)261-0312
주 소    강원도 춘천시 석사동 퇴계주공 아파트 303동 1002호

 

  

 

기간
(/7/"\/0007~\5\77/7/00)
고교 ㅣ|2011/03~2014/02

학교명             저모            성적/만점      졸업여부    소재지

 

 

 

 

 

 

 

 

 

대학         2014/03~
~                                                              /
경력사항
회사명                는우기애                   직위                 담당업무                소재지

(/////0001~///0ㅁ000)

 

 

 

 

 

0표
」요
스
0앞

 

 

 

 

 

 

 

 

 

 

 

 

 

 

군필여부           0       계급             면제사유
0///7/0000~///0000)

군필            2015/07~2017~04     육군               병장
자격사항

자격명                 취득일                  발급처                 등록번호
"14105: 24000552016        2019/05/02                                   44/사1-×\
"105: 『ㅁ0\4600012016 ㅣ 2019/06/03                                   41\7-하24
6 제(  )회 공인회계사 2차 시험 합격 (        년)
외국어능력

외국어명             수준            공인시험명          점수(급수)        점수(급수)쥐득일
영어                                70티16              595            2019/03/23
취업보호대상여부
보훈여부                       보훈번호                       장애여부

근무관련사항

근무시작가능일                     근무형태                       8 비어

2019/07/12            『81ㄴ81176
In [30]:
with codecs.open("hanpage_1.txt", 'w', encoding='utf-8') as file_descriptor:
    builder.write_file(file_descriptor, txt)

읽기:

In [32]:
import codecs
import pyocr.builders
In [33]:
builder = pyocr.builders.TextBuilder()
In [35]:
with codecs.open("hanpage_1.txt", 'r', encoding='utf-8') as file_descriptor:
    txt = builder.read_file(file_descriptor)
print(txt)
기본사항
지원본부/직무 ㅣ 인턴                         국적      대한민국
성 명                               색티퀴일    1995/06/18
영문성명      100119 1410                       1/1010116      010-9473-9051
『-131|      120141231@0-버키.2011417.00.1                 033)261-0312
주 소    강원도 춘천시 석사동 퇴계주공 아파트 303동 1002호

 

  

 

기간
(/7/"\/0007~\5\77/7/00)
고교 ㅣ|2011/03~2014/02

학교명             저모            성적/만점      졸업여부    소재지

 

 

 

 

 

 

 

 

 

대학         2014/03~
~                                                              /
경력사항
회사명                는우기애                   직위                 담당업무                소재지

(/////0001~///0ㅁ000)

 

 

 

 

 

0표
」요
스
0앞

 

 

 

 

 

 

 

 

 

 

 

 

 

 

군필여부           0       계급             면제사유
0///7/0000~///0000)

군필            2015/07~2017~04     육군               병장
자격사항

자격명                 취득일                  발급처                 등록번호
"14105: 24000552016        2019/05/02                                   44/사1-×\
"105: 『ㅁ0\4600012016 ㅣ 2019/06/03                                   41\7-하24
6 제(  )회 공인회계사 2차 시험 합격 (        년)
외국어능력

외국어명             수준            공인시험명          점수(급수)        점수(급수)쥐득일
영어                                70티16              595            2019/03/23
취업보호대상여부
보훈여부                       보훈번호                       장애여부

근무관련사항

근무시작가능일                     근무형태                       8 비어

2019/07/12            『81ㄴ81176

hOCR 파일 작성 및 읽기

쓰기:

In [36]:
import codecs
import pyocr
import pyocr.builders
In [37]:
tool = pyocr.get_available_tools()[0]
In [38]:
builder = pyocr.builders.LineBoxBuilder()
In [39]:
line_boxes = tool.image_to_string(
    Image.open('hanpage_1.jpg'),
    lang=lang,
    builder=builder
)
print(line_boxes[0])
[
    314 769 3893 778
] 314 769 3893 778
In [40]:
with codecs.open("hanpage_1.html", 'w', encoding='utf-8') as file_descriptor:
    builder.write_file(file_descriptor, line_boxes)

읽기:

In [41]:
import codecs
import pyocr.builders
In [42]:
builder = pyocr.builders.LineBoxBuilder()
In [44]:
with codecs.open("hanpage_1.html", 'r', encoding='utf-8') as file_descriptor:
    line_boxes = builder.read_file(file_descriptor)
print(line_boxes[0])
[
    314 769 3893 778
] 314 769 3893 778

영어문서

In [68]:
lang = langs[0]
print("Will use lang '%s'" % (lang))
Will use lang 'eng'

텍스트 이미지

In [70]:
txt = tool.image_to_string(
    Image.open('page_1.jpg'),
    lang=lang,
    builder=pyocr.builders.TextBuilder()
)
print(txt)
Mitcnell O'Hara-Wilc

DATA SCIENTIST
58 Madeleine Rd, Clayton
0+61 408 259421 | SWmail@mitchelloharawild.com | mitchelloharawild | wmitchelloharawild | YW mitchoharawild

Education
Monash University Clayton, Australia
BCom (HONS) IN ECONOMETRICS Mar. 2017 - Nov. 2017

« GPA of 3.875, WAM of 86.625
« Best in class for: Advanced statistical modelling (ETC3580), Bayesian time series econometrics (ETC4541), Applied econometrics 2 (ETC4410),
Advanced topics in computational science (FIT4012), Honours Research Project (ETC4860)

Monash University Clayton, Australia

BCOM IN ECONOMETRICS, BSC IN MATHEMATICAL STATISTICS AND COMPUTATIONAL SCIENCE Mar. 2013 - Nov. 2016

* GPA of 3.688, WAM of 85.385

« Mentored in the Access Monash Ambassador Program (2015 and 2016)

« Participated in the Vice-Chancellor’s Ancora Imparo Student Leadership Program (2014)

« Best in class for: Business analytics (ETC3450), Business forecasting (ETC2450), Algorithms and data structures (FIT2004), Time series analysis
for business and economics (ETC3450)

Experience
iSelect Cheltenham, Australia
DATA MINING (INTERNSHIP) Feb. 2015 - Mar. 2015

« Improved business data and issue reporting with interactive visualisations, and model-based anomaly detection.

Coles Rowville, Australia
FRESH PRODUCE Oct. 2010 - Nov. 2015
« Food preparation & display, first aid, staff training and customer assistance.

Monash University Clayton, Australia
RESEARCH ASSISTANT Jan. 2016 - Present

« Supervisors include Rob Hyndman, Dianne Cook, and George Athanasopoulos.
* Consulting projects with DiabetesLab, Tennis Australia, Monash University and Huawei.
« Contributed to the development of numerous open source R packages.

Google Sydney, Australia
STUDENT AMBASSADOR Feb. 2015 - Nov. 2015
« Supported Google’s presence on campus with events and media.

Monash University Caulfield & Clayton, Australia
TEACHING ASSOCIATE S1 2016 - Present

« Advanced statistical modelling (ETC3580)

« Business forecasting (ETF3231/ETF5231)

« Mathematics for business (ETF2700)

« Data modelling and computing (ETC1010)

Rotaract Monash, Australia

VOLUNTEER Feb. 2013 - Nov. 2016

« Development and maintenance of club website and online services.
« Organising and hosting fundraisers.

NOVEMBER, 2018 MITCHELL O’HARA-WILD + CURRICULUM VITAE 1
In [73]:
word_boxes = tool.image_to_string(
    Image.open('page_1.jpg'),
    lang="eng",
    builder=pyocr.builders.WordBoxBuilder()
)
print(word_boxes[0])
Mitcnell 1097 157 1796 328
In [75]:
line_and_word_boxes = tool.image_to_string(
    Image.open('page_1.jpg'), lang=lang,
    builder=pyocr.builders.LineBoxBuilder()
)
print(line_and_word_boxes[0])
[
  Mitcnell 1097 157 1796 328
  O'Hara-Wilc 1882 157 3005 328
] 1097 157 3005 328
In [76]:
digits = tool.image_to_string(
    Image.open('page_1.jpg'),
    lang=lang,
    builder=pyocr.tesseract.DigitBuilder()
)
print(digits[0])
0

방향 감지

In [78]:
if tool.can_detect_orientation():
    try:
        orientation = tool.detect_orientation(
            Image.open('page_1.jpg'),
            lang=lang
        )
    except pyocr.PyocrException as exc:
        print("Orientation detection failed: {}".format(exc))
        #return
    print("Orientation: {}".format(orientation))
Orientation: {'angle': 0, 'confidence': 15.29}

텍스트 파일 쓰기 및 읽기

쓰기:

In [79]:
tool = pyocr.get_available_tools()[0]
In [80]:
builder = pyocr.builders.TextBuilder()
In [81]:
txt = tool.image_to_string(
    Image.open('page_1.jpg'),
    lang=lang,
    builder=builder
)
print(txt)
Mitcnell O'Hara-Wilc

DATA SCIENTIST
58 Madeleine Rd, Clayton
0+61 408 259421 | SWmail@mitchelloharawild.com | mitchelloharawild | wmitchelloharawild | YW mitchoharawild

Education
Monash University Clayton, Australia
BCom (HONS) IN ECONOMETRICS Mar. 2017 - Nov. 2017

« GPA of 3.875, WAM of 86.625
« Best in class for: Advanced statistical modelling (ETC3580), Bayesian time series econometrics (ETC4541), Applied econometrics 2 (ETC4410),
Advanced topics in computational science (FIT4012), Honours Research Project (ETC4860)

Monash University Clayton, Australia

BCOM IN ECONOMETRICS, BSC IN MATHEMATICAL STATISTICS AND COMPUTATIONAL SCIENCE Mar. 2013 - Nov. 2016

* GPA of 3.688, WAM of 85.385

« Mentored in the Access Monash Ambassador Program (2015 and 2016)

« Participated in the Vice-Chancellor’s Ancora Imparo Student Leadership Program (2014)

« Best in class for: Business analytics (ETC3450), Business forecasting (ETC2450), Algorithms and data structures (FIT2004), Time series analysis
for business and economics (ETC3450)

Experience
iSelect Cheltenham, Australia
DATA MINING (INTERNSHIP) Feb. 2015 - Mar. 2015

« Improved business data and issue reporting with interactive visualisations, and model-based anomaly detection.

Coles Rowville, Australia
FRESH PRODUCE Oct. 2010 - Nov. 2015
« Food preparation & display, first aid, staff training and customer assistance.

Monash University Clayton, Australia
RESEARCH ASSISTANT Jan. 2016 - Present

« Supervisors include Rob Hyndman, Dianne Cook, and George Athanasopoulos.
* Consulting projects with DiabetesLab, Tennis Australia, Monash University and Huawei.
« Contributed to the development of numerous open source R packages.

Google Sydney, Australia
STUDENT AMBASSADOR Feb. 2015 - Nov. 2015
« Supported Google’s presence on campus with events and media.

Monash University Caulfield & Clayton, Australia
TEACHING ASSOCIATE S1 2016 - Present

« Advanced statistical modelling (ETC3580)

« Business forecasting (ETF3231/ETF5231)

« Mathematics for business (ETF2700)

« Data modelling and computing (ETC1010)

Rotaract Monash, Australia

VOLUNTEER Feb. 2013 - Nov. 2016

« Development and maintenance of club website and online services.
« Organising and hosting fundraisers.

NOVEMBER, 2018 MITCHELL O’HARA-WILD + CURRICULUM VITAE 1
In [82]:
with codecs.open("page_1.txt", 'w', encoding='utf-8') as file_descriptor:
    builder.write_file(file_descriptor, txt)

읽기:

In [83]:
builder = pyocr.builders.TextBuilder()
In [84]:
with codecs.open("page_1.txt", 'r', encoding='utf-8') as file_descriptor:
    txt = builder.read_file(file_descriptor)
print(txt)
Mitcnell O'Hara-Wilc

DATA SCIENTIST
58 Madeleine Rd, Clayton
0+61 408 259421 | SWmail@mitchelloharawild.com | mitchelloharawild | wmitchelloharawild | YW mitchoharawild

Education
Monash University Clayton, Australia
BCom (HONS) IN ECONOMETRICS Mar. 2017 - Nov. 2017

« GPA of 3.875, WAM of 86.625
« Best in class for: Advanced statistical modelling (ETC3580), Bayesian time series econometrics (ETC4541), Applied econometrics 2 (ETC4410),
Advanced topics in computational science (FIT4012), Honours Research Project (ETC4860)

Monash University Clayton, Australia

BCOM IN ECONOMETRICS, BSC IN MATHEMATICAL STATISTICS AND COMPUTATIONAL SCIENCE Mar. 2013 - Nov. 2016

* GPA of 3.688, WAM of 85.385

« Mentored in the Access Monash Ambassador Program (2015 and 2016)

« Participated in the Vice-Chancellor’s Ancora Imparo Student Leadership Program (2014)

« Best in class for: Business analytics (ETC3450), Business forecasting (ETC2450), Algorithms and data structures (FIT2004), Time series analysis
for business and economics (ETC3450)

Experience
iSelect Cheltenham, Australia
DATA MINING (INTERNSHIP) Feb. 2015 - Mar. 2015

« Improved business data and issue reporting with interactive visualisations, and model-based anomaly detection.

Coles Rowville, Australia
FRESH PRODUCE Oct. 2010 - Nov. 2015
« Food preparation & display, first aid, staff training and customer assistance.

Monash University Clayton, Australia
RESEARCH ASSISTANT Jan. 2016 - Present

« Supervisors include Rob Hyndman, Dianne Cook, and George Athanasopoulos.
* Consulting projects with DiabetesLab, Tennis Australia, Monash University and Huawei.
« Contributed to the development of numerous open source R packages.

Google Sydney, Australia
STUDENT AMBASSADOR Feb. 2015 - Nov. 2015
« Supported Google’s presence on campus with events and media.

Monash University Caulfield & Clayton, Australia
TEACHING ASSOCIATE S1 2016 - Present

« Advanced statistical modelling (ETC3580)

« Business forecasting (ETF3231/ETF5231)

« Mathematics for business (ETF2700)

« Data modelling and computing (ETC1010)

Rotaract Monash, Australia

VOLUNTEER Feb. 2013 - Nov. 2016

« Development and maintenance of club website and online services.
« Organising and hosting fundraisers.

NOVEMBER, 2018 MITCHELL O’HARA-WILD + CURRICULUM VITAE 1

hOCR 파일 작성 및 읽기

쓰기:

In [85]:
tool = pyocr.get_available_tools()[0]
In [86]:
builder = pyocr.builders.LineBoxBuilder()
In [87]:
line_boxes = tool.image_to_string(
    Image.open('page_1.jpg'),
    lang=lang,
    builder=builder
)
print(line_boxes[0])
[
  Mitcnell 1097 157 1796 328
  O'Hara-Wilc 1882 157 3005 328
] 1097 157 3005 328
In [88]:
with codecs.open("page_1.html", 'w', encoding='utf-8') as file_descriptor:
    builder.write_file(file_descriptor, line_boxes)

읽기:

In [89]:
builder = pyocr.builders.LineBoxBuilder()
In [90]:
with codecs.open("page_1.html", 'r', encoding='utf-8') as file_descriptor:
    line_boxes = builder.read_file(file_descriptor)
print(line_boxes[0])
[
  Mitcnell 1097 157 1796 328
  O'Hara-Wilc 1882 157 3005 328
] 1097 157 3005 328