123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353 |
- using Android.App;
- using Android.Graphics;
- using Android.OS;
- using Android.Widget;
- using AndroidX.AppCompat.App;
- using IDCardRecognitionLibs;
- using OfficeOpenXml;
- using System;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using System.Threading;
- using System.Threading.Tasks;
- namespace IDCardRecognitionXamarin
- {
- [Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
- public class MainActivity : AppCompatActivity
- {
- private IDCardRecog _iDCardRecog = new IDCardRecog();
- private volatile bool _testing = false;
- private volatile Android.Graphics.Bitmap _testImg;
- private string _assemblyName;
- private TypeInfo _typeInfo;
- protected override void OnCreate(Bundle savedInstanceState)
- {
- var typeInfo = GetType().GetTypeInfo();
- _typeInfo = typeInfo;
- var assemblyName = typeInfo.Assembly.GetName().Name;
- _assemblyName = assemblyName;
- var netDetDir = $"{assemblyName}.Resources.ValidModels.ch_PP-OCRv4_det_infer.onnx";
- byte[] detBuffer = getModelBuffer(typeInfo, netDetDir);
- var netRecDir = $"{assemblyName}.Resources.ValidModels.ch_PP-OCRv4_rec_infer.onnx";
- byte[] recBuffer = getModelBuffer(typeInfo, netRecDir);
- var netDirKeys = $"{assemblyName}.Resources.ValidModels.ppocr_keys_v1.txt";
- byte[] recKeyBuffer = getModelBuffer(typeInfo, netDirKeys);
- var netClsDir = $"{assemblyName}.Resources.ValidModels.ch_ppocr_mobile_cls_infer.onnx";
- byte[] clsBuffer = getModelBuffer(typeInfo, netClsDir);
- bool ret = _iDCardRecog.LoadNetWorks(detBuffer, recBuffer, recKeyBuffer, clsBuffer);
- if (!ret)
- {
- Console.WriteLine("LoadNetWorks error");
- }
- base.OnCreate(savedInstanceState);
- Xamarin.Essentials.Platform.Init(this, savedInstanceState);
- SetContentView(Resource.Layout.activity_main);
- var btnTestBin = FindViewById<Button>(Resource.Id.btnBin);
- btnTestBin.Click += BtnShowSrcImgClick;
- var btnPlusStruct = FindViewById<Button>(Resource.Id.btnPlus);
- btnPlusStruct.Click += BtnTestBtnPlusClick;
- }
- private void BtnShowSrcImgClick(object sender, EventArgs e)
- {
- if (!_testing)
- {
- Task.Run(() =>
- {
- _testing = true;
- ImageView imageView = FindViewById<ImageView>(Resource.Id.imageView);
- var typeInfo = GetType().GetTypeInfo();
- var assemblyName = typeInfo.Assembly.GetName().Name;
- TextView textView = FindViewById<TextView>(Resource.Id.retTextInfor);
- var resourceName1 = $"{assemblyName}.Resources.drawable.img_3.png";
- using (var stream = typeInfo.Assembly.GetManifestResourceStream(resourceName1))
- {
- // 更新显示图像
- var bitmap = BitmapFactory.DecodeStream(stream);
- RunOnUiThread(() => imageView.SetImageBitmap(bitmap));
- // 将图像传给_test去做检测
- int width = bitmap.Width;
- int height = bitmap.Height;
- IntPtr dataPointer = bitmap.LockPixels();
- EnumColorType colorType = EnumColorType.Rgba;
- int stride = bitmap.RowBytes;
- byte[] data = BitmapToByte(dataPointer, width, height, colorType, stride);
- ClassIDCardRecogResult result = _iDCardRecog.EvaluateOneImage(data, width, height, colorType);
- RunOnUiThread(() => textView.Text = "身份证信息:" + "\n "
- + "返回码:" + result.Status + "\n "
- + "姓名:" + result.Name + "\n "
- + "性别:" + result.Gender + "\n "
- + "民族:" + result.Nation + "\n "
- + "出生:" + result.Birthdate + "\n "
- + "住址:" + result.Address + "\n "
- + "公民身份号码:" + result.IdNumber + "\n ");
- }
- Thread.Sleep(3000);
- _iDCardRecog.Dispose();
- _testing = false;
- });
- }
- }
- private void BtnTestBtnPlusClick(object sender, EventArgs e)
- {
- if (!_testing)
- {
- Task.Run(() =>
- {
- _testing = true;
- ImageView imageView = FindViewById<ImageView>(Resource.Id.imageView);
- var typeInfo = GetType().GetTypeInfo();
- var assemblyName = typeInfo.Assembly.GetName().Name;
- TextView textView = FindViewById<TextView>(Resource.Id.retTextInfor);
- int indexStart = 19;
- int indexEnd = 50;
- string dstPath = "/sdcard/Documents/" + DateTime.Now.ToString("yyyy-MM-dd-mm-ss-fffff") + "_log.txt";
- // 将文本内容存储到Excel表格
- string excelFilePath = "/sdcard/Documents/" + DateTime.Now.ToString("yyyy-MM-dd-mm-ss-fffff") + "_log.xlsx";
- AppendTextToExcel(excelFilePath, "imgId", "so20");
- for (int i = indexStart; i < indexEnd; i++)
- {
- var resourceName1 = $"{assemblyName}.Resources.drawable.img_{i}.png";
- using (var stream = typeInfo.Assembly.GetManifestResourceStream(resourceName1))
- {
- // 更新显示图像
- var bitmap = BitmapFactory.DecodeStream(stream);
- RunOnUiThread(() => imageView.SetImageBitmap(bitmap));
- // 将图像传给_test去做检测
- int width = bitmap.Width;
- int height = bitmap.Height;
- IntPtr dataPointer = bitmap.LockPixels();
- EnumColorType colorType = EnumColorType.Rgba;
- int stride = bitmap.RowBytes;
- byte[] data = BitmapToByte(dataPointer, width, height, colorType, stride);
- ClassIDCardRecogResult result = _iDCardRecog.EvaluateOneImage(data, width, height, colorType);
- RunOnUiThread(() => textView.Text = i + ".jpg -" + "身份证信息:" + "\n "
- + "返回码:" + result.Status + "\n "
- + "耗时:" + result.TimeSpan + "\n ");
- // 添加文本到log 中
- string addExcelCol2 = result.Status + "-" + result.Name
- + "-" + result.Gender
- + "-" + result.Nation
- + "-" + result.Birthdate
- + "-" + result.Nation
- + "-" + result.Address;
- AppendTextToFile(dstPath, "img_" + i + ".jpg:\n" + addExcelCol2);
- AppendTextToExcel(excelFilePath, "img_" + i + ".jpg", addExcelCol2);
- }
- Thread.Sleep(3000);
- }
- _testing = false;
- _iDCardRecog.Dispose();
- });
- }
- }
- // 追加文本到文件
- private void AppendTextToFile(string filePath, string text)
- {
- try
- {
- // 如果文件不存在,则创建文件;如果存在,则追加内容
- using (StreamWriter sw = File.AppendText(filePath))
- {
- sw.WriteLine(text);
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine("Error appending text to file: " + ex.Message);
- }
- }
- // 将文本内容追加到Excel表格
- private static void AppendTextToExcel(string excelFilePath, string textContentColumn0, string textContentColumn1)
- {
- FileInfo excelFile = new FileInfo(excelFilePath);
- using (ExcelPackage package = new ExcelPackage(excelFile))
- {
- ExcelWorksheet worksheet;
- // 检查是否存在名为 "LogData" 的工作表
- if (package.Workbook.Worksheets.Any(ws => ws.Name == "LogData"))
- {
- worksheet = package.Workbook.Worksheets["LogData"];
- }
- else
- {
- // 如果不存在,则创建新的工作表
- worksheet = package.Workbook.Worksheets.Add("LogData");
- }
- // 获取工作表中已有的行数
- int existingRowCount = worksheet.Dimension?.Rows ?? 0;
- // 分割新文本内容并追加到表格
- string[] linesColumn0 = textContentColumn0.Split('\n');
- string[] linesColumn1 = textContentColumn1.Split('\n');
- int newRowCount = Math.Max(linesColumn0.Length, linesColumn1.Length);
- for (int rowIndex = existingRowCount + 1; rowIndex <= existingRowCount + newRowCount; rowIndex++)
- {
- // 获取每列文本内容
- string column0Value = (rowIndex - existingRowCount <= linesColumn0.Length) ? linesColumn0[rowIndex - existingRowCount - 1] : string.Empty;
- string column1Value = (rowIndex - existingRowCount <= linesColumn1.Length) ? linesColumn1[rowIndex - existingRowCount - 1] : string.Empty;
- // 存储到表格
- worksheet.Cells[rowIndex, 1].Value = column0Value; // 第一列
- worksheet.Cells[rowIndex, 2].Value = column1Value; // 第二列
- }
- package.Save();
- }
- }
- private static byte[] ReadStreamContent(System.IO.Stream stream)
- {
- if (stream != null)
- {
- try
- {
- // 使用BinaryReader读取流中的内容并转换为字节数组
- using (BinaryReader br = new BinaryReader(stream))
- {
- // 使用MemoryStream来存储字节数组
- using (MemoryStream ms = new MemoryStream())
- {
- byte[] buffer = new byte[1024];
- int bytesRead;
- while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0)
- {
- ms.Write(buffer, 0, bytesRead);
- }
- // 返回字节数组
- return ms.ToArray();
- }
- }
- }
- catch (Exception ex)
- {
- // 处理异常
- Console.WriteLine("读取流时发生错误:" + ex.Message);
- return new byte[0];
- }
- }
- else
- {
- Console.WriteLine("流为空");
- return new byte[0];
- }
- }
- private static string ReadStreamContentStr(System.IO.Stream stream)
- {
- if (stream != null)
- {
- try
- {
- // 使用StreamReader读取流中的内容
- using (StreamReader sr = new StreamReader(stream))
- {
- // 读取流中的全部内容
- return sr.ReadToEnd();
- }
- }
- catch (Exception ex)
- {
- // 处理异常
- Console.WriteLine("读取流时发生错误:" + ex.Message);
- return string.Empty;
- }
- }
- else
- {
- Console.WriteLine("流为空");
- return string.Empty;
- }
- }
- private byte[] getModelBuffer(TypeInfo typeInfo, string netDir)
- {
- // 获取模型流
- var stream = typeInfo.Assembly.GetManifestResourceStream(netDir);
- if (stream == null)
- {
- throw new InvalidOperationException($"Resource not found: {netDir}");
- }
- // 读取流内容到字节数组
- byte[] buffer = new byte[stream.Length];
- stream.Read(buffer, 0, buffer.Length);
- return buffer;
- }
- private byte[] BitmapToByte(IntPtr dataPointer, int width, int height, EnumColorType colorType, int stride)
- {
- int origBytesPerPixel = 0;
- EnumColorType dstColorType = EnumColorType.Bgra;
- if (colorType == EnumColorType.Rgba)
- {
- origBytesPerPixel = 4;
- }
- if (colorType == EnumColorType.Bgr)
- {
- origBytesPerPixel = 3;
- }
- byte[] dstDataArray = new byte[width * height * origBytesPerPixel];
- IntPtr ptrH, ptrW;
- int dstStride = width * origBytesPerPixel;
- for (int nh = 0; nh < height; nh++)
- {
- ptrH = IntPtr.Add(dataPointer, nh * stride);
- Marshal.Copy(ptrH, dstDataArray, nh * dstStride, dstStride);
- }
- //// 如果原图是BGRA彩色图
- ////if (oriColorType == EnumColorType.Bgra)
- ////{
- //// if (colorType == EnumColorType.Bgr)
- //// {
- //// int dstOffset;
- //// for (int nh = 0; nh < height; nh++)
- //// {
- //// ptrH = IntPtr.Add(dataPointer, nh * stride);
- //// for (int nw = 0; nw < width; nw++)
- //// {
- //// ptrW = IntPtr.Add(ptrH, nw * origBytesPerPixel);
- //// dstOffset = nh * dstStride + nw * 3;
- //// Marshal.Copy(ptrW, dstDataArray, dstOffset, 3);
- //// }
- //// }
- //// }
- ////}
- return dstDataArray;
- }
- }
- }
|