Compare commits
4
Commits
main
...
feat-dml-ppocr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74583166b6 | ||
|
|
3b7bf83b30 | ||
|
|
bee375484c | ||
|
|
bd8cb74cae |
No files matched your search
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
File renamed without changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
@@ -31,6 +31,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AvalonEdit" Version="6.3.0.90" />
|
||||
<PackageReference Include="clipper_standard" Version="0.0.1" />
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
|
||||
@@ -42,11 +43,6 @@
|
||||
<PackageReference Include="OpenCvSharp4.Windows" Version="4.8.0.20230708" />
|
||||
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.77" />
|
||||
<PackageReference Include="MouseKeyHook" Version="5.7.1" />
|
||||
<PackageReference Include="Sdcb.PaddleInference" Version="2.5.0.1" />
|
||||
<PackageReference Include="Sdcb.PaddleInference.runtime.win64.cuda118_cudnn86_tr85_sm86_89" Version="2.5.1" />
|
||||
<PackageReference Include="Sdcb.PaddleInference.runtime.win64.openblas" Version="2.5.1" />
|
||||
<PackageReference Include="Sdcb.PaddleOCR" Version="2.7.0" />
|
||||
<PackageReference Include="Sdcb.PaddleOCR.Models.Online" Version="2.7.0.1" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.RichTextBox.Wpf" Version="1.1.0" />
|
||||
@@ -55,7 +51,7 @@
|
||||
<PackageReference Include="Vanara.PInvoke.User32" Version="3.4.17" />
|
||||
<PackageReference Include="WPF-UI" Version="3.0.0-preview.7" />
|
||||
<PackageReference Include="WPF-UI.Tray" Version="3.0.0-preview.7" />
|
||||
<PackageReference Include="YoloV8.Gpu" Version="2.0.1" />
|
||||
<PackageReference Include="YoloV8" Version="2.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition=" '$(Configuration)' == 'Debug'">
|
||||
@@ -112,63 +108,9 @@
|
||||
<None Update="Assets\Map\map_sd1024.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\Common\avatar_side_classify_sim.onnx">
|
||||
<None Update="Assets\Model\**">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\Domain\bgi_tree.onnx">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\Domain\bgi_tree.pt">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\Fish\bgi_fish.onnx">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\PaddleOCR\ch_PP-OCRv4_det\inference.pdiparams">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\PaddleOCR\ch_PP-OCRv4_det\inference.pdiparams.info">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\PaddleOCR\ch_PP-OCRv4_det\inference.pdmodel">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\PaddleOCR\ch_PP-OCRv4_rec\inference.pdiparams">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\PaddleOCR\ch_PP-OCRv4_rec\inference.pdiparams.info">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\PaddleOCR\ch_PP-OCRv4_rec\inference.pdmodel">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\PaddleOCR\ch_ppocr_mobile_v2.0_cls\._inference.pdmodel">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\PaddleOCR\ch_ppocr_mobile_v2.0_cls\inference.pdiparams">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\PaddleOCR\ch_ppocr_mobile_v2.0_cls\inference.pdiparams.info">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\PaddleOCR\ch_ppocr_mobile_v2.0_cls\inference.pdmodel">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\PaddleOCR\ppocr_keys_v1.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\PaddleOCR\test_ocr.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\Yap\all_list.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\Yap\index_2_word.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\Yap\model_training.onnx">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFight\Assets\1920x1080\click_any_close_tip.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
@@ -523,16 +465,7 @@
|
||||
<None Update="GameTask\QuickSereniteaPot\Assets\1920x1080\SereniteaPotIcon.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoFight\1.四神挂机[推荐].txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoFight\2.宵宫夜兰班行秋.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoFight\2.宵宫队[请看文件内说明].txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoFight\群友分享\*.txt">
|
||||
<None Update="User\AutoFight\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoGeniusInvokation\1.莫娜砂糖琴.txt">
|
||||
|
||||
@@ -5,7 +5,7 @@ namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
public class Global
|
||||
{
|
||||
public static string Version { get; } = "0.30.2";
|
||||
public static string Version { get; } = "0.30.3";
|
||||
|
||||
public static string StartUpPath { get; set; } = AppContext.BaseDirectory;
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using OpenCvSharp;
|
||||
using Sdcb.PaddleOCR;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
|
||||
@@ -9,5 +8,5 @@ public interface IOcrService
|
||||
|
||||
public string OcrWithoutDetector(Mat mat);
|
||||
|
||||
public PaddleOcrResult OcrResult(Mat mat);
|
||||
public OcrResult OcrResult(Mat mat);
|
||||
}
|
||||
@@ -4,7 +4,6 @@ namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
|
||||
public class OcrFactory
|
||||
{
|
||||
// public static IOcrService Media = Create(OcrEngineTypes.Media);
|
||||
public static IOcrService Paddle { get; } = Create(OcrEngineTypes.Paddle);
|
||||
|
||||
public static IOcrService Create(OcrEngineTypes type)
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
using OpenCvSharp;
|
||||
using System.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
|
||||
// <summary>
|
||||
/// Represents a region detected in an OCR result using Paddle OCR.
|
||||
/// </summary>
|
||||
public record struct OcrResultRegion(RotatedRect Rect, string Text, float Score);
|
||||
|
||||
/// <summary>
|
||||
/// Represents the OCR result of a paddle object detection model.
|
||||
/// </summary>
|
||||
public record OcrResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PaddleOcrResult"/> class with the specified <paramref name="Regions"/>.
|
||||
/// </summary>
|
||||
/// <param name="Regions">An array of <see cref="PaddleOcrResultRegion"/> objects representing the detected text regions.</param>
|
||||
public OcrResult(OcrResultRegion[] Regions)
|
||||
{
|
||||
this.Regions = Regions;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets an array of <see cref="PaddleOcrResultRegion"/> objects representing the detected text regions.
|
||||
/// </summary>
|
||||
/// <value>An array of <see cref="PaddleOcrResultRegion"/> objects representing the detected text regions.</value>
|
||||
public OcrResultRegion[] Regions { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Concatenates the text from each <see cref="PaddleOcrResultRegion"/> object in <see cref="Regions"/>
|
||||
/// and returns the resulting string, ordered by the region's center positions.
|
||||
/// </summary>
|
||||
/// <value>A string containing the concatenated text from each <see cref="PaddleOcrResultRegion"/> object
|
||||
/// in <see cref="Regions"/>, ordered by the region's center positions.</value>
|
||||
public string Text => string.Join("\n", Regions
|
||||
.OrderBy(x => x.Rect.Center.Y)
|
||||
.ThenBy(x => x.Rect.Center.X)
|
||||
.Select(x => x.Text));
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
using BetterGenshinImpact.GameTask.AutoSkip.Model;
|
||||
using BetterGenshinImpact.View.Drawable;
|
||||
using OpenCvSharp;
|
||||
using Sdcb.PaddleOCR;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
@@ -9,11 +8,11 @@ using System.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
|
||||
public static class PaddleOcrResultExtension
|
||||
public static class OcrResultExtension
|
||||
{
|
||||
public static bool RegionHasText(this PaddleOcrResult result, ReadOnlySpan<char> text)
|
||||
public static bool RegionHasText(this OcrResult result, ReadOnlySpan<char> text)
|
||||
{
|
||||
foreach (ref readonly PaddleOcrResultRegion item in result.Regions.AsSpan())
|
||||
foreach (ref readonly OcrResultRegion item in result.Regions.AsSpan())
|
||||
{
|
||||
if (item.Text.AsSpan().Contains(text, StringComparison.InvariantCulture))
|
||||
{
|
||||
@@ -24,9 +23,9 @@ public static class PaddleOcrResultExtension
|
||||
return false;
|
||||
}
|
||||
|
||||
public static PaddleOcrResultRegion FindRegionByText(this PaddleOcrResult result, ReadOnlySpan<char> text)
|
||||
public static OcrResultRegion FindRegionByText(this OcrResult result, ReadOnlySpan<char> text)
|
||||
{
|
||||
foreach (ref readonly PaddleOcrResultRegion item in result.Regions.AsSpan())
|
||||
foreach (ref readonly OcrResultRegion item in result.Regions.AsSpan())
|
||||
{
|
||||
if (item.Text.AsSpan().Contains(text, StringComparison.InvariantCulture))
|
||||
{
|
||||
@@ -37,9 +36,9 @@ public static class PaddleOcrResultExtension
|
||||
return default;
|
||||
}
|
||||
|
||||
public static Rect FindRectByText(this PaddleOcrResult result, string text)
|
||||
public static Rect FindRectByText(this OcrResult result, string text)
|
||||
{
|
||||
foreach (ref PaddleOcrResultRegion item in result.Regions.AsSpan())
|
||||
foreach (ref OcrResultRegion item in result.Regions.AsSpan())
|
||||
{
|
||||
if (item.Text.Contains(text))
|
||||
{
|
||||
@@ -50,17 +49,17 @@ public static class PaddleOcrResultExtension
|
||||
return default;
|
||||
}
|
||||
|
||||
public static List<RectDrawable> ToRectDrawableList(this PaddleOcrResult result, Pen? pen = null)
|
||||
public static List<RectDrawable> ToRectDrawableList(this OcrResult result, Pen? pen = null)
|
||||
{
|
||||
return result.Regions.Select(item => item.Rect.BoundingRect().ToRectDrawable(pen)).ToList();
|
||||
}
|
||||
|
||||
public static List<RectDrawable> ToRectDrawableListOffset(this PaddleOcrResult result, int offsetX, int offsetY, Pen? pen = null)
|
||||
public static List<RectDrawable> ToRectDrawableListOffset(this OcrResult result, int offsetX, int offsetY, Pen? pen = null)
|
||||
{
|
||||
return result.Regions.Select(item => item.Rect.BoundingRect().ToRectDrawable(offsetX, offsetY, pen)).ToList();
|
||||
}
|
||||
|
||||
public static PaddleOcrResultRect ToOcrResultRect(this PaddleOcrResultRegion region)
|
||||
public static PaddleOcrResultRect ToOcrResultRect(this OcrResultRegion region)
|
||||
{
|
||||
return new PaddleOcrResultRect(region.Rect.BoundingRect(), region.Text, region.Score);
|
||||
}
|
||||
|
||||
@@ -1,50 +1,24 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX.OCR.Paddle;
|
||||
using OpenCvSharp;
|
||||
using Sdcb.PaddleInference;
|
||||
using Sdcb.PaddleOCR;
|
||||
using Sdcb.PaddleOCR.Models;
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
|
||||
public class PaddleOcrService : IOcrService
|
||||
{
|
||||
private static readonly object locker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Usage:
|
||||
/// https://github.com/sdcb/PaddleSharp/blob/master/docs/ocr.md
|
||||
/// 模型列表:
|
||||
/// https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.5/doc/doc_ch/models_list.md
|
||||
/// </summary>
|
||||
private readonly PaddleOcrAll _paddleOcrAll;
|
||||
private PaddleOcrEngine _ocrEngine;
|
||||
|
||||
public PaddleOcrService()
|
||||
{
|
||||
var path = Global.Absolute("Assets\\Model\\PaddleOcr");
|
||||
var localDetModel = DetectionModel.FromDirectory(Path.Combine(path, "ch_PP-OCRv4_det"), ModelVersion.V4);
|
||||
var localClsModel = ClassificationModel.FromDirectory(Path.Combine(path, "ch_ppocr_mobile_v2.0_cls"));
|
||||
var localRecModel = RecognizationModel.FromDirectory(Path.Combine(path, "ch_PP-OCRv4_rec"), Path.Combine(path, "ppocr_keys_v1.txt"), ModelVersion.V4);
|
||||
var model = new FullOcrModel(localDetModel, localClsModel, localRecModel);
|
||||
Action<PaddleConfig> device = TaskContext.Instance().Config.InferenceDevice switch
|
||||
{
|
||||
"CPU" => PaddleDevice.Onnx(),
|
||||
"GPU" => PaddleDevice.Onnx(),
|
||||
_ => throw new InvalidEnumArgumentException("无效的推理设备")
|
||||
};
|
||||
_paddleOcrAll = new PaddleOcrAll(model, device)
|
||||
{
|
||||
AllowRotateDetection = false, /* 允许识别有角度的文字 */
|
||||
Enable180Classification = false /* 允许识别旋转角度大于90度的文字 */
|
||||
};
|
||||
|
||||
// System.AccessViolationException
|
||||
// https://github.com/babalae/better-genshin-impact/releases/latest
|
||||
// 下载并解压到相同目录下
|
||||
var detPath = Global.Absolute("Assets\\Model\\PaddleOCR\\V3\\ch_PP-OCRv3_det_infer.onnx");
|
||||
var clsPath = Global.Absolute("Assets\\Model\\PaddleOCR\\V3\\ch_ppocr_mobile_v2.0_cls_infer.onnx");
|
||||
var recPath = Global.Absolute("Assets\\Model\\PaddleOCR\\V3\\ch_PP-OCRv3_rec_infer.onnx");
|
||||
var keysPath = Global.Absolute("Assets\\Model\\PaddleOCR\\V3\\ppocr_keys_v1.txt");
|
||||
_ocrEngine = new PaddleOcrEngine();
|
||||
_ocrEngine.InitModels(detPath, clsPath, recPath, keysPath, Math.Min(4, Environment.ProcessorCount));
|
||||
}
|
||||
|
||||
public string Ocr(Mat mat)
|
||||
@@ -52,25 +26,25 @@ public class PaddleOcrService : IOcrService
|
||||
return OcrResult(mat).Text;
|
||||
}
|
||||
|
||||
public PaddleOcrResult OcrResult(Mat mat)
|
||||
public string OcrWithoutDetector(Mat mat)
|
||||
{
|
||||
lock (locker)
|
||||
{
|
||||
var str = _ocrEngine.OnlyRecognizerRun(mat);
|
||||
Debug.WriteLine($"PaddleOcrWithoutDetector 结果: {str}");
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
public OcrResult OcrResult(Mat mat)
|
||||
{
|
||||
lock (locker)
|
||||
{
|
||||
long startTime = Stopwatch.GetTimestamp();
|
||||
var result = _paddleOcrAll.Run(mat);
|
||||
var result = _ocrEngine.Run(mat).ToBgiOcrResult();
|
||||
TimeSpan time = Stopwatch.GetElapsedTime(startTime);
|
||||
Debug.WriteLine($"PaddleOcr 耗时 {time.TotalMilliseconds}ms 结果: {result.Text}");
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public string OcrWithoutDetector(Mat mat)
|
||||
{
|
||||
lock (locker)
|
||||
{
|
||||
var str = _paddleOcrAll.Recognizer.Run(mat).Text;
|
||||
Debug.WriteLine($"PaddleOcrWithoutDetector 结果: {str}");
|
||||
return str;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// using BetterGenshinImpact.Core.Config;
|
||||
// using OpenCvSharp;
|
||||
// using Sdcb.PaddleInference;
|
||||
// using Sdcb.PaddleOCR;
|
||||
// using Sdcb.PaddleOCR.Models;
|
||||
// using System;
|
||||
// using System.ComponentModel;
|
||||
// using System.Diagnostics;
|
||||
// using System.IO;
|
||||
// using BetterGenshinImpact.GameTask;
|
||||
//
|
||||
// namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
//
|
||||
// public class PaddleOcrService : IOcrService
|
||||
// {
|
||||
// private static readonly object locker = new();
|
||||
//
|
||||
// /// <summary>
|
||||
// /// Usage:
|
||||
// /// https://github.com/sdcb/PaddleSharp/blob/master/docs/ocr.md
|
||||
// /// 模型列表:
|
||||
// /// https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.5/doc/doc_ch/models_list.md
|
||||
// /// </summary>
|
||||
// private readonly PaddleOcrAll _paddleOcrAll;
|
||||
//
|
||||
// public PaddleOcrService()
|
||||
// {
|
||||
// var path = Global.Absolute("Assets\\Model\\PaddleOcr");
|
||||
// var localDetModel = DetectionModel.FromDirectory(Path.Combine(path, "ch_PP-OCRv4_det"), ModelVersion.V4);
|
||||
// var localClsModel = ClassificationModel.FromDirectory(Path.Combine(path, "ch_ppocr_mobile_v2.0_cls"));
|
||||
// var localRecModel = RecognizationModel.FromDirectory(Path.Combine(path, "ch_PP-OCRv4_rec"), Path.Combine(path, "ppocr_keys_v1.txt"), ModelVersion.V4);
|
||||
// var model = new FullOcrModel(localDetModel, localClsModel, localRecModel);
|
||||
// Action<PaddleConfig> device = TaskContext.Instance().Config.InferenceDevice switch
|
||||
// {
|
||||
// "CPU" => PaddleDevice.Onnx(),
|
||||
// "GPU" => PaddleDevice.Onnx(),
|
||||
// _ => throw new InvalidEnumArgumentException("无效的推理设备")
|
||||
// };
|
||||
// _paddleOcrAll = new PaddleOcrAll(model, device)
|
||||
// {
|
||||
// AllowRotateDetection = false, /* 允许识别有角度的文字 */
|
||||
// Enable180Classification = false /* 允许识别旋转角度大于90度的文字 */
|
||||
// };
|
||||
//
|
||||
// // System.AccessViolationException
|
||||
// // https://github.com/babalae/better-genshin-impact/releases/latest
|
||||
// // 下载并解压到相同目录下
|
||||
// }
|
||||
//
|
||||
// public string Ocr(Mat mat)
|
||||
// {
|
||||
// return OcrResult(mat).Text;
|
||||
// }
|
||||
//
|
||||
// public OcrResult OcrResult(Mat mat)
|
||||
// {
|
||||
// lock (locker)
|
||||
// {
|
||||
// long startTime = Stopwatch.GetTimestamp();
|
||||
// var result = _paddleOcrAll.Run(mat);
|
||||
// TimeSpan time = Stopwatch.GetElapsedTime(startTime);
|
||||
// Debug.WriteLine($"PaddleOcr 耗时 {time.TotalMilliseconds}ms 结果: {result.Text}");
|
||||
// return result;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public string OcrWithoutDetector(Mat mat)
|
||||
// {
|
||||
// lock (locker)
|
||||
// {
|
||||
// var str = _paddleOcrAll.Recognizer.Run(mat).Text;
|
||||
// Debug.WriteLine($"PaddleOcrWithoutDetector 结果: {str}");
|
||||
// return str;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
@@ -0,0 +1,168 @@
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using Microsoft.ML.OnnxRuntime.Tensors;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Windows.Forms.VisualStyles;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX.OCR.Paddle;
|
||||
|
||||
class AngleNet
|
||||
{
|
||||
private readonly float[] MeanValues = { 127.5F, 127.5F, 127.5F };
|
||||
private readonly float[] NormValues = { 1.0F / 127.5F, 1.0F / 127.5F, 1.0F / 127.5F };
|
||||
private const int angleDstWidth = 192;
|
||||
private const int angleDstHeight = 48;
|
||||
private const int angleCols = 2;
|
||||
private InferenceSession angleNet;
|
||||
private List<string> inputNames;
|
||||
|
||||
public AngleNet()
|
||||
{
|
||||
}
|
||||
|
||||
~AngleNet()
|
||||
{
|
||||
angleNet.Dispose();
|
||||
}
|
||||
|
||||
public void InitModel(string path, int numThread)
|
||||
{
|
||||
try
|
||||
{
|
||||
SessionOptions op = BgiSessionOption.Instance.Options;
|
||||
op.GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_EXTENDED;
|
||||
op.InterOpNumThreads = numThread;
|
||||
op.IntraOpNumThreads = numThread;
|
||||
angleNet = new InferenceSession(path, op);
|
||||
inputNames = angleNet.InputMetadata.Keys.ToList();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message + ex.StackTrace);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public List<Angle> GetAngles(List<Mat> partImgs, bool doAngle, bool mostAngle)
|
||||
{
|
||||
List<Angle> angles = new List<Angle>();
|
||||
if (doAngle)
|
||||
{
|
||||
for (int i = 0; i < partImgs.Count; i++)
|
||||
{
|
||||
var startTicks = DateTime.Now.Ticks;
|
||||
var angle = GetAngle(partImgs[i]);
|
||||
var endTicks = DateTime.Now.Ticks;
|
||||
var angleTime = (endTicks - startTicks) / 10000F;
|
||||
angle.Time = angleTime;
|
||||
angles.Add(angle);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = 0; i < partImgs.Count; i++)
|
||||
{
|
||||
var angle = new Angle();
|
||||
angle.Index = -1;
|
||||
angle.Score = 0F;
|
||||
angles.Add(angle);
|
||||
}
|
||||
}
|
||||
//Most Possible AngleIndex
|
||||
if (doAngle && mostAngle)
|
||||
{
|
||||
List<int> angleIndexes = new List<int>();
|
||||
angles.ForEach(x => angleIndexes.Add(x.Index));
|
||||
|
||||
double sum = angleIndexes.Sum();
|
||||
double halfPercent = angles.Count / 2.0f;
|
||||
int mostAngleIndex;
|
||||
if (sum < halfPercent)
|
||||
{//all angle set to 0
|
||||
mostAngleIndex = 0;
|
||||
}
|
||||
else
|
||||
{//all angle set to 1
|
||||
mostAngleIndex = 1;
|
||||
}
|
||||
Console.WriteLine($"Set All Angle to mostAngleIndex({mostAngleIndex})");
|
||||
for (int i = 0; i < angles.Count; ++i)
|
||||
{
|
||||
Angle angle = angles[i];
|
||||
angle.Index = mostAngleIndex;
|
||||
angles[i] = angle;
|
||||
}
|
||||
}
|
||||
return angles;
|
||||
}
|
||||
|
||||
private Angle GetAngle(Mat src)
|
||||
{
|
||||
Angle angle = new Angle();
|
||||
Mat angleImg = new Mat();
|
||||
Cv2.Resize(src, angleImg, new Size(angleDstWidth, angleDstHeight));
|
||||
Tensor<float> inputTensors = OcrUtils.SubstractMeanNormalize(angleImg, MeanValues, NormValues);
|
||||
var inputs = new List<NamedOnnxValue>
|
||||
{
|
||||
NamedOnnxValue.CreateFromTensor(inputNames[0], inputTensors)
|
||||
};
|
||||
try
|
||||
{
|
||||
using (IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = angleNet.Run(inputs))
|
||||
{
|
||||
var resultsArray = results.ToArray();
|
||||
Console.WriteLine(resultsArray);
|
||||
float[] outputData = resultsArray[0].AsEnumerable<float>().ToArray();
|
||||
return ScoreToAngle(outputData, angleCols);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex.Message + ex.StackTrace);
|
||||
//throw ex;
|
||||
}
|
||||
return angle;
|
||||
}
|
||||
|
||||
private Angle ScoreToAngle(float[] srcData, int angleCols)
|
||||
{
|
||||
Angle angle = new Angle();
|
||||
int angleIndex = 0;
|
||||
float maxValue = -1000.0F;
|
||||
for (int i = 0; i < angleCols; i++)
|
||||
{
|
||||
if (i == 0) maxValue = srcData[i];
|
||||
else if (srcData[i] > maxValue)
|
||||
{
|
||||
angleIndex = i;
|
||||
maxValue = srcData[i];
|
||||
}
|
||||
}
|
||||
angle.Index = angleIndex;
|
||||
angle.Score = maxValue;
|
||||
return angle;
|
||||
}
|
||||
|
||||
private Mat AdjustTargetImg(Mat src, int dstWidth, int dstHeight)
|
||||
{
|
||||
Mat srcResize = new Mat();
|
||||
float scale = (float)dstHeight / (float)src.Rows;
|
||||
int angleWidth = (int)((float)src.Cols * scale);
|
||||
Cv2.Resize(src, srcResize, new Size(angleWidth, dstHeight));
|
||||
Mat srcFit = new Mat(dstHeight, dstWidth, MatType.CV_8UC3);
|
||||
//srcFit.SetTo(new MCvScalar(255,255,255));
|
||||
if (angleWidth < dstWidth)
|
||||
{
|
||||
Cv2.CopyMakeBorder(srcResize, srcFit, 0, 0, 0, dstWidth - angleWidth, BorderTypes.Isolated, new Scalar(255, 255, 255));
|
||||
}
|
||||
else
|
||||
{
|
||||
var rect = new Rect(0, 0, dstWidth, dstHeight);
|
||||
Mat partAngle = new Mat(srcResize, rect);
|
||||
partAngle.CopyTo(srcFit);
|
||||
}
|
||||
return srcFit;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using Microsoft.ML.OnnxRuntime.Tensors;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX.OCR.Paddle;
|
||||
|
||||
class CrnnNet
|
||||
{
|
||||
private readonly float[] MeanValues = { 127.5F, 127.5F, 127.5F };
|
||||
private readonly float[] NormValues = { 1.0F / 127.5F, 1.0F / 127.5F, 1.0F / 127.5F };
|
||||
private const int crnnDstHeight = 48;
|
||||
private const int crnnCols = 6625;
|
||||
|
||||
private InferenceSession crnnNet;
|
||||
private List<string> keys;
|
||||
private List<string> inputNames;
|
||||
|
||||
public CrnnNet()
|
||||
{
|
||||
}
|
||||
|
||||
~CrnnNet()
|
||||
{
|
||||
crnnNet.Dispose();
|
||||
}
|
||||
|
||||
public void InitModel(string path, string keysPath, int numThread)
|
||||
{
|
||||
try
|
||||
{
|
||||
SessionOptions op = BgiSessionOption.Instance.Options;
|
||||
op.GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_EXTENDED;
|
||||
op.InterOpNumThreads = numThread;
|
||||
op.IntraOpNumThreads = numThread;
|
||||
crnnNet = new InferenceSession(path, op);
|
||||
inputNames = crnnNet.InputMetadata.Keys.ToList();
|
||||
keys = InitKeys(keysPath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(ex.Message + ex.StackTrace);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
private List<string> InitKeys(string path)
|
||||
{
|
||||
StreamReader sr = new StreamReader(path, Encoding.UTF8);
|
||||
List<string> keys = new List<string>();
|
||||
keys.Add("#");
|
||||
String line;
|
||||
while ((line = sr.ReadLine()) != null)
|
||||
{
|
||||
//Debug.WriteLine(line.ToString());
|
||||
keys.Add(line);
|
||||
}
|
||||
keys.Add(" ");
|
||||
Debug.WriteLine($"keys Size = {keys.Count}");
|
||||
return keys;
|
||||
}
|
||||
|
||||
public List<TextLine> GetTextLines(List<Mat> partImgs)
|
||||
{
|
||||
List<TextLine> textLines = new List<TextLine>();
|
||||
for (int i = 0; i < partImgs.Count; i++)
|
||||
{
|
||||
var startTicks = DateTime.Now.Ticks;
|
||||
var textLine = GetTextLine(partImgs[i]);
|
||||
var endTicks = DateTime.Now.Ticks;
|
||||
var crnnTime = (endTicks - startTicks) / 10000F;
|
||||
textLine.Time = crnnTime;
|
||||
textLines.Add(textLine);
|
||||
}
|
||||
return textLines;
|
||||
}
|
||||
|
||||
public TextLine GetTextLine(Mat src)
|
||||
{
|
||||
TextLine textLine = new TextLine();
|
||||
|
||||
float scale = (float)crnnDstHeight / (float)src.Rows;
|
||||
int dstWidth = (int)((float)src.Cols * scale);
|
||||
|
||||
Mat srcResize = new Mat();
|
||||
Cv2.Resize(src, srcResize, new Size(dstWidth, crnnDstHeight));
|
||||
Tensor<float> inputTensors = OcrUtils.SubstractMeanNormalize(srcResize, MeanValues, NormValues);
|
||||
var inputs = new List<NamedOnnxValue>
|
||||
{
|
||||
NamedOnnxValue.CreateFromTensor(inputNames[0], inputTensors)
|
||||
};
|
||||
try
|
||||
{
|
||||
using (IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = crnnNet.Run(inputs))
|
||||
{
|
||||
var resultsArray = results.ToArray();
|
||||
var dimensions = resultsArray[0].AsTensor<float>().Dimensions;
|
||||
float[] outputData = resultsArray[0].AsEnumerable<float>().ToArray();
|
||||
|
||||
return ScoreToTextLine(outputData, dimensions[1], dimensions[2]);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(ex.Message + ex.StackTrace);
|
||||
//throw ex;
|
||||
}
|
||||
|
||||
return textLine;
|
||||
}
|
||||
|
||||
private TextLine ScoreToTextLine(float[] srcData, int h, int w)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
TextLine textLine = new TextLine();
|
||||
|
||||
int lastIndex = 0;
|
||||
List<float> scores = new List<float>();
|
||||
|
||||
for (int i = 0; i < h; i++)
|
||||
{
|
||||
int maxIndex = 0;
|
||||
float maxValue = -1000F;
|
||||
for (int j = 0; j < w; j++)
|
||||
{
|
||||
int idx = i * w + j;
|
||||
if (srcData[idx] > maxValue)
|
||||
{
|
||||
maxIndex = j;
|
||||
maxValue = srcData[idx];
|
||||
}
|
||||
}
|
||||
|
||||
if (maxIndex > 0 && maxIndex < keys.Count && (!(i > 0 && maxIndex == lastIndex)))
|
||||
{
|
||||
scores.Add(maxValue);
|
||||
sb.Append(keys[maxIndex]);
|
||||
}
|
||||
lastIndex = maxIndex;
|
||||
}
|
||||
textLine.Text = sb.ToString();
|
||||
textLine.CharScores = scores;
|
||||
return textLine;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
using ClipperLib;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using Microsoft.ML.OnnxRuntime.Tensors;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using Point = OpenCvSharp.Point;
|
||||
using Size = OpenCvSharp.Size;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX.OCR.Paddle;
|
||||
|
||||
class DbNet
|
||||
{
|
||||
private readonly float[] MeanValues = { 0.485F * 255F, 0.456F * 255F, 0.406F * 255F };
|
||||
private readonly float[] NormValues = { 1.0F / 0.229F / 255.0F, 1.0F / 0.224F / 255.0F, 1.0F / 0.225F / 255.0F };
|
||||
|
||||
private InferenceSession dbNet;
|
||||
|
||||
private List<string> inputNames;
|
||||
|
||||
public DbNet()
|
||||
{
|
||||
}
|
||||
|
||||
~DbNet()
|
||||
{
|
||||
dbNet.Dispose();
|
||||
}
|
||||
|
||||
public void InitModel(string path, int numThread)
|
||||
{
|
||||
try
|
||||
{
|
||||
SessionOptions op = BgiSessionOption.Instance.Options;
|
||||
op.GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_EXTENDED;
|
||||
op.InterOpNumThreads = numThread;
|
||||
op.IntraOpNumThreads = numThread;
|
||||
dbNet = new InferenceSession(path, op);
|
||||
inputNames = dbNet.InputMetadata.Keys.ToList();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(ex.Message + ex.StackTrace);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
public List<TextBox> GetTextBoxes(Mat src, ScaleParam scale, float boxScoreThresh, float boxThresh, float unClipRatio)
|
||||
{
|
||||
Mat srcResize = new Mat();
|
||||
Cv2.Resize(src, srcResize, new Size(scale.DstWidth, scale.DstHeight));
|
||||
Tensor<float> inputTensors = OcrUtils.SubstractMeanNormalize(srcResize, MeanValues, NormValues);
|
||||
var inputs = new List<NamedOnnxValue>
|
||||
{
|
||||
NamedOnnxValue.CreateFromTensor(inputNames[0], inputTensors)
|
||||
};
|
||||
try
|
||||
{
|
||||
using (IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = dbNet.Run(inputs))
|
||||
{
|
||||
var resultsArray = results.ToArray();
|
||||
// Debug.WriteLine(resultsArray);
|
||||
var textBoxes = GetTextBoxes(resultsArray, srcResize.Rows, srcResize.Cols, scale, boxScoreThresh, boxThresh, unClipRatio);
|
||||
return textBoxes;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(ex.Message + ex.StackTrace);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static List<TextBox> GetTextBoxes(DisposableNamedOnnxValue[] outputTensor, int rows, int cols, ScaleParam s, float boxScoreThresh, float boxThresh, float unClipRatio)
|
||||
{
|
||||
float maxSideThresh = 3.0f;//长边门限
|
||||
List<TextBox> rsBoxes = new List<TextBox>();
|
||||
//-----Data preparation-----
|
||||
float[] predData = outputTensor[0].AsEnumerable<float>().ToArray();
|
||||
List<byte> cbufData = new List<byte>();
|
||||
foreach (float data in predData)
|
||||
{
|
||||
var val = data * 255;
|
||||
cbufData.Add(Convert.ToByte(val));
|
||||
}
|
||||
Mat predMat = new Mat(rows, cols, MatType.CV_32FC1, predData);
|
||||
Mat cbufMat = new Mat(rows, cols, MatType.CV_8UC1, cbufData.ToArray());
|
||||
|
||||
//-----boxThresh-----
|
||||
Mat thresholdMat = new Mat();
|
||||
Cv2.Threshold(cbufMat, thresholdMat, boxThresh * 255.0, 255.0, ThresholdTypes.Binary);
|
||||
|
||||
//-----dilate-----
|
||||
Mat dilateMat = new Mat();
|
||||
Mat dilateElement = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(2, 2), new Point(-1, -1));
|
||||
Cv2.Dilate(thresholdMat, dilateMat, dilateElement, new Point(-1, -1), 1, BorderTypes.Default, new Scalar(128, 128, 128));
|
||||
|
||||
Cv2.FindContours(dilateMat, out var contours, out _, RetrievalModes.List, ContourApproximationModes.ApproxSimple);
|
||||
|
||||
for (int i = 0; i < contours.Length; i++)
|
||||
{
|
||||
if (contours[i].Length <= 2)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
float maxSide = 0;
|
||||
List<Point2f> minBox = GetMiniBox(contours[i], out maxSide);
|
||||
if (maxSide < maxSideThresh)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
double score = GetScore(contours[i], predMat);
|
||||
if (score < boxScoreThresh)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
List<Point> clipBox = Unclip(minBox, unClipRatio);
|
||||
if (clipBox == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
List<Point2f> clipMinBox = GetMiniBox(clipBox.ToArray(), out maxSide);
|
||||
if (maxSide < maxSideThresh + 2)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
List<Point> finalPoints = new List<Point>();
|
||||
foreach (var item in clipMinBox)
|
||||
{
|
||||
int x = (int)(item.X / s.ScaleWidth);
|
||||
int ptx = Math.Min(Math.Max(x, 0), s.SrcWidth);
|
||||
|
||||
int y = (int)(item.Y / s.ScaleHeight);
|
||||
int pty = Math.Min(Math.Max(y, 0), s.SrcHeight);
|
||||
Point dstPt = new Point(ptx, pty);
|
||||
finalPoints.Add(dstPt);
|
||||
}
|
||||
|
||||
TextBox textBox = new TextBox();
|
||||
textBox.Score = (float)score;
|
||||
textBox.Points = finalPoints;
|
||||
rsBoxes.Add(textBox);
|
||||
}
|
||||
rsBoxes.Reverse();
|
||||
return rsBoxes;
|
||||
}
|
||||
|
||||
// private static List<Point2f> GetMiniBox(Point[] contours, out float minEdgeSize)
|
||||
// {
|
||||
// VectorOfPoint vop = new VectorOfPoint(contours);
|
||||
// return GetMiniBox(vop, out minEdgeSize);
|
||||
// }
|
||||
|
||||
private static List<Point2f> GetMiniBox(Point[] contours, out float minEdgeSize)
|
||||
{
|
||||
List<Point2f> box = new List<Point2f>();
|
||||
RotatedRect rrect = Cv2.MinAreaRect(contours);
|
||||
Point2f[] points = Cv2.BoxPoints(rrect);
|
||||
minEdgeSize = Math.Min(rrect.Size.Width, rrect.Size.Height);
|
||||
|
||||
List<Point2f> thePoints = new List<Point2f>(points);
|
||||
thePoints.Sort(CompareByX);
|
||||
|
||||
int index_1 = 0, index_2 = 1, index_3 = 2, index_4 = 3;
|
||||
if (thePoints[1].Y > thePoints[0].Y)
|
||||
{
|
||||
index_1 = 0;
|
||||
index_4 = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
index_1 = 1;
|
||||
index_4 = 0;
|
||||
}
|
||||
|
||||
if (thePoints[3].Y > thePoints[2].Y)
|
||||
{
|
||||
index_2 = 2;
|
||||
index_3 = 3;
|
||||
}
|
||||
else
|
||||
{
|
||||
index_2 = 3;
|
||||
index_3 = 2;
|
||||
}
|
||||
|
||||
box.Add(thePoints[index_1]);
|
||||
box.Add(thePoints[index_2]);
|
||||
box.Add(thePoints[index_3]);
|
||||
box.Add(thePoints[index_4]);
|
||||
|
||||
return box;
|
||||
}
|
||||
|
||||
public static int CompareByX(Point2f left, Point2f right)
|
||||
{
|
||||
if (left == null && right == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (left == null)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (right == null)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (left.X > right.X)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (left.X == right.X)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static double GetScore(Point[] contours, Mat fMapMat)
|
||||
{
|
||||
short xmin = 9999;
|
||||
short xmax = 0;
|
||||
short ymin = 9999;
|
||||
short ymax = 0;
|
||||
|
||||
try
|
||||
{
|
||||
foreach (Point point in contours)
|
||||
{
|
||||
if (point.X < xmin)
|
||||
{
|
||||
//var xx = nd[point.X];
|
||||
xmin = (short)point.X;
|
||||
}
|
||||
|
||||
if (point.X > xmax)
|
||||
{
|
||||
xmax = (short)point.X;
|
||||
}
|
||||
|
||||
if (point.Y < ymin)
|
||||
{
|
||||
ymin = (short)point.Y;
|
||||
}
|
||||
|
||||
if (point.Y > ymax)
|
||||
{
|
||||
ymax = (short)point.Y;
|
||||
}
|
||||
}
|
||||
|
||||
int roiWidth = xmax - xmin + 1;
|
||||
int roiHeight = ymax - ymin + 1;
|
||||
|
||||
// Image<Gray, float> bitmap = fMapMat.ToImage<Gray, float>();
|
||||
// Image<Gray, float> roiBitmap = new Image<Gray, float>(roiWidth, roiHeight);
|
||||
// float[,,] dataFloat = bitmap.Data;
|
||||
// float[,,] data = roiBitmap.Data;
|
||||
//
|
||||
// for (int j = ymin; j < ymin + roiHeight; j++)
|
||||
// {
|
||||
// for (int i = xmin; i < xmin + roiWidth; i++)
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// data[j - ymin, i - xmin, 0] = dataFloat[j, i, 0];
|
||||
// }
|
||||
// catch (Exception ex2)
|
||||
// {
|
||||
// Debug.WriteLine(ex2.Message);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
Mat mask = Mat.Zeros(roiHeight, roiWidth, MatType.CV_8UC1);
|
||||
List<Point> pts = new List<Point>();
|
||||
foreach (Point point in contours)
|
||||
{
|
||||
pts.Add(new Point(point.X - xmin, point.Y - ymin));
|
||||
}
|
||||
|
||||
Cv2.FillPoly(mask, new[] { pts }, new Scalar(1));
|
||||
|
||||
return Cv2.Mean(new Mat(fMapMat, new Rect(xmin, ymin, roiWidth, roiHeight)), mask).Val0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(ex.Message + ex.StackTrace);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static List<Point> Unclip(List<Point2f> box, float unclip_ratio)
|
||||
{
|
||||
RotatedRect clipRect = Cv2.MinAreaRect(box.ToArray());
|
||||
if (clipRect.Size.Height < 1.001 && clipRect.Size.Width < 1.001)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
List<IntPoint> theCliperPts = new List<IntPoint>();
|
||||
foreach (Point2f pt in box)
|
||||
{
|
||||
IntPoint a1 = new IntPoint((int)pt.X, (int)pt.Y);
|
||||
theCliperPts.Add(a1);
|
||||
}
|
||||
|
||||
float area = Math.Abs(SignedPolygonArea(box.ToArray<Point2f>()));
|
||||
double length = LengthOfPoints(box);
|
||||
double distance = area * unclip_ratio / length;
|
||||
|
||||
ClipperOffset co = new ClipperOffset();
|
||||
co.AddPath(theCliperPts, JoinType.jtRound, EndType.etClosedPolygon);
|
||||
List<List<IntPoint>> solution = new List<List<IntPoint>>();
|
||||
co.Execute(ref solution, distance);
|
||||
if (solution.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
List<Point> retPts = new List<Point>();
|
||||
foreach (IntPoint ip in solution[0])
|
||||
{
|
||||
retPts.Add(new Point((int)ip.X, (int)ip.Y));
|
||||
}
|
||||
|
||||
return retPts;
|
||||
}
|
||||
|
||||
private static float SignedPolygonArea(Point2f[] Points)
|
||||
{
|
||||
// Add the first point to the end.
|
||||
int num_points = Points.Length;
|
||||
Point2f[] pts = new Point2f[num_points + 1];
|
||||
Points.CopyTo(pts, 0);
|
||||
pts[num_points] = Points[0];
|
||||
|
||||
// Get the areas.
|
||||
float area = 0;
|
||||
for (int i = 0; i < num_points; i++)
|
||||
{
|
||||
area +=
|
||||
(pts[i + 1].X - pts[i].X) *
|
||||
(pts[i + 1].Y + pts[i].Y) / 2;
|
||||
}
|
||||
|
||||
return area;
|
||||
}
|
||||
|
||||
private static double LengthOfPoints(List<Point2f> box)
|
||||
{
|
||||
double length = 0;
|
||||
|
||||
Point2f pt = box[0];
|
||||
double x0 = pt.X;
|
||||
double y0 = pt.Y;
|
||||
double x1 = 0, y1 = 0, dx = 0, dy = 0;
|
||||
box.Add(pt);
|
||||
|
||||
int count = box.Count;
|
||||
for (int idx = 1; idx < count; idx++)
|
||||
{
|
||||
Point2f pts = box[idx];
|
||||
x1 = pts.X;
|
||||
y1 = pts.Y;
|
||||
dx = x1 - x0;
|
||||
dy = y1 - y0;
|
||||
|
||||
length += Math.Sqrt(dx * dx + dy * dy);
|
||||
|
||||
x0 = x1;
|
||||
y0 = y1;
|
||||
}
|
||||
|
||||
box.RemoveAt(count - 1);
|
||||
return length;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX.OCR.Paddle;
|
||||
|
||||
public sealed class TextBox
|
||||
{
|
||||
public List<Point> Points { get; set; }
|
||||
public float Score { get; set; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"TextBox[score({Score}),[x: {Points[0].X}, y: {Points[0].Y}], [x: {Points[1].X}, y: {Points[1].Y}], [x: {Points[2].X}, y: {Points[2].Y}], [x: {Points[3].X}, y: {Points[3].Y}]]";
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class Angle
|
||||
{
|
||||
public int Index { get; set; }
|
||||
public float Score { get; set; }
|
||||
public float Time { get; set; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
string header = Index >= 0 ? "Angle" : "AngleDisabled";
|
||||
return $"{header}[Index({Index}), Score({Score}), Time({Time}ms)]";
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class TextLine
|
||||
{
|
||||
public string Text { get; set; }
|
||||
public List<float> CharScores { get; set; }
|
||||
public float Time { get; set; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
CharScores.ForEach(x => sb.Append($"{x},"));
|
||||
return $"TextLine[Text({Text}),CharScores({sb.ToString()}),Time({Time}ms)]";
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class TextBlock
|
||||
{
|
||||
public List<Point> BoxPoints { get; set; }
|
||||
public float BoxScore { get; set; }
|
||||
public int AngleIndex { get; set; }
|
||||
public float AngleScore { get; set; }
|
||||
public float AngleTime { get; set; }
|
||||
public string Text { get; set; }
|
||||
public List<float> CharScores { get; set; }
|
||||
public float CrnnTime { get; set; }
|
||||
public float BlockTime { get; set; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.AppendLine("├─TextBlock");
|
||||
string textBox = $"│ ├──TextBox[score({BoxScore}),[x: {BoxPoints[0].X}, y: {BoxPoints[0].Y}], [x: {BoxPoints[1].X}, y: {BoxPoints[1].Y}], [x: {BoxPoints[2].X}, y: {BoxPoints[2].Y}], [x: {BoxPoints[3].X}, y: {BoxPoints[3].Y}]]";
|
||||
sb.AppendLine(textBox);
|
||||
string header = AngleIndex >= 0 ? "Angle" : "AngleDisabled";
|
||||
string angle = $"│ ├──{header}[Index({AngleIndex}), Score({AngleScore}), Time({AngleTime}ms)]";
|
||||
sb.AppendLine(angle);
|
||||
StringBuilder sbScores = new StringBuilder();
|
||||
CharScores.ForEach(x => sbScores.Append($"{x},"));
|
||||
string textLine = $"│ ├──TextLine[Text({Text}),CharScores({sbScores.ToString()}),Time({CrnnTime}ms)]";
|
||||
sb.AppendLine(textLine);
|
||||
sb.AppendLine($"│ └──BlockTime({BlockTime}ms)");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class RapidOcrResult
|
||||
{
|
||||
public List<TextBlock> TextBlocks { get; set; }
|
||||
public float DbNetTime { get; set; }
|
||||
|
||||
// public Mat BoxImg { get; set; }
|
||||
public float DetectTime { get; set; }
|
||||
|
||||
public string StrRes { get; set; }
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.AppendLine("OcrResult");
|
||||
TextBlocks.ForEach(x => sb.Append(x));
|
||||
sb.AppendLine($"├─DbNetTime({DbNetTime}ms)");
|
||||
sb.AppendLine($"├─DetectTime({DetectTime}ms)");
|
||||
sb.AppendLine($"└─StrRes({StrRes})");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public OcrResult ToBgiOcrResult()
|
||||
{
|
||||
List<OcrResultRegion> regions = [];
|
||||
foreach (var block in TextBlocks)
|
||||
{
|
||||
var rotatedRect = Cv2.MinAreaRect(block.BoxPoints);
|
||||
regions.Add(new OcrResultRegion(rotatedRect, block.Text, block.BoxScore));
|
||||
}
|
||||
return new OcrResult([.. regions]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
using Microsoft.ML.OnnxRuntime.Tensors;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX.OCR.Paddle;
|
||||
|
||||
class OcrUtils
|
||||
{
|
||||
public static Tensor<float> SubstractMeanNormalize(Mat src, float[] meanVals, float[] normVals)
|
||||
{
|
||||
return ToTensorUnsafe(src, meanVals, normVals);
|
||||
}
|
||||
|
||||
public static Tensor<float> ToTensorUnsafe(Mat src, float[] meanVals, float[] normVals)
|
||||
{
|
||||
var channels = src.Channels();
|
||||
var rows = src.Rows;
|
||||
var cols = src.Cols;
|
||||
|
||||
Tensor<float> inputTensor = new DenseTensor<float>([1, channels, rows, cols]);
|
||||
|
||||
unsafe
|
||||
{
|
||||
var b = (byte*)src.Ptr(0).ToPointer();
|
||||
for (int r = 0; r < rows; r++)
|
||||
{
|
||||
for (int c = 0; c < cols; c++)
|
||||
{
|
||||
for (int ch = 0; ch < channels; ch++)
|
||||
{
|
||||
var value = b[(r * cols + c) * channels + ch];
|
||||
var data = value * normVals[ch] - meanVals[ch] * normVals[ch];
|
||||
inputTensor[0, ch, r, c] = data;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return inputTensor;
|
||||
}
|
||||
|
||||
public static Mat MakePadding(Mat src, int padding)
|
||||
{
|
||||
if (padding <= 0) return src;
|
||||
Scalar paddingScalar = new Scalar(255, 255, 255);
|
||||
Mat paddingSrc = new Mat();
|
||||
Cv2.CopyMakeBorder(src, paddingSrc, padding, padding, padding, padding, BorderTypes.Isolated, paddingScalar);
|
||||
return paddingSrc;
|
||||
}
|
||||
|
||||
public static int GetThickness(Mat boxImg)
|
||||
{
|
||||
int minSize = boxImg.Cols > boxImg.Rows ? boxImg.Rows : boxImg.Cols;
|
||||
int thickness = minSize / 1000 + 2;
|
||||
return thickness;
|
||||
}
|
||||
|
||||
public static void DrawTextBox(Mat boxImg, List<Point> box, int thickness)
|
||||
{
|
||||
if (box == null || box.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var color = new Scalar(0, 0, 255);//B(0) G(0) R(255)
|
||||
Cv2.Line(boxImg, box[0], box[1], color, thickness);
|
||||
Cv2.Line(boxImg, box[1], box[2], color, thickness);
|
||||
Cv2.Line(boxImg, box[2], box[3], color, thickness);
|
||||
Cv2.Line(boxImg, box[3], box[0], color, thickness);
|
||||
}
|
||||
|
||||
public static void DrawTextBoxes(Mat src, List<TextBox> textBoxes, int thickness)
|
||||
{
|
||||
for (int i = 0; i < textBoxes.Count; i++)
|
||||
{
|
||||
TextBox t = textBoxes[i];
|
||||
DrawTextBox(src, t.Points, thickness);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Mat> GetPartImages(Mat src, List<TextBox> textBoxes)
|
||||
{
|
||||
List<Mat> partImages = new List<Mat>();
|
||||
for (int i = 0; i < textBoxes.Count; ++i)
|
||||
{
|
||||
Mat partImg = GetRotateCropImage(src, textBoxes[i].Points);
|
||||
//Mat partImg = new Mat();
|
||||
//GetRoiFromBox(src, partImg, textBoxes[i].Points);
|
||||
partImages.Add(partImg);
|
||||
}
|
||||
return partImages;
|
||||
}
|
||||
|
||||
public static Mat GetRotateCropImage(Mat src, List<Point> box)
|
||||
{
|
||||
List<Point> points = new List<Point>();
|
||||
points.AddRange(box);
|
||||
|
||||
int[] collectX = { box[0].X, box[1].X, box[2].X, box[3].X };
|
||||
int[] collectY = { box[0].Y, box[1].Y, box[2].Y, box[3].Y };
|
||||
int left = collectX.Min();
|
||||
int right = collectX.Max();
|
||||
int top = collectY.Min();
|
||||
int bottom = collectY.Max();
|
||||
|
||||
Rect rect = new Rect(left, top, right - left, bottom - top);
|
||||
Mat imgCrop = new Mat(src, rect);
|
||||
|
||||
for (int i = 0; i < points.Count; i++)
|
||||
{
|
||||
var pt = points[i];
|
||||
pt.X -= left;
|
||||
pt.Y -= top;
|
||||
points[i] = pt;
|
||||
}
|
||||
|
||||
int imgCropWidth = (int)(Math.Sqrt(Math.Pow(points[0].X - points[1].X, 2) +
|
||||
Math.Pow(points[0].Y - points[1].Y, 2)));
|
||||
int imgCropHeight = (int)(Math.Sqrt(Math.Pow(points[0].X - points[3].X, 2) +
|
||||
Math.Pow(points[0].Y - points[3].Y, 2)));
|
||||
|
||||
var ptsDst0 = new Point2f(0, 0);
|
||||
var ptsDst1 = new Point2f(imgCropWidth, 0);
|
||||
var ptsDst2 = new Point2f(imgCropWidth, imgCropHeight);
|
||||
var ptsDst3 = new Point2f(0, imgCropHeight);
|
||||
|
||||
Point2f[] ptsDst = { ptsDst0, ptsDst1, ptsDst2, ptsDst3 };
|
||||
|
||||
var ptsSrc0 = new Point2f(points[0].X, points[0].Y);
|
||||
var ptsSrc1 = new Point2f(points[1].X, points[1].Y);
|
||||
var ptsSrc2 = new Point2f(points[2].X, points[2].Y);
|
||||
var ptsSrc3 = new Point2f(points[3].X, points[3].Y);
|
||||
|
||||
Point2f[] ptsSrc = { ptsSrc0, ptsSrc1, ptsSrc2, ptsSrc3 };
|
||||
|
||||
Mat M = Cv2.GetPerspectiveTransform(ptsSrc, ptsDst);
|
||||
|
||||
Mat partImg = new Mat();
|
||||
Cv2.WarpPerspective(imgCrop, partImg, M,
|
||||
new Size(imgCropWidth, imgCropHeight), InterpolationFlags.Nearest, BorderTypes.Replicate);
|
||||
|
||||
if (partImg.Rows >= partImg.Cols * 1.5)
|
||||
{
|
||||
Mat srcCopy = new Mat();
|
||||
Cv2.Transpose(partImg, srcCopy);
|
||||
Cv2.Flip(srcCopy, srcCopy, 0);
|
||||
return srcCopy;
|
||||
}
|
||||
else
|
||||
{
|
||||
return partImg;
|
||||
}
|
||||
}
|
||||
|
||||
public static Mat MatRotateClockWise180(Mat src)
|
||||
{
|
||||
Cv2.Flip(src, src, FlipMode.Y);
|
||||
Cv2.Flip(src, src, FlipMode.X);
|
||||
return src;
|
||||
}
|
||||
|
||||
public static Mat MatRotateClockWise90(Mat src)
|
||||
{
|
||||
Cv2.Rotate(src, src, RotateFlags.Rotate90Clockwise);
|
||||
return src;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX.OCR.Paddle;
|
||||
|
||||
/// <summary>
|
||||
/// edit from: https://github.com/RapidAI/RapidOCRCSharp
|
||||
/// </summary>
|
||||
public class PaddleOcrEngine
|
||||
{
|
||||
public bool isPartImg { get; set; }
|
||||
public bool isDebugImg { get; set; }
|
||||
private DbNet dbNet;
|
||||
private AngleNet angleNet;
|
||||
private CrnnNet crnnNet;
|
||||
|
||||
public PaddleOcrEngine()
|
||||
{
|
||||
dbNet = new DbNet();
|
||||
angleNet = new AngleNet();
|
||||
crnnNet = new CrnnNet();
|
||||
}
|
||||
|
||||
public void InitModels(string detPath, string clsPath, string recPath, string keysPath, int numThread)
|
||||
{
|
||||
try
|
||||
{
|
||||
dbNet.InitModel(detPath, numThread);
|
||||
angleNet.InitModel(clsPath, numThread);
|
||||
crnnNet.InitModel(recPath, keysPath, numThread);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(ex.Message + ex.StackTrace);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public Mat ToChannel3Mat(Mat mat)
|
||||
{
|
||||
return mat.Channels() switch
|
||||
{
|
||||
4 => mat.CvtColor(ColorConversionCodes.RGBA2BGR),
|
||||
1 => mat.CvtColor(ColorConversionCodes.GRAY2RGB),
|
||||
3 => mat,
|
||||
var x => throw new Exception($"Unexpect src channel: {x}, allow: (1/3/4)")
|
||||
};
|
||||
}
|
||||
|
||||
public RapidOcrResult Run(Mat mat)
|
||||
{
|
||||
using var channel3 = ToChannel3Mat(mat);
|
||||
return Run(channel3, 0, 1024, 0.5f, 0.3f, 1.6f, false, false);
|
||||
}
|
||||
|
||||
public string OnlyRecognizerRun(Mat mat)
|
||||
{
|
||||
using var channel3 = ToChannel3Mat(mat);
|
||||
var textLine = crnnNet.GetTextLine(channel3);
|
||||
return textLine.Text;
|
||||
}
|
||||
|
||||
public RapidOcrResult Run(Mat originSrc, int padding, int maxSideLen, float boxScoreThresh, float boxThresh,
|
||||
float unClipRatio, bool doAngle, bool mostAngle)
|
||||
{
|
||||
int originMaxSide = Math.Max(originSrc.Cols, originSrc.Rows);
|
||||
|
||||
int resize;
|
||||
if (maxSideLen <= 0 || maxSideLen > originMaxSide)
|
||||
{
|
||||
resize = originMaxSide;
|
||||
}
|
||||
else
|
||||
{
|
||||
resize = maxSideLen;
|
||||
}
|
||||
resize += 2 * padding;
|
||||
Rect paddingRect = new Rect(padding, padding, originSrc.Cols, originSrc.Rows);
|
||||
Mat paddingSrc = OcrUtils.MakePadding(originSrc, padding);
|
||||
|
||||
ScaleParam scale = ScaleParam.GetScaleParam(paddingSrc, resize);
|
||||
|
||||
return RunOnce(paddingSrc, paddingRect, scale, boxScoreThresh, boxThresh, unClipRatio, doAngle, mostAngle);
|
||||
}
|
||||
|
||||
private RapidOcrResult RunOnce(Mat src, Rect originRect, ScaleParam scale, float boxScoreThresh, float boxThresh,
|
||||
float unClipRatio, bool doAngle, bool mostAngle)
|
||||
{
|
||||
// Mat textBoxPaddingImg = src.Clone();
|
||||
// int thickness = OcrUtils.GetThickness(src);
|
||||
// Debug.WriteLine("=====Start detect=====");
|
||||
var startTicks = DateTime.Now.Ticks;
|
||||
|
||||
// Debug.WriteLine("---------- step: dbNet getTextBoxes ----------");
|
||||
var textBoxes = dbNet.GetTextBoxes(src, scale, boxScoreThresh, boxThresh, unClipRatio);
|
||||
var dbNetTime = (DateTime.Now.Ticks - startTicks) / 10000F;
|
||||
|
||||
// Debug.WriteLine($"TextBoxesSize({textBoxes.Count})");
|
||||
textBoxes.ForEach(x => Debug.WriteLine(x));
|
||||
//Debug.WriteLine($"dbNetTime({dbNetTime}ms)");
|
||||
|
||||
// Debug.WriteLine("---------- step: drawTextBoxes ----------");
|
||||
// OcrUtils.DrawTextBoxes(textBoxPaddingImg, textBoxes, thickness);
|
||||
//Cv2.Imshow("ResultPadding", textBoxPaddingImg);
|
||||
|
||||
//---------- getPartImages ----------
|
||||
List<Mat> partImages = OcrUtils.GetPartImages(src, textBoxes);
|
||||
if (isPartImg)
|
||||
{
|
||||
for (int i = 0; i < partImages.Count; i++)
|
||||
{
|
||||
Cv2.ImShow($"PartImg({i})", partImages[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Debug.WriteLine("---------- step: angleNet getAngles ----------");
|
||||
List<Angle> angles = angleNet.GetAngles(partImages, doAngle, mostAngle);
|
||||
//angles.ForEach(x => Debug.WriteLine(x));
|
||||
|
||||
//Rotate partImgs
|
||||
for (int i = 0; i < partImages.Count; ++i)
|
||||
{
|
||||
if (angles[i].Index == 1)
|
||||
{
|
||||
partImages[i] = OcrUtils.MatRotateClockWise180(partImages[i]);
|
||||
}
|
||||
if (isDebugImg)
|
||||
{
|
||||
Cv2.ImShow($"DebugImg({i})", partImages[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Debug.WriteLine("---------- step: crnnNet getTextLines ----------");
|
||||
List<TextLine> textLines = crnnNet.GetTextLines(partImages);
|
||||
//textLines.ForEach(x => Debug.WriteLine(x));
|
||||
|
||||
List<TextBlock> textBlocks = new List<TextBlock>();
|
||||
for (int i = 0; i < textLines.Count; ++i)
|
||||
{
|
||||
TextBlock textBlock = new()
|
||||
{
|
||||
BoxPoints = textBoxes[i].Points,
|
||||
BoxScore = textBoxes[i].Score,
|
||||
AngleIndex = angles[i].Index,
|
||||
AngleScore = angles[i].Score,
|
||||
AngleTime = angles[i].Time,
|
||||
Text = textLines[i].Text,
|
||||
CharScores = textLines[i].CharScores,
|
||||
CrnnTime = textLines[i].Time,
|
||||
BlockTime = angles[i].Time + textLines[i].Time
|
||||
};
|
||||
textBlocks.Add(textBlock);
|
||||
}
|
||||
//textBlocks.ForEach(x => Debug.WriteLine(x));
|
||||
|
||||
var endTicks = DateTime.Now.Ticks;
|
||||
var fullDetectTime = (endTicks - startTicks) / 10000F;
|
||||
//Debug.WriteLine($"fullDetectTime({fullDetectTime}ms)");
|
||||
|
||||
//cropped to original size
|
||||
// Mat boxImg = new Mat(textBoxPaddingImg, originRect);
|
||||
|
||||
StringBuilder strRes = new StringBuilder();
|
||||
textBlocks.ForEach(x => strRes.AppendLine(x.Text));
|
||||
|
||||
var ocrResult = new RapidOcrResult
|
||||
{
|
||||
TextBlocks = textBlocks,
|
||||
DbNetTime = dbNetTime,
|
||||
// ocrResult.BoxImg = boxImg;
|
||||
DetectTime = fullDetectTime,
|
||||
StrRes = strRes.ToString()
|
||||
};
|
||||
|
||||
return ocrResult;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using System;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX.OCR.Paddle;
|
||||
|
||||
class ScaleParam
|
||||
{
|
||||
private int srcWidth;
|
||||
private int srcHeight;
|
||||
private int dstWidth;
|
||||
private int dstHeight;
|
||||
private float scaleWidth;
|
||||
private float scaleHeight;
|
||||
|
||||
public int SrcWidth { get => srcWidth; set => srcWidth = value; }
|
||||
public int SrcHeight { get => srcHeight; set => srcHeight = value; }
|
||||
public int DstWidth { get => dstWidth; set => dstWidth = value; }
|
||||
public int DstHeight { get => dstHeight; set => dstHeight = value; }
|
||||
public float ScaleWidth { get => scaleWidth; set => scaleWidth = value; }
|
||||
public float ScaleHeight { get => scaleHeight; set => scaleHeight = value; }
|
||||
|
||||
public ScaleParam(int srcWidth, int srcHeight, int dstWidth, int dstHeight, float scaleWidth, float scaleHeight)
|
||||
{
|
||||
this.srcWidth = srcWidth;
|
||||
this.srcHeight = srcHeight;
|
||||
this.dstWidth = dstWidth;
|
||||
this.dstHeight = dstHeight;
|
||||
this.scaleWidth = scaleWidth;
|
||||
this.scaleHeight = scaleHeight;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"sw:{this.srcWidth},sh:{this.srcHeight},dw:{this.dstWidth},dh:{this.dstHeight},{this.scaleWidth},{this.scaleHeight}";
|
||||
}
|
||||
|
||||
public static ScaleParam GetScaleParam(Mat src, int dstSize)
|
||||
{
|
||||
int srcWidth, srcHeight, dstWidth, dstHeight;
|
||||
srcWidth = src.Cols;
|
||||
dstWidth = src.Cols;
|
||||
srcHeight = src.Rows;
|
||||
dstHeight = src.Rows;
|
||||
|
||||
float scale = 1.0F;
|
||||
if (dstWidth > dstHeight)
|
||||
{
|
||||
scale = (float)dstSize / (float)dstWidth;
|
||||
dstWidth = dstSize;
|
||||
dstHeight = (int)((float)dstHeight * scale);
|
||||
}
|
||||
else
|
||||
{
|
||||
scale = (float)dstSize / (float)dstHeight;
|
||||
dstHeight = dstSize;
|
||||
dstWidth = (int)((float)dstWidth * scale);
|
||||
}
|
||||
if (dstWidth % 32 != 0)
|
||||
{
|
||||
dstWidth = (dstWidth / 32 - 1) * 32;
|
||||
dstWidth = Math.Max(dstWidth, 32);
|
||||
}
|
||||
if (dstHeight % 32 != 0)
|
||||
{
|
||||
dstHeight = (dstHeight / 32 - 1) * 32;
|
||||
dstHeight = Math.Max(dstHeight, 32);
|
||||
}
|
||||
float scaleWidth = (float)dstWidth / (float)srcWidth;
|
||||
float scaleHeight = (float)dstHeight / (float)srcHeight;
|
||||
return new ScaleParam(srcWidth, srcHeight, dstWidth, dstHeight, scaleWidth, scaleHeight);
|
||||
}
|
||||
}
|
||||
@@ -375,7 +375,7 @@ public class AutoDomainTask
|
||||
using var ra = GetRectAreaFromDispatcher();
|
||||
|
||||
var endTipsRect = ra.DeriveCrop(AutoFightContext.Instance.FightAssets.EndTipsUpperRect);
|
||||
var text = OcrFactory.Paddle.Ocr(endTipsRect.SrcGreyMat);
|
||||
var text = OcrFactory.Paddle.Ocr(endTipsRect.SrcMat);
|
||||
if (text.Contains("挑战") || text.Contains("达成"))
|
||||
{
|
||||
Logger.LogInformation("检测到秘境结束提示(挑战达成),结束秘境");
|
||||
@@ -383,7 +383,7 @@ public class AutoDomainTask
|
||||
}
|
||||
|
||||
endTipsRect = ra.DeriveCrop(AutoFightContext.Instance.FightAssets.EndTipsRect);
|
||||
text = OcrFactory.Paddle.Ocr(endTipsRect.SrcGreyMat);
|
||||
text = OcrFactory.Paddle.Ocr(endTipsRect.SrcMat);
|
||||
if (text.Contains("自动") || text.Contains("退出"))
|
||||
{
|
||||
Logger.LogInformation("检测到秘境结束提示(xxx秒后自动退出),结束秘境");
|
||||
@@ -758,7 +758,7 @@ public class AutoDomainTask
|
||||
// 图像右侧就是浓缩树脂数量
|
||||
var countArea = ra.DeriveCrop(condensedResinCountRa.X + condensedResinCountRa.Width, condensedResinCountRa.Y, condensedResinCountRa.Width, condensedResinCountRa.Height);
|
||||
// Cv2.ImWrite($"log/resin_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")}.png", countArea.SrcGreyMat);
|
||||
var count = OcrFactory.Paddle.OcrWithoutDetector(countArea.SrcGreyMat);
|
||||
var count = OcrFactory.Paddle.OcrWithoutDetector(countArea.SrcMat);
|
||||
condensedResinCount = StringUtils.TryParseInt(count);
|
||||
}
|
||||
|
||||
@@ -768,7 +768,7 @@ public class AutoDomainTask
|
||||
{
|
||||
// 图像右侧就是脆弱树脂数量
|
||||
var countArea = ra.DeriveCrop(fragileResinCountRa.X + fragileResinCountRa.Width, fragileResinCountRa.Y, (int)(fragileResinCountRa.Width * 3), fragileResinCountRa.Height);
|
||||
var count = OcrFactory.Paddle.Ocr(countArea.SrcGreyMat);
|
||||
var count = OcrFactory.Paddle.Ocr(countArea.SrcMat);
|
||||
fragileResinCount = StringUtils.TryParseInt(count);
|
||||
}
|
||||
|
||||
|
||||
@@ -299,7 +299,7 @@ public class Avatar
|
||||
public double GetSkillCurrentCd(ImageRegion imageRegion)
|
||||
{
|
||||
var eRa = imageRegion.DeriveCrop(AutoFightContext.Instance.FightAssets.ERect);
|
||||
var text = OcrFactory.Paddle.Ocr(eRa.SrcGreyMat);
|
||||
var text = OcrFactory.Paddle.Ocr(eRa.SrcMat);
|
||||
return StringUtils.TryParseDouble(text);
|
||||
}
|
||||
|
||||
@@ -353,7 +353,7 @@ public class Avatar
|
||||
// public double GetBurstCurrentCd(CaptureContent content)
|
||||
// {
|
||||
// var qRa = content.CaptureRectArea.Crop(AutoFightContext.Instance.FightAssets.QRect);
|
||||
// var text = OcrFactory.Paddle.Ocr(qRa.SrcGreyMat);
|
||||
// var text = OcrFactory.Paddle.Ocr(qRa.SrcMat);
|
||||
// return StringUtils.TryParseDouble(text);
|
||||
// }
|
||||
|
||||
|
||||
@@ -3,13 +3,12 @@ using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Assets;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Config;
|
||||
using BetterGenshinImpact.GameTask.Model;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using Compunet.YoloV8;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
using OpenCvSharp.Extensions;
|
||||
using Sdcb.PaddleOCR;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
@@ -18,7 +17,6 @@ using System.Drawing.Imaging;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
@@ -212,7 +210,7 @@ public class CombatScenes : IDisposable
|
||||
}
|
||||
|
||||
[Obsolete]
|
||||
private void ParseTeamOcrResult(PaddleOcrResult result, ImageRegion rectArea)
|
||||
private void ParseTeamOcrResult(OcrResult result, ImageRegion rectArea)
|
||||
{
|
||||
List<string> names = new();
|
||||
List<Rect> nameRects = new();
|
||||
|
||||
@@ -136,14 +136,14 @@ public class AutoPickTrigger : ITaskTrigger
|
||||
// 计算出文字区域
|
||||
var textRect = new Rect(foundRectArea.X + (int)(config.ItemTextLeftOffset * scale), foundRectArea.Y,
|
||||
(int)((config.ItemTextRightOffset - config.ItemTextLeftOffset) * scale), foundRectArea.Height);
|
||||
if (textRect.X + textRect.Width > content.CaptureRectArea.SrcGreyMat.Width
|
||||
|| textRect.Y + textRect.Height > content.CaptureRectArea.SrcGreyMat.Height)
|
||||
if (textRect.X + textRect.Width > content.CaptureRectArea.SrcMat.Width
|
||||
|| textRect.Y + textRect.Height > content.CaptureRectArea.SrcMat.Height)
|
||||
{
|
||||
Debug.WriteLine("AutoPickTrigger: 文字区域 out of range");
|
||||
return;
|
||||
}
|
||||
|
||||
var textMat = new Mat(content.CaptureRectArea.SrcGreyMat, textRect);
|
||||
var textMat = new Mat(content.CaptureRectArea.SrcMat, textRect);
|
||||
|
||||
string text;
|
||||
if (config.OcrEngine == PickOcrEngineEnum.Yap.ToString())
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
@@ -6,12 +7,12 @@ using BetterGenshinImpact.GameTask.AutoSkip.Assets;
|
||||
using BetterGenshinImpact.GameTask.AutoSkip.Model;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.GameTask.Common.Element.Assets;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using BetterGenshinImpact.Service;
|
||||
using BetterGenshinImpact.View.Drawable;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
using Sdcb.PaddleOCR;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
@@ -20,8 +21,6 @@ using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Windows.Forms;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoSkip;
|
||||
@@ -260,7 +259,7 @@ public class AutoSkipTrigger : ITaskTrigger
|
||||
// OCR识别选项文字
|
||||
foreach (var hangoutOption in hangoutOptionList)
|
||||
{
|
||||
var text = OcrFactory.Paddle.Ocr(hangoutOption.TextRect!.SrcGreyMat);
|
||||
var text = OcrFactory.Paddle.Ocr(hangoutOption.TextRect!.SrcMat);
|
||||
hangoutOption.OptionTextSrc = StringUtils.RemoveAllEnter(text);
|
||||
}
|
||||
|
||||
|
||||
@@ -253,7 +253,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
|
||||
wDown = false;
|
||||
}
|
||||
// 识别距离
|
||||
var text = OcrFactory.Paddle.OcrWithoutDetector(ra.SrcGreyMat[_missionDistanceRect]);
|
||||
var text = OcrFactory.Paddle.OcrWithoutDetector(ra.SrcMat[_missionDistanceRect]);
|
||||
if (StringUtils.TryExtractPositiveInt(text) is > -1 and <= 3)
|
||||
{
|
||||
Logger.LogInformation("任务追踪:到达目标,识别结果[{Text}]", text);
|
||||
|
||||
@@ -4,8 +4,6 @@ using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.View.Drawable;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
using OpenCvSharp.Extensions;
|
||||
using Sdcb.PaddleOCR;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
@@ -153,7 +151,7 @@ public class ExpeditionTask
|
||||
/// </summary>
|
||||
/// <param name="result"></param>
|
||||
/// <returns></returns>
|
||||
private List<ExpeditionCharacterCard> GetCharacterCards(PaddleOcrResult result)
|
||||
private List<ExpeditionCharacterCard> GetCharacterCards(OcrResult result)
|
||||
{
|
||||
var captureRect = TaskContext.Instance().SystemInfo.CaptureAreaRect;
|
||||
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
|
||||
@@ -209,18 +207,18 @@ public class ExpeditionTask
|
||||
|
||||
private readonly Pen _pen = new(Color.Red, 1);
|
||||
|
||||
private PaddleOcrResult CaptureAndOcr(CaptureContent content)
|
||||
private OcrResult CaptureAndOcr(CaptureContent content)
|
||||
{
|
||||
using var ra = TaskControl.CaptureToRectArea();
|
||||
var result = OcrFactory.Paddle.OcrResult(ra.SrcGreyMat);
|
||||
var result = OcrFactory.Paddle.OcrResult(ra.SrcMat);
|
||||
//VisionContext.Instance().DrawContent.PutOrRemoveRectList("OcrResultRects", result.ToRectDrawableList(_pen));
|
||||
return result;
|
||||
}
|
||||
|
||||
private PaddleOcrResult CaptureAndOcr(CaptureContent content, Rect rect)
|
||||
private OcrResult CaptureAndOcr(CaptureContent content, Rect rect)
|
||||
{
|
||||
using var ra = TaskControl.CaptureToRectArea();
|
||||
var result = OcrFactory.Paddle.OcrResult(ra.SrcGreyMat);
|
||||
var result = OcrFactory.Paddle.OcrResult(ra.SrcMat);
|
||||
//VisionContext.Instance().DrawContent.PutOrRemoveRectList("OcrResultRects", result.ToRectDrawableList(_pen));
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -232,7 +232,7 @@ public partial class AutoWoodTask
|
||||
{
|
||||
// OCR识别文本区域
|
||||
var woodCountRect = CaptureToRectArea().DeriveCrop(assert.WoodCountUpperRect);
|
||||
return OcrFactory.Paddle.Ocr(woodCountRect.SrcGreyMat);
|
||||
return OcrFactory.Paddle.Ocr(woodCountRect.SrcMat);
|
||||
}
|
||||
|
||||
private bool HasDetectedWoodText(string recognizedText)
|
||||
|
||||
@@ -197,10 +197,10 @@ public class ImageRegion : Region
|
||||
throw new Exception($"[OCR]识别对象{ro.Name}的匹配文本不能全为空");
|
||||
}
|
||||
|
||||
var roi = SrcGreyMat;
|
||||
var roi = SrcMat;
|
||||
if (ro.RegionOfInterest != Rect.Empty)
|
||||
{
|
||||
roi = new Mat(SrcGreyMat, ro.RegionOfInterest);
|
||||
roi = new Mat(SrcMat, ro.RegionOfInterest);
|
||||
}
|
||||
|
||||
var result = OcrFactory.Paddle.OcrResult(roi);
|
||||
@@ -289,10 +289,10 @@ public class ImageRegion : Region
|
||||
}
|
||||
else
|
||||
{
|
||||
roi = SrcGreyMat;
|
||||
roi = SrcMat;
|
||||
if (ro.RegionOfInterest != Rect.Empty)
|
||||
{
|
||||
roi = new Mat(SrcGreyMat, ro.RegionOfInterest);
|
||||
roi = new Mat(SrcMat, ro.RegionOfInterest);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -414,10 +414,10 @@ public class ImageRegion : Region
|
||||
}
|
||||
else if (RecognitionTypes.Ocr.Equals(ro.RecognitionType))
|
||||
{
|
||||
var roi = SrcGreyMat;
|
||||
var roi = SrcMat;
|
||||
if (ro.RegionOfInterest != Rect.Empty)
|
||||
{
|
||||
roi = new Mat(SrcGreyMat, ro.RegionOfInterest);
|
||||
roi = new Mat(SrcMat, ro.RegionOfInterest);
|
||||
}
|
||||
|
||||
var result = OcrFactory.Paddle.OcrResult(roi);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX.OCR.Paddle;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using BetterGenshinImpact.Model;
|
||||
using BetterGenshinImpact.Service.Interface;
|
||||
@@ -15,7 +16,11 @@ using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Forms;
|
||||
using Windows.Devices.Geolocation;
|
||||
using Windows.Media.Ocr;
|
||||
using Wpf.Ui;
|
||||
using MessageBox = System.Windows.Forms.MessageBox;
|
||||
|
||||
namespace BetterGenshinImpact.ViewModel;
|
||||
|
||||
@@ -67,7 +72,7 @@ public partial class MainWindowViewModel : ObservableObject, IViewModel
|
||||
{
|
||||
try
|
||||
{
|
||||
var s = OcrFactory.Paddle.Ocr(new Mat(Global.Absolute("Assets\\Model\\PaddleOCR\\test_ocr.png"), ImreadModes.Grayscale));
|
||||
var s = OcrFactory.Paddle.Ocr(new Mat(Global.Absolute("Assets\\Model\\PaddleOCR\\test_ocr.png")));
|
||||
Debug.WriteLine("PaddleOcr预热结果:" + s);
|
||||
}
|
||||
catch (Exception e)
|
||||
|
||||
Reference in new issue
Block a user