개발하기
광학 문자 인식 (OCR) 프로그램 만들기
제컴퓨터에서는
2022. 5. 26. 10:49
오늘 업무중 OCR 기술에 대한 개발업무 지시를 듣고 OCR이 무엇인지에 대해 검색을 해보았다.
‘Optimal Character Recognition’ 의 줄임말로 쉽게말해 이미지 속에서 글씨를 인식해서 복사할수있는 텍스트로 변경해주는 아주 편리한 기술이다.
우리의 주변에서의 사례를 들자면 은행어플을 인증할때 신분증 사진을 찍을 때가 있다.
그때 이미지의 글씨들을 인식해서 자동으로 신분증에 대한 정보를 빈칸에 입력해준다.
스캔한 문서라던지, 방대한자료를 빠르게 스캔할수 있다!
이런 경우에 유용하게 사용할 수 있을것같다..
using System;
using System.IO;
using System.Windows.Forms;
using Tesseract;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using OpenCvSharp;
using OpenCvSharp.Extensions;
namespace test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Text = "불러오기";
button2.Text = "분석하기";
}
Bitmap bmp;
public void button1_Click(object sender, EventArgs e)
{
string imgfile = string.Empty;
OpenFileDialog dialog = new OpenFileDialog();
dialog.InitialDirectory = @"C:\DeskTOP\";
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
imgfile = dialog.FileName;
bmp = new Bitmap(imgfile);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = bmp;
//Mat src = new Mat(imgfile);
//Mat dst = src.SubMat(new OpenCvSharp.Rect(1050, 80, 320, 150));
//this.pictureBox2.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(dst);
}
catch
{
MessageBox.Show("이미지를 불러오는데 실패했습니다.");
}
}
}
private void button2_Click(object sender, EventArgs e)
{
Bitmap img = new Bitmap(pictureBox1.Image);
try
{
textBox1.Text = "";
//OCR분석
var ocr = new TesseractEngine(@"./tessdata", "kor", EngineMode.TesseractAndLstm);
var texts = ocr.Process(img);
textBox1.Text = texts.GetText();
//원하는값 추출
/* Regex rx = new Regex(@"(\s\d{3}\s)");
MatchCollection m = rx.Matches(texts.GetText());
if (m.Count==0)
{
MessageBox.Show("매치 결과가 없습니다");
} else {
for (int ctr=0; ctr< m.Count; ctr++) {
textBox2.Text += m[ctr].Value;
}
}*/
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
<결과>
C#으로 작성한 아주 간단한 기능만하는 프로그램은
불러오기 버튼을 통해 이미지를 불러오면, 분석하기 버튼을 통해 결과값 창에 문자인식이 나타나게된다.