0% found this document useful (0 votes)
6 views6 pages

Ocr

The document is a C# code implementation for an OCR application using AForge and OpenCvSharp libraries. It initializes a video capture device and processes frames to extract text using Tesseract OCR, with features for camera control and image preprocessing. The application handles various exceptions and updates the user interface with status and results of the OCR process.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views6 pages

Ocr

The document is a C# code implementation for an OCR application using AForge and OpenCvSharp libraries. It initializes a video capture device and processes frames to extract text using Tesseract OCR, with features for camera control and image preprocessing. The application handles various exceptions and updates the user interface with status and results of the OCR process.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

using AForge.

Video;
using AForge.Video.DirectShow;
using OpenCvSharp;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using Tesseract;

namespace iVCamOCR
{
public partial class Form1 : Form
{
private VideoCaptureDevice videoSource;
private TesseractEngine ocrEngine;
private DateTime lastOcrTime = DateTime.MinValue;
private readonly TimeSpan ocrInterval = TimeSpan.FromMilliseconds(300);
private bool isProcessingOCR = false;
private readonly object lockObject = new object();
private int frameCount = 0;

public Form1()
{
InitializeComponent();
InitializeOCRAndCamera();
}

private void InitializeOCRAndCamera()


{
try
{
ocrEngine = new TesseractEngine(@"./tessdata", "eng",
EngineMode.Default);
if (ocrEngine == null)
{
MessageBox.Show("Không thể khởi tạo Tesseract. Kiểm tra file
tessdata.", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
catch (Exception ex)
{
MessageBox.Show($"Lỗi khởi tạo OCR: {ex.Message}", "Lỗi",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}

try
{
var videoDevices = new
FilterInfoCollection(FilterCategory.VideoInputDevice);
if (videoDevices.Count == 0)
{
MessageBox.Show("Không tìm thấy thiết bị camera. Kiểm tra iVCam
hoặc camera laptop.", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
btnStart.Enabled = false;
return;
}
videoSource = new
VideoCaptureDevice(videoDevices[0].MonikerString);
if (videoSource.VideoCapabilities.Length > 0)
{
videoSource.VideoResolution =
videoSource.VideoCapabilities[videoSource.VideoCapabilities.Length - 1];
}
videoSource.NewFrame += Video_NewFrame;
btnStop.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show($"Lỗi khởi tạo camera: {ex.Message}", "Lỗi",
MessageBoxButtons.OK, MessageBoxIcon.Error);
btnStart.Enabled = false;
}
}

private void Video_NewFrame(object sender, NewFrameEventArgs eventArgs)


{
try
{
frameCount++;
if (frameCount % 100 == 0)
{
UpdateStatus($"Khung hình xử lý: {frameCount}");
}

Bitmap frame = (Bitmap)eventArgs.Frame.Clone();


if (pictureBoxCamera.InvokeRequired)
{
pictureBoxCamera.Invoke(new Action(() =>
{
lock (lockObject)
{
pictureBoxCamera.Image?.Dispose();
pictureBoxCamera.Image = new Bitmap(frame);
}
}));
}
else
{
lock (lockObject)
{
pictureBoxCamera.Image?.Dispose();
pictureBoxCamera.Image = new Bitmap(frame);
}
}
frame.Dispose();

if (!isProcessingOCR && (DateTime.Now - lastOcrTime) >=


ocrInterval)
{
isProcessingOCR = true;
Bitmap ocrFrame = (Bitmap)eventArgs.Frame.Clone();
ThreadPool.QueueUserWorkItem(state => PerformOCR(ocrFrame));
}
}
catch (Exception ex)
{
UpdateResult($"Lỗi video: {ex.Message}");
}
}

private void PerformOCR(Bitmap frame)


{
try
{
using (Bitmap processedFrame = PreprocessImage(frame))
{
using (var page = ocrEngine.Process(processedFrame,
PageSegMode.AutoOsd))
{
string text = page.GetText().Trim();
if (!string.IsNullOrEmpty(text))
{
UpdateResult(text);
}
else
{
UpdateResult("Không tìm thấy văn bản.");
}
}
}
lastOcrTime = DateTime.Now;
}
catch (Exception ex)
{
UpdateResult($"Lỗi OCR: {ex.Message}");
}
finally
{
if (frame != null) frame.Dispose();
isProcessingOCR = false;
}
}

private Bitmap PreprocessImage(Bitmap bitmap)


{
using (var mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap))
{
// Resize với chuyển đổi Size
var resizedMat = new Mat();
Cv2.Resize(mat, resizedMat, new OpenCvSharp.Size(640, 480));

// Chuyển sang thang xám


var grayMat = new Mat();
Cv2.CvtColor(resizedMat, grayMat, ColorConversionCodes.BGR2GRAY);

// Tăng độ tương phản


var contrastMat = new Mat();
Cv2.ConvertScaleAbs(grayMat, contrastMat, alpha: 1.5, beta: 0);

// Phát hiện biên


var edges = new Mat();
Cv2.Canny(contrastMat, edges, 50, 150);

// Tìm contours
OpenCvSharp.Point[][] contoursArray;
OpenCvSharp.HierarchyIndex[] hierarchy; // Thay Mat bằng
HierarchyIndex[]
Cv2.FindContours(edges, out contoursArray, out hierarchy,
RetrievalModes.List, ContourApproximationModes.ApproxSimple);

// Chuyển đổi OpenCvSharp.Point[][] sang System.Drawing.Point[][]


var contours = contoursArray.Select(c => c.Select(p => new
System.Drawing.Point(p.X, p.Y)).ToArray()).ToArray();

OpenCvSharp.Rect? largestRect = null;


double maxArea = 0;
foreach (var contour in contoursArray)
{
var rect = Cv2.BoundingRect(contour);
double area = rect.Width * rect.Height;
if (area > maxArea && area > 2000 && rect.Width > 10 &&
rect.Height > 10)
{
maxArea = area;
largestRect = rect;
}
}

if (largestRect.HasValue)
{
var roiMat = new Mat(contrastMat, largestRect.Value);
var threshMat = new Mat();
Cv2.Threshold(roiMat, threshMat, 0, 255, ThresholdTypes.Binary
| ThresholdTypes.Otsu);
var kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new
OpenCvSharp.Size(3, 3));
Cv2.MorphologyEx(threshMat, threshMat, MorphTypes.Open,
kernel);
return
OpenCvSharp.Extensions.BitmapConverter.ToBitmap(threshMat);
}
return
OpenCvSharp.Extensions.BitmapConverter.ToBitmap(contrastMat);
}
}

private void UpdateResult(string text)


{
if (textBoxOCRResult.InvokeRequired)
{
textBoxOCRResult.Invoke(new Action(() =>
{
textBoxOCRResult.Text = text;
textBoxOCRResult.SelectionStart = textBoxOCRResult.Text.Length;
textBoxOCRResult.ScrollToCaret();
}));
}
else
{
textBoxOCRResult.Text = text;
textBoxOCRResult.SelectionStart = textBoxOCRResult.Text.Length;
textBoxOCRResult.ScrollToCaret();
}
}

private void UpdateStatus(string status)


{
if (lblStatus.InvokeRequired)
{
lblStatus.Invoke(new Action(() => lblStatus.Text = status));
}
else
{
lblStatus.Text = status;
}
}

private void btnStart_Click(object sender, EventArgs e)


{
if (videoSource != null && !videoSource.IsRunning)
{
try
{
videoSource.Start();
btnStart.Enabled = false;
btnStop.Enabled = true;
UpdateStatus("Camera Đang Chạy");
}
catch (Exception ex)
{
MessageBox.Show($"Lỗi khởi động camera: {ex.Message}", "Lỗi",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

private void btnStop_Click(object sender, EventArgs e)


{
if (videoSource != null && videoSource.IsRunning)
{
try
{
videoSource.SignalToStop();
videoSource.WaitForStop();
lock (lockObject)
{
pictureBoxCamera.Image?.Dispose();
pictureBoxCamera.Image = null;
}
UpdateResult("");
btnStart.Enabled = true;
btnStop.Enabled = false;
UpdateStatus("Camera Đã Dừng");
}
catch (Exception ex)
{
MessageBox.Show($"Lỗi dừng camera: {ex.Message}", "Lỗi",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
if (videoSource != null && videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource.WaitForStop();
}
lock (lockObject)
{
ocrEngine?.Dispose();
pictureBoxCamera.Image?.Dispose();
}
}
catch (Exception ex)
{
MessageBox.Show($"Lỗi khi đóng ứng dụng: {ex.Message}", "Lỗi",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

You might also like