Ocr
Ocr
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();
}
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;
}
}
// 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);
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);
}
}