效果
项目
代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpenCvSharp;
using OpenCvSharp.Extensions;
namespace OpenCvSharp_提取文字区域
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Mat mat;
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Image = new Bitmap("test.jpg");
mat = new Mat("test.jpg");
Mat temp = Preprocess("test.jpg");
pictureBox2.Image = FindTextRegion(temp);
}
public Bitmap FindTextRegion(Mat dilation)
{
OpenCvSharp.Point[][] contours;
HierarchyIndex[] hierarchly;
Rect biggestContourRect = new Rect();
Cv2.FindContours(dilation, out contours, out hierarchly, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);
int i = 0;
foreach (OpenCvSharp.Point[] contour in contours)
{
double area = Cv2.ContourArea(contour);
if (area < 1000)
{
continue;
}
double epsilon = 0.001 * Cv2.ArcLength(contour, true);
biggestContourRect = Cv2.BoundingRect(contour);
if (biggestContourRect.Height > (biggestContourRect.Width * 1.2))
{
continue;
}
mat.Rectangle(biggestContourRect, new Scalar(0, 255, 0), 2);
}
return mat.ToBitmap();
}
public Mat Preprocess(string imgPath)
{
Mat dilation2 = new Mat();
using (Mat src = new Mat(imgPath, ImreadModes.Grayscale))
{
Mat sobel = new Mat();
Cv2.Sobel(src, sobel, MatType.CV_8U, 1, 0, 3);
Mat binary = new Mat();
Cv2.Threshold(sobel, binary, 0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
Mat element1 = new Mat();
Mat element2 = new Mat();
OpenCvSharp.Size size1 = new OpenCvSharp.Size(30, 9);
OpenCvSharp.Size size2 = new OpenCvSharp.Size(24, 6);
element1 = Cv2.GetStructuringElement(MorphShapes.Rect, size1);
element2 = Cv2.GetStructuringElement(MorphShapes.Rect, size2);
Mat dilation = new Mat();
Cv2.Dilate(binary, dilation, element2);
Mat erosion = new Mat();
Cv2.Erode(dilation, erosion, element1);
Cv2.Dilate(erosion, dilation2, element2, null, 3);
}
return dilation2;
}
}
}
Demo下载
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?