v1.2 新禾欣版本初版

This commit is contained in:
CPL 2024-10-18 08:22:25 +08:00
parent 5f50916938
commit 2764865ef5
8 changed files with 588 additions and 224 deletions

View File

@ -90,6 +90,10 @@ namespace LeatherApp
public static string cloud_ip, cloud_username, cloud_password, CloudThisName; public static string cloud_ip, cloud_username, cloud_password, CloudThisName;
public static int cloud_port, cloud_open; public static int cloud_port, cloud_open;
//传统算法
public static bool OpenHalconDefect;
public static string HalconParamPath;
public static void LoadCloudConfig() public static void LoadCloudConfig()
{ {
if (string.IsNullOrWhiteSpace(appBasePath)) if (string.IsNullOrWhiteSpace(appBasePath))
@ -212,6 +216,14 @@ namespace LeatherApp
SkipLabelGrade = lsTmp.Split(new char[] { ',', ';' }); SkipLabelGrade = lsTmp.Split(new char[] { ',', ';' });
else else
SkipLabelGrade = new string[1] { "" }; SkipLabelGrade = new string[1] { "" };
//传统参数
OpenHalconDefect = ini.ReadBool("Halcon", "OpenHalconDefect");
lsTmp = ini.ReadString("Halcon", "HalconParamPath", "").Trim();
if (!string.IsNullOrWhiteSpace(lsTmp))
HalconParamPath = lsTmp;
else
HalconParamPath = appBasePath;
} }
#region defectItemList <=> DefectItemList.json #region defectItemList <=> DefectItemList.json
@ -245,10 +257,20 @@ namespace LeatherApp
{ {
try try
{ {
if (id == -99)
{
JObject obj = new JObject();
obj.Add("id", 0);
obj.Add("code", "ng");
obj.Add("name", "NG");
obj.Add("color", "Red");
return obj;
}
var item = Config.defectItemList.FirstOrDefault(m => m.Value<int>("id") == id); var item = Config.defectItemList.FirstOrDefault(m => m.Value<int>("id") == id);
if (item == null) if (item == null)
return null; return null;
return (JObject)item; return (JObject)item;
} }
catch { return null; } catch { return null; }
} }

View File

@ -10,11 +10,15 @@ using System.Linq;
using System.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading; using System.Threading;
using HalconDotNet;
using System.Windows.Forms.VisualStyles;
using LeatherApp.Utils; using LeatherApp.Utils;
using Models; using Models;
using OpenCvSharp; using OpenCvSharp;
using OpenCvSharp.Extensions; using OpenCvSharp.Extensions;
using PG_Detect;
using SqlSugar; using SqlSugar;
using HZH_Controls;
namespace LeatherApp.Device namespace LeatherApp.Device
{ {
@ -93,22 +97,14 @@ namespace LeatherApp.Device
private List<DefectTask> taskMakeTagList = new List<DefectTask>(); private List<DefectTask> taskMakeTagList = new List<DefectTask>();
private string preModelName = ""; private string preModelName = "";
//传统算法核心
private PGDetect tPGDetect = new PGDetect();
public DefectLib() public DefectLib()
{ {
} }
public bool start() public bool start()
{ {
//List<DefectLabelInfo> DefectLabelInfoList = new List<DefectLabelInfo>();
//DefectLabelInfoList.Add(new DefectLabelInfo() { x = 1953, y = 429, w = 200, h = 200, classId = 1, confidence = 0.8, contrast = 0.9, i = 0, j = 0 });
//DefectLabelInfoList.Add(new DefectLabelInfo() {x = 1953,y = 929,w=900,h = 400,classId = 11,confidence = 0.8, contrast = 0.9, i = 0,j = 0 });
//DefectLabelInfoList.Add(new DefectLabelInfo() { x = 3169, y = 1029, w = 900, h = 400, classId = 11, confidence = 0.8, contrast = 0.9, i = 1, j = 0 });
//DefectLabelInfoList.Add(new DefectLabelInfo() { x = 4721, y = 919, w = 900, h = 400, classId = 11, confidence = 0.8, contrast = 0.9, i = 2, j = 0 });
//DefectLabelInfoList.Add(new DefectLabelInfo() { x = 6145, y = 829, w = 900, h = 400, classId = 11, confidence = 0.8, contrast = 0.9, i = 3, j = 0 });
//DefectLabelInfoList.Add(new DefectLabelInfo() { x = 8073, y = 929, w = 900, h = 400, classId = 11, confidence = 0.8, contrast = 0.9, i = 4, j = 0 });
//DefectLabelInfoList.Add(new DefectLabelInfo() { x = 9407, y = 929, w = 900, h = 400, classId = 11, confidence = 0.8, contrast = 0.9, i = 5, j = 0 });
//DefectLabelInfoList.Add(new DefectLabelInfo() { x = 10801, y = 999, w = 900, h = 400, classId = 11, confidence = 0.8, contrast = 0.9, i = 6, j = 0 });
//DefectLabelInfoList.Add(new DefectLabelInfo() { x = 12465, y = 629, w = 900, h = 800, classId = 11, confidence = 0.8, contrast = 0.9, i = 7, j = 0 });
//DefectLabelInfoList = HeBingDefect(16384, DefectLabelInfoList);
try try
{ {
//detector = CreateDetector(Config.model_path, Config.labels_path, true, 6); //detector = CreateDetector(Config.model_path, Config.labels_path, true, 6);
@ -238,6 +234,51 @@ namespace LeatherApp.Device
} }
} }
} }
public bool LoadModel(string modelPath)
{
int step = 0;
try
{
if (!Config.OpenHalconDefect)
{
if (preModelName != modelPath)
{
step = 3;
//先释放模型
if (detector != IntPtr.Zero)
{
step = 4;
DestroyDetector(detector);
detector = IntPtr.Zero;
}
step = 5;
detector = CreateDetector($"./models/{modelPath}");
if (detector == IntPtr.Zero)
throw new Exception($"模型({modelPath})初始化失败!");
step = 6;
preModelName = modelPath;
}
}
else
{
HObject obj = new HObject();
Mat mat = new Mat($"./init.bmp");
OpenCVUtil.MatToHObject(mat, out obj);
//HOperatorSet.GenImageConst(out obj, "byte", 2048 * 8, 2048 * 2);//生成一幅图像用byte格式默认是黑色
//Mat initMat = new Mat(2048 * 2, 2048 * 8, MatType.CV_8UC3);
if (!tPGDetect.IniOptimization(obj, Config.HalconParamPath))
throw new Exception($"传统算法({Config.HalconParamPath})初始化失败!");
}
return true;
}
catch (Exception e)
{
WarningEvent?.Invoke(DateTime.Now, WarningEnum.Low, $"Load Model err({step}):" + e.Message);
return false;
}
}
private void runStep() private void runStep()
{ {
int step = 0; int step = 0;
@ -258,54 +299,67 @@ namespace LeatherApp.Device
{ {
Stopwatch stopwatch = Stopwatch.StartNew(); Stopwatch stopwatch = Stopwatch.StartNew();
step =2; step =2;
if (preModelName != task.modelName) LoadModel(task.modelName);
{
step = 3;
//先释放模型
if (detector != IntPtr.Zero)
{
step = 4;
DestroyDetector(detector);
detector = IntPtr.Zero;
}
step = 5;
detector = CreateDetector($"./models/{task.modelName}");
if (detector == IntPtr.Zero)
throw new Exception($"模型({task.modelName})初始化失败!");
step = 6;
preModelName = task.modelName;
}
//源图 //源图
//Bitmap bmp = yolo1.Read2Bmp(file_path); //Bitmap bmp = yolo1.Read2Bmp(file_path);
//切割图像输入图像格式14208*10640 //切割图像输入图像格式14208*10640
stopwatch.Start(); stopwatch.Start();
//task.resizeBmp = OpenCVUtil.resize( task.bmp.Clone(), task.resize.Width, task.resize.Height);//在外面已做了resize if (!Config.OpenHalconDefect)
//Cv2.CvtColor(task.bmp, task.bmpBgr2rgb, ColorConversionCodes.BGR2RGB);
//task.bmps_cut = OpenCVToCutsMat(task.bmpBgr2rgb, image_width, image_hight); //这里cut时之前加的clone
step = 7;
task.bmps_cut = OpenCVToCutsMat(task.bmp, image_width, image_hight); //这里cut时之前加的clone
stopwatch.Stop();
task.stopwatch[0] = stopwatch.ElapsedMilliseconds;
//Resize图像
//stopwatch.Restart();
//task.bmps_resize = yolo1.OpenCVToResizesMat(task.bmps_cut, task.resize.Width, task.resize.Height);
//stopwatch.Stop();
//task.stopwatch[1] = stopwatch.ElapsedMilliseconds;
//预处理模型
//stopwatch.Restart();
//task.tensors = yolo1.PreprocessImageMat(task.bmps_resize);
//stopwatch.Stop();
//task.stopwatch[2] = stopwatch.ElapsedMilliseconds;
step = 8;
lock (taskOperationList)
{ {
taskOperationList.Add(task); //task.resizeBmp = OpenCVUtil.resize( task.bmp.Clone(), task.resize.Width, task.resize.Height);//在外面已做了resize
QueueCountEvent?.BeginInvoke(1, taskOperationList.Count, null, null);
//Cv2.CvtColor(task.bmp, task.bmpBgr2rgb, ColorConversionCodes.BGR2RGB);
//task.bmps_cut = OpenCVToCutsMat(task.bmpBgr2rgb, image_width, image_hight); //这里cut时之前加的clone
step = 7;
task.bmps_cut = OpenCVToCutsMat(task.bmp, image_width, image_hight); //这里cut时之前加的clone
stopwatch.Stop();
task.stopwatch[0] = stopwatch.ElapsedMilliseconds;
//Resize图像
//stopwatch.Restart();
//task.bmps_resize = yolo1.OpenCVToResizesMat(task.bmps_cut, task.resize.Width, task.resize.Height);
//stopwatch.Stop();
//task.stopwatch[1] = stopwatch.ElapsedMilliseconds;
//预处理模型
//stopwatch.Restart();
//task.tensors = yolo1.PreprocessImageMat(task.bmps_resize);
//stopwatch.Stop();
//task.stopwatch[2] = stopwatch.ElapsedMilliseconds;
step = 8;
lock (taskOperationList)
{
taskOperationList.Add(task);
QueueCountEvent?.BeginInvoke(1, taskOperationList.Count, null, null);
}
step = 9;
}
else
{
step = 20;
int object_num = 0;
//转换
OpenCVUtil.MatToHObject(task.bmp, out task.ho_Img);
stopwatch.Stop();
task.stopwatch[0] = stopwatch.ElapsedMilliseconds;
stopwatch.Restart();
step = 21;
//预处理
tPGDetect.Processing(task.ho_Img, out task.ho_imgG, out task.ho_ImageResult3, out task.ho_ImageSub,
Config.HalconParamPath,
out task.hv_RES, out task.hv_gauss_filter1, out task.hv_gauss_filter2,
out task.hv_Energy_value, out task.hv_Region_S_value, out task.hv_class);
stopwatch.Stop();
task.stopwatch[1] = stopwatch.ElapsedMilliseconds;
lock (taskOperationList)
{
taskOperationList.Add(task);
QueueCountEvent?.BeginInvoke(1, taskOperationList.Count, null, null);
}
} }
step = 9;
} }
} }
catch (Exception ex) catch (Exception ex)
@ -335,7 +389,7 @@ namespace LeatherApp.Device
int cut_count=0,step = 0; int cut_count=0,step = 0;
try try
{ {
if (task != null && task.bmps_cut.Count()>0) if (task != null && task.bmps_cut.Count()>0 && !Config.OpenHalconDefect)
{ {
//WarningEvent?.Invoke(DateTime.Now,WarningEnum.Low, "DefectLib tasks 运行推理..."); //WarningEvent?.Invoke(DateTime.Now,WarningEnum.Low, "DefectLib tasks 运行推理...");
cut_count = task.bmps_cut.Count(); cut_count = task.bmps_cut.Count();
@ -375,6 +429,24 @@ namespace LeatherApp.Device
QueueCountEvent?.BeginInvoke(2, taskMakeTagList.Count, null, null); QueueCountEvent?.BeginInvoke(2, taskMakeTagList.Count, null, null);
} }
} }
else
{
Stopwatch stopwatch = Stopwatch.StartNew();
stopwatch.Start();
step = 22;
//算法处理
tPGDetect.Detect(task.ho_Img, task.ho_imgG, task.ho_ImageResult3, task.ho_ImageSub,
task.hv_Energy_value, task.hv_Region_S_value, task.hv_class,
out task.hv_defectinfo, out task.object_num);
stopwatch.Stop();
task.stopwatch[2] = stopwatch.ElapsedMilliseconds;
lock (taskMakeTagList)
{
taskMakeTagList.Add(task);
QueueCountEvent?.BeginInvoke(2, taskMakeTagList.Count, null, null);
}
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -663,60 +735,62 @@ namespace LeatherApp.Device
int count = 0; int count = 0;
liStep = 3; liStep = 3;
//车用革去除接头处横档误判 if (!Config.OpenHalconDefect)
bool haveJieTou = false;
List<DefectLabelInfo> DefectLabelInfoList = new List<DefectLabelInfo>();
for (int i = 0; i < cut_count; i++)
{ {
liStep = i * 100; //车用革去除接头处横档误判
//task.resultInfo += $"第 {i}/{cut_count} 张小图(大图索引{task.photoIndex}): 缺陷数 = {task.output_num[i]}\n"; bool haveJieTou = false;
//task.resultInfo +=$"大图({task.tag})[{task.bmp.Width}*{task.bmp.Height}],第 {i + 1}/{cut_count} 张小图[{task.bmps_cut[i].Width}*{task.bmps_cut[i].Height}]: 瑕疵output_num = {output_num[i]}\n"; List<DefectLabelInfo> DefectLabelInfoList = new List<DefectLabelInfo>();
#region
for (int j = 0; j < task.output_num[i]; j++)//缺陷数 for (int i = 0; i < cut_count; i++)
{ {
liStep += j;//0 liStep = i * 100;
//WarningEvent?.Invoke(DateTime.Now,WarningEnum.Low, $"-------"); //task.resultInfo += $"第 {i}/{cut_count} 张小图(大图索引{task.photoIndex}): 缺陷数 = {task.output_num[i]}\n";
int index = count * detect_elem_size; //task.resultInfo +=$"大图({task.tag})[{task.bmp.Width}*{task.bmp.Height}],第 {i + 1}/{cut_count} 张小图[{task.bmps_cut[i].Width}*{task.bmps_cut[i].Height}]: 瑕疵output_num = {output_num[i]}\n";
#region
// 打印输出信息(示例代码,根据实际情况进行修改和格式化) for (int j = 0; j < task.output_num[i]; j++)//缺陷数
// 获取输出信息
int x = (int)task.output[index];
int y = (int)task.output[index + 1];
int w = (int)task.output[index + 2];
int h = (int)task.output[index + 3];
int classId = (int)task.output[index + 4];
double confidence = Math.Round(task.output[index + 5], 2); //置信度
double contrast = Math.Round(task.output[index + 6], 3);//对比度
//y = image_hight-y-h;//转到右下角为原点
count++;
//var cmW = Math.Round(w * task.widthRatio / Config.cm2px_x, 2);
//var cmH = Math.Round(h * task.widthRatio / Config.cm2px_y, 2);
var cmW = Math.Round(w * 1.0 / Config.cm2px_x, 2);
var cmH = Math.Round(h * 1.0 / Config.cm2px_y, 2);
// 打印输出信息
//task.resultInfo += $"----{i}----col:{i % colNum}/{colNum} row:{i / colNum}/{colNum}-----------\n目标:{j + 1} 类别ID:{classId} 置信度:{confidence} 对比度:{contrast} 坐标:({x},{y})-({x + w},{y + h}) 宽高:w={w},h={h}; \n";
DefectLabelInfoList.Add(new DefectLabelInfo()
{ {
x = (int)task.output[index], liStep += j;//0
y = (int)task.output[index + 1], //WarningEvent?.Invoke(DateTime.Now,WarningEnum.Low, $"-------");
w = (int)task.output[index + 2], int index = count * detect_elem_size;
h = (int)task.output[index + 3],
classId = (int)task.output[index + 4],
confidence = Math.Round(task.output[index + 5], 2), //置信度
contrast = ContrastToPercent( Math.Round(task.output[index + 6], 3)),//对比度
//cmW = Math.Round(w * task.widthRatio / Config.cm2px_x, 2),
//cmH = Math.Round(h * task.widthRatio / Config.cm2px_y, 2),
cmW = Math.Round(w * 1.0 / Config.cm2px_x, 2),
cmH = Math.Round(h * 1.0 / Config.cm2px_y, 2),
i = i,
j = j,
});
}
#endregion // 打印输出信息(示例代码,根据实际情况进行修改和格式化)
// 获取输出信息
int x = (int)task.output[index];
int y = (int)task.output[index + 1];
int w = (int)task.output[index + 2];
int h = (int)task.output[index + 3];
int classId = (int)task.output[index + 4];
double confidence = Math.Round(task.output[index + 5], 2); //置信度
double contrast = Math.Round(task.output[index + 6], 3);//对比度
//y = image_hight-y-h;//转到右下角为原点
count++;
//var cmW = Math.Round(w * task.widthRatio / Config.cm2px_x, 2);
//var cmH = Math.Round(h * task.widthRatio / Config.cm2px_y, 2);
var cmW = Math.Round(w * 1.0 / Config.cm2px_x, 2);
var cmH = Math.Round(h * 1.0 / Config.cm2px_y, 2);
// 打印输出信息
//task.resultInfo += $"----{i}----col:{i % colNum}/{colNum} row:{i / colNum}/{colNum}-----------\n目标:{j + 1} 类别ID:{classId} 置信度:{confidence} 对比度:{contrast} 坐标:({x},{y})-({x + w},{y + h}) 宽高:w={w},h={h}; \n";
DefectLabelInfoList.Add(new DefectLabelInfo()
{
x = (int)task.output[index],
y = (int)task.output[index + 1],
w = (int)task.output[index + 2],
h = (int)task.output[index + 3],
classId = (int)task.output[index + 4],
confidence = Math.Round(task.output[index + 5], 2), //置信度
contrast = ContrastToPercent(Math.Round(task.output[index + 6], 3)),//对比度
//cmW = Math.Round(w * task.widthRatio / Config.cm2px_x, 2),
//cmH = Math.Round(h * task.widthRatio / Config.cm2px_y, 2),
cmW = Math.Round(w * 1.0 / Config.cm2px_x, 2),
cmH = Math.Round(h * 1.0 / Config.cm2px_y, 2),
i = i,
j = j,
});
}
#endregion
#if false #if false
for (int j = 0; j < task.output_num[i]; j++)//缺陷数 for (int j = 0; j < task.output_num[i]; j++)//缺陷数
{ {
@ -832,132 +906,206 @@ namespace LeatherApp.Device
//WarningEvent?.Invoke(DateTime.Now,WarningEnum.Low, $"缺陷小图数量:{task.lstDefectBmp.Count}"); //WarningEvent?.Invoke(DateTime.Now,WarningEnum.Low, $"缺陷小图数量:{task.lstDefectBmp.Count}");
} }
#endif #endif
} }
#region #region
liStep = 3000; liStep = 3000;
if (DefectLabelInfoList.Count >0) if (DefectLabelInfoList.Count > 0)
DefectLabelInfoList = HeBingDefect(task.bmp.Width, DefectLabelInfoList); DefectLabelInfoList = HeBingDefect(task.bmp.Width, DefectLabelInfoList);
liStep++; liStep++;
#endregion #endregion
//结果过滤 //结果过滤
#region #region
//降序排序,先得到是否有接头检出 //降序排序,先得到是否有接头检出
List<DefectLabelInfo> DefectLabelInfoListByClassID = DefectLabelInfoList.OrderByDescending(t => t.classId).ToList();//降序 List<DefectLabelInfo> DefectLabelInfoListByClassID = DefectLabelInfoList.OrderByDescending(t => t.classId).ToList();//降序
for (int q = 0; q < DefectLabelInfoListByClassID.Count; q++) for (int q = 0; q < DefectLabelInfoListByClassID.Count; q++)
{
//是否满足此产品标准
if (task.qualifiedLimitList != null && task.qualifiedLimitList.Count > 0)
{ {
qualifiedLimit = task.qualifiedLimitList.FirstOrDefault(m => m.Code == Config.getDefectCode(DefectLabelInfoListByClassID[q].classId)); //是否满足此产品标准
if (qualifiedLimit != null) if (task.qualifiedLimitList != null && task.qualifiedLimitList.Count > 0)
{ {
// 打印输出信息 qualifiedLimit = task.qualifiedLimitList.FirstOrDefault(m => m.Code == Config.getDefectCode(DefectLabelInfoListByClassID[q].classId));
task.resultInfo += $"----{DefectLabelInfoListByClassID[q].i}----col:{DefectLabelInfoListByClassID[q].i % colNum}/{colNum} row:{DefectLabelInfoListByClassID[q].i / colNum}/{colNum}-----------\n目标:{DefectLabelInfoListByClassID[q].j + 1} 类别ID:{DefectLabelInfoListByClassID[q].classId} 置信度:{DefectLabelInfoListByClassID[q].confidence} 对比度:{DefectLabelInfoListByClassID[q].contrast}\n"; if (qualifiedLimit != null)
{
// 打印输出信息
task.resultInfo += $"----{DefectLabelInfoListByClassID[q].i}----col:{DefectLabelInfoListByClassID[q].i % colNum}/{colNum} row:{DefectLabelInfoListByClassID[q].i / colNum}/{colNum}-----------\n目标:{DefectLabelInfoListByClassID[q].j + 1} 类别ID:{DefectLabelInfoListByClassID[q].classId} 置信度:{DefectLabelInfoListByClassID[q].confidence} 对比度:{DefectLabelInfoListByClassID[q].contrast}\n";
//if ((qualifiedLimit.ZXD > 0 && qualifiedLimit.ZXD > confidence) //if ((qualifiedLimit.ZXD > 0 && qualifiedLimit.ZXD > confidence)
// || (qualifiedLimit.ContrastTop + qualifiedLimit.ContrastLower > 0 && x> qualifiedLimit.ContrastLower && x < qualifiedLimit.ContrastTop) // || (qualifiedLimit.ContrastTop + qualifiedLimit.ContrastLower > 0 && x> qualifiedLimit.ContrastLower && x < qualifiedLimit.ContrastTop)
// || (qualifiedLimit.Area > 0 && qualifiedLimit.Area > cmW * cmH)) // || (qualifiedLimit.Area > 0 && qualifiedLimit.Area > cmW * cmH))
if (DefectLabelInfoListByClassID[q].confidence <= qualifiedLimit.ZXD)//confidence > qualifiedLimit.ZXD 是瑕疵 才继续判断下面的两个条件 if (DefectLabelInfoListByClassID[q].confidence <= qualifiedLimit.ZXD)//confidence > qualifiedLimit.ZXD 是瑕疵 才继续判断下面的两个条件
{
task.resultInfo += $" 置信度不满足此产品瑕疵标准,跳过! \n";
continue;
}
//下限<对比度<上限:不是瑕疵
var ContrastTotal = qualifiedLimit.ContrastTop + qualifiedLimit.ContrastLower;
if (qualifiedLimit.IsOR)
{
//if (!(
// (ContrastTotal <= 0 || (PercentToContrast(DefectLabelInfoListByClassID[q].contrast) < qualifiedLimit.ContrastLower || PercentToContrast(DefectLabelInfoListByClassID[q].contrast) > qualifiedLimit.ContrastTop))))
//{
// task.resultInfo += $" 不满足此产品瑕疵标准,跳过! \n";
// //WarningEvent?.Invoke(DateTime.Now,WarningEnum.Low, $"判断不是瑕疵类别ID:{classId} 置信度({confidence},[{qualifiedLimit.ZXD}]); isOr({qualifiedLimit.IsOR}); 面积({cmW * cmH},[{ qualifiedLimit.Area}]); 对比度({contrast},[{qualifiedLimit.ContrastLower}-{qualifiedLimit.ContrastTop}])");
// continue;
//}
}
else
{
if (!(ContrastTotal <= 0 || (PercentToContrast(DefectLabelInfoListByClassID[q].contrast) < qualifiedLimit.ContrastLower || PercentToContrast(DefectLabelInfoListByClassID[q].contrast) > qualifiedLimit.ContrastTop)))
{ {
task.resultInfo += $" 不满足此产品瑕疵标准,跳过! \n"; task.resultInfo += $" 置信度不满足此产品瑕疵标准,跳过! \n";
//WarningEvent?.Invoke(DateTime.Now,WarningEnum.Low, $"判断不是瑕疵类别ID:{classId} 置信度({confidence},[{qualifiedLimit.ZXD}]); isOr({qualifiedLimit.IsOR}); 面积({cmW * cmH},[{ qualifiedLimit.Area}]); 对比度({contrast},[{qualifiedLimit.ContrastLower}-{qualifiedLimit.ContrastTop}])");
continue; continue;
} }
//下限<对比度<上限:不是瑕疵
var ContrastTotal = qualifiedLimit.ContrastTop + qualifiedLimit.ContrastLower;
if (qualifiedLimit.IsOR)
{
//if (!(
// (ContrastTotal <= 0 || (PercentToContrast(DefectLabelInfoListByClassID[q].contrast) < qualifiedLimit.ContrastLower || PercentToContrast(DefectLabelInfoListByClassID[q].contrast) > qualifiedLimit.ContrastTop))))
//{
// task.resultInfo += $" 不满足此产品瑕疵标准,跳过! \n";
// //WarningEvent?.Invoke(DateTime.Now,WarningEnum.Low, $"判断不是瑕疵类别ID:{classId} 置信度({confidence},[{qualifiedLimit.ZXD}]); isOr({qualifiedLimit.IsOR}); 面积({cmW * cmH},[{ qualifiedLimit.Area}]); 对比度({contrast},[{qualifiedLimit.ContrastLower}-{qualifiedLimit.ContrastTop}])");
// continue;
//}
}
else
{
if (!(ContrastTotal <= 0 || (PercentToContrast(DefectLabelInfoListByClassID[q].contrast) < qualifiedLimit.ContrastLower || PercentToContrast(DefectLabelInfoListByClassID[q].contrast) > qualifiedLimit.ContrastTop)))
{
task.resultInfo += $" 不满足此产品瑕疵标准,跳过! \n";
//WarningEvent?.Invoke(DateTime.Now,WarningEnum.Low, $"判断不是瑕疵类别ID:{classId} 置信度({confidence},[{qualifiedLimit.ZXD}]); isOr({qualifiedLimit.IsOR}); 面积({cmW * cmH},[{ qualifiedLimit.Area}]); 对比度({contrast},[{qualifiedLimit.ContrastLower}-{qualifiedLimit.ContrastTop}])");
continue;
}
}
if (qualifiedLimit.Area > 0 && DefectLabelInfoListByClassID[q].cmW * DefectLabelInfoListByClassID[q].cmH < qualifiedLimit.Area)
{
task.resultInfo += $" 不满足此产品瑕疵标准面积,跳过! \n";
continue;
}
if (Config.getDefectCode(DefectLabelInfoListByClassID[q].classId) == "jietou")
haveJieTou = true;
if (haveJieTou && (Config.getDefectCode(DefectLabelInfoListByClassID[q].classId) == "hengdang"))
{
task.resultInfo += $" 判断为接头处横档,跳过! \n";
continue;
}
if (Config.getDefectCode(DefectLabelInfoListByClassID[q].classId) == "na")
{
task.resultInfo += $" 判断为正向标签na跳过 \n";
continue;
}
//WarningEvent?.Invoke(DateTime.Now,WarningEnum.Low, $"判断是瑕疵类别ID:{classId} 置信度({confidence},[{qualifiedLimit.ZXD}]); isOr({qualifiedLimit.IsOR}); 面积({cmW * cmH},[{ qualifiedLimit.Area}]); 对比度({contrast},[{qualifiedLimit.ContrastLower}-{qualifiedLimit.ContrastTop}])");
} }
if(qualifiedLimit.Area > 0 && DefectLabelInfoListByClassID[q].cmW * DefectLabelInfoListByClassID[q].cmH < qualifiedLimit.Area)
{
task.resultInfo += $" 不满足此产品瑕疵标准面积,跳过! \n";
continue;
}
if (Config.getDefectCode(DefectLabelInfoListByClassID[q].classId) == "jietou")
haveJieTou = true;
if(haveJieTou && (Config.getDefectCode(DefectLabelInfoListByClassID[q].classId) == "hengdang"))
{
task.resultInfo += $" 判断为接头处横档,跳过! \n";
continue;
}
if (Config.getDefectCode(DefectLabelInfoListByClassID[q].classId) == "na")
{
task.resultInfo += $" 判断为正向标签na跳过 \n";
continue;
}
//WarningEvent?.Invoke(DateTime.Now,WarningEnum.Low, $"判断是瑕疵类别ID:{classId} 置信度({confidence},[{qualifiedLimit.ZXD}]); isOr({qualifiedLimit.IsOR}); 面积({cmW * cmH},[{ qualifiedLimit.Area}]); 对比度({contrast},[{qualifiedLimit.ContrastLower}-{qualifiedLimit.ContrastTop}])");
} }
liStep++;//1
//打标
var point1 = new OpenCvSharp.Point((DefectLabelInfoListByClassID[q].i % colNum) * image_width + DefectLabelInfoListByClassID[q].x, (DefectLabelInfoListByClassID[q].i / colNum) * image_hight + DefectLabelInfoListByClassID[q].y);
var point2 = new OpenCvSharp.Point(point1.X + DefectLabelInfoListByClassID[q].w, point1.Y + DefectLabelInfoListByClassID[q].h);
liStep++;//2
//task.resultInfo += $" 转换到大图坐标(px)p1={point1.X},{point1.Y}; p2={point2.X},{point2.Y}\n";
Cv2.Rectangle(task.bmpTag, point1, point2, new Scalar(0.0, 0.0, 255.0), 5);//画打标点
//WarningEvent?.Invoke(DateTime.Now,WarningEnum.Low, $"保存第 {count} 行缺陷信息;");
int px = (point1.X - task.xw) > 0 ? (point1.X - task.xw) : 0;
//var cmX = Math.Round(px * task.widthRatio / Config.cm2px_x, 2);
var cmX = Math.Round((double)px / Config.cm2px_x, 2);
//var cmY = Math.Round((task.bmp.Height - point1.Y - DefectLabelInfoListByClassID[q].h) * task.widthRatio / Config.cm2px_y, 2);//外面计Y从右下角为原点
var cmY = Math.Round((task.bmp.Height - point1.Y - DefectLabelInfoListByClassID[q].h) * 1.0 / Config.cm2px_y, 2);//外面计Y从右下角为原点
liStep++;//3
//task.resultInfo += $" 转换到大图坐标(cm)[widthRatio={task.widthRatio}]x={cmX},y={cmY}; w={DefectLabelInfoList[q].cmW},h={DefectLabelInfoList[q].cmH}\n";
task.excelTable.Rows.Add($"{task.photoIndex}", cmX, cmY, DefectLabelInfoListByClassID[q].cmW, DefectLabelInfoListByClassID[q].cmH, DefectLabelInfoListByClassID[q].j + 1, DefectLabelInfoListByClassID[q].classId, DefectLabelInfoListByClassID[q].confidence, DefectLabelInfoListByClassID[q].contrast);
liStep++;//4
//切缺陷小图
//WarningEvent?.Invoke(DateTime.Now,WarningEnum.Low, $"保存第 {count} 个缺陷小图;");
int left, top, decX, decY;
decX = (DefectLabelInfoListByClassID[q].w > 236 ? 20 : 256 - DefectLabelInfoListByClassID[q].w) / 2;
decY = (DefectLabelInfoListByClassID[q].h > 236 ? 20 : 256 - DefectLabelInfoListByClassID[q].h) / 2;
left = point1.X - decX;
top = point1.Y - decY;
if (left < 0) left = 0;
if (top < 0) top = 0;
int width = DefectLabelInfoListByClassID[q].w + decX * 2;
int height = DefectLabelInfoListByClassID[q].h + decY * 2;
if (left + width > task.bmp.Width - 1) width = task.bmp.Width - left - 1;
if (top + height > task.bmp.Height - 1) height = task.bmp.Height - top - 1;
liStep++;//5
Rect roi = new Rect(left, top, width, height);
liStep++;//6
if (height < 1 || width < 1)
{
//task.resultInfo += $" 打标到大图坐标Rect(px)left={left},top={top}; width={width},height={height}\n";
//task.resultInfo += $" test point1.Y={point1.Y},h={DefectLabelInfoList[q].h}; top={top},mat.Height={task.bmp.Height}\n================\n";
WarningEvent?.Invoke(DateTime.Now, WarningEnum.Normal, task.resultInfo);
}
//保存
//string filename = $"{Config.appBasePath}\\temp\\{task.tag}\\{task.tag}_X{mmX.ToString()}_Y{mmY.ToString()}_W{mmW.ToString()}_H{mmH.ToString()}_目标{j + 1}_类别{classId}_置信度{confidence}.bmp";
//OpenCvSharp.Extensions.BitmapConverter.ToBitmap(new Mat(task.bmp, roi)).Save(filename, ImageFormat.Jpeg);
task.lstDefectBmp.Add(new Mat(task.bmpTag, roi).Clone());
liStep++;//7
} }
liStep++;//1 #endregion
//打标
var point1 = new OpenCvSharp.Point((DefectLabelInfoListByClassID[q].i % colNum) * image_width + DefectLabelInfoListByClassID[q].x, (DefectLabelInfoListByClassID[q].i / colNum) * image_hight + DefectLabelInfoListByClassID[q].y);
var point2 = new OpenCvSharp.Point(point1.X + DefectLabelInfoListByClassID[q].w, point1.Y + DefectLabelInfoListByClassID[q].h);
liStep++;//2
//task.resultInfo += $" 转换到大图坐标(px)p1={point1.X},{point1.Y}; p2={point2.X},{point2.Y}\n";
Cv2.Rectangle(task.bmpTag, point1, point2, new Scalar(0.0, 0.0, 255.0), 5);//画打标点
//WarningEvent?.Invoke(DateTime.Now,WarningEnum.Low, $"保存第 {count} 行缺陷信息;");
int px = (point1.X - task.xw) > 0 ? (point1.X - task.xw) : 0;
//var cmX = Math.Round(px * task.widthRatio / Config.cm2px_x, 2);
var cmX = Math.Round((double)px / Config.cm2px_x, 2);
//var cmY = Math.Round((task.bmp.Height - point1.Y - DefectLabelInfoListByClassID[q].h) * task.widthRatio / Config.cm2px_y, 2);//外面计Y从右下角为原点
var cmY = Math.Round((task.bmp.Height - point1.Y - DefectLabelInfoListByClassID[q].h) * 1.0 / Config.cm2px_y, 2);//外面计Y从右下角为原点
liStep++;//3
//task.resultInfo += $" 转换到大图坐标(cm)[widthRatio={task.widthRatio}]x={cmX},y={cmY}; w={DefectLabelInfoList[q].cmW},h={DefectLabelInfoList[q].cmH}\n";
task.excelTable.Rows.Add($"{task.photoIndex}", cmX, cmY, DefectLabelInfoListByClassID[q].cmW, DefectLabelInfoListByClassID[q].cmH, DefectLabelInfoListByClassID[q].j + 1, DefectLabelInfoListByClassID[q].classId, DefectLabelInfoListByClassID[q].confidence, DefectLabelInfoListByClassID[q].contrast);
liStep++;//4
//切缺陷小图
//WarningEvent?.Invoke(DateTime.Now,WarningEnum.Low, $"保存第 {count} 个缺陷小图;");
int left, top, decX, decY;
decX = (DefectLabelInfoListByClassID[q].w > 236 ? 20 : 256 - DefectLabelInfoListByClassID[q].w) / 2;
decY = (DefectLabelInfoListByClassID[q].h > 236 ? 20 : 256 - DefectLabelInfoListByClassID[q].h) / 2;
left = point1.X - decX;
top = point1.Y - decY;
if (left < 0) left = 0;
if (top < 0) top = 0;
int width = DefectLabelInfoListByClassID[q].w + decX * 2;
int height = DefectLabelInfoListByClassID[q].h + decY * 2;
if (left + width > task.bmp.Width - 1) width = task.bmp.Width - left - 1;
if (top + height > task.bmp.Height - 1) height = task.bmp.Height - top - 1;
liStep++;//5
Rect roi = new Rect(left, top, width, height);
liStep++;//6
if (height < 1 || width < 1)
{
//task.resultInfo += $" 打标到大图坐标Rect(px)left={left},top={top}; width={width},height={height}\n";
//task.resultInfo += $" test point1.Y={point1.Y},h={DefectLabelInfoList[q].h}; top={top},mat.Height={task.bmp.Height}\n================\n";
WarningEvent?.Invoke(DateTime.Now, WarningEnum.Normal, task.resultInfo);
}
//保存
//string filename = $"{Config.appBasePath}\\temp\\{task.tag}\\{task.tag}_X{mmX.ToString()}_Y{mmY.ToString()}_W{mmW.ToString()}_H{mmH.ToString()}_目标{j + 1}_类别{classId}_置信度{confidence}.bmp";
//OpenCvSharp.Extensions.BitmapConverter.ToBitmap(new Mat(task.bmp, roi)).Save(filename, ImageFormat.Jpeg);
task.lstDefectBmp.Add(new Mat(task.bmpTag, roi).Clone());
liStep++;//7
} }
#endregion else
liStep = 99; {
stopwatch.Restart();
//打标
var defectinfo = task.hv_defectinfo.ToOArr();
List<DefectLabelInfo> DefectLabelInfoList = new List<DefectLabelInfo>();
for (int i = 0; i < task.object_num; i++)
{
liStep = 23 + i;
#region
int index = i * 6;
// 打印输出信息(示例代码,根据实际情况进行修改和格式化)
// 获取输出信息
int x = (int)defectinfo[index].ToInt();
int y = (int)defectinfo[index + 1].ToInt();
int w = (int)defectinfo[index + 2].ToInt();
int h = (int)defectinfo[index + 3].ToInt();
int classId = -99;//(int)defectinfo[index + 4].ToInt();
double confidence = Math.Round(defectinfo[index + 5].ToDouble(), 2); //置信度
int px = x;
var cmX = Math.Round(px * task.widthRatio / Config.cm2px_x, 2);
var cmY = Math.Round((task.bmp.Height - y - h) * task.widthRatio / Config.cm2px_y, 2);//外面计Y从右下角为原点
DefectLabelInfoList.Add(new DefectLabelInfo()
{
x = x,
y = y,
w = w,
h = h,
classId = classId,
confidence = confidence, //置信度
cmW = Math.Round(w * task.widthRatio / Config.cm2px_x, 2),
cmH = Math.Round(h * task.widthRatio / Config.cm2px_y, 2),
i = i,
j = i,
});
//y = image_hight-y-h;//转到右下角为原点
task.excelTable.Rows.Add($"{task.photoIndex}", cmX, cmY,
Math.Round(w * task.widthRatio / Config.cm2px_x, 2), Math.Round(h * task.widthRatio / Config.cm2px_y, 2),
i, classId, confidence, 0);
int penLine = 20;
//打标
var point1 = new OpenCvSharp.Point(x, y);
var point2 = new OpenCvSharp.Point(point1.X + w + penLine / 2, point1.Y + h + penLine / 2);
Cv2.Rectangle(task.bmpTag, point1, point2, new Scalar(0.0, 0.0, 255.0), penLine);//画打标点
//切小图
int left, top, decX, decY;
int tdecX = (w / 2) / 2;
int tdecY = w / h > 4 ? w / 8 : (h / 1) / 2;
decX = (w > 236 ? tdecX : 256 - w) / 2;
decY = (h > 236 ? tdecY : 256 - h) / 2;
left = point1.X - decX;
top = point1.Y - decY;
if (left < 0) left = 0;
if (top < 0) top = 0;
int width = w + decX * 2;
int height = h + decY * 2;
if (left + width > task.bmp.Width - 1) width = task.bmp.Width - left - 1;
if (top + height > task.bmp.Height - 1) height = task.bmp.Height - top - 1;
Rect roi = new Rect(left, top, width, height);
task.lstDefectBmp.Add(new Mat(task.bmpTag, roi).Clone());
#endregion
}
}
liStep = 99;
stopwatch.Stop(); stopwatch.Stop();
task.stopwatch[3] = stopwatch.ElapsedMilliseconds; task.stopwatch[3] = stopwatch.ElapsedMilliseconds;
@ -1081,6 +1229,14 @@ namespace LeatherApp.Device
public long[] stopwatch = new long[4]; public long[] stopwatch = new long[4];
public int xw; public int xw;
//传统算法使用
public HObject ho_Img = new HObject();
public HObject ho_imgG = new HObject();
public HObject ho_ImageResult3 = new HObject();
public HObject ho_ImageSub = new HObject();
public HTuple hv_RES, hv_gauss_filter1, hv_gauss_filter2, hv_Energy_value, hv_Region_S_value, hv_class, hv_defectinfo;
public int object_num = 0;
} }
public void add(DefectTask task) public void add(DefectTask task)

View File

@ -59,6 +59,15 @@
<Reference Include="ExcelNumberFormat, Version=1.1.0.0, Culture=neutral, PublicKeyToken=23c6f5d73be07eca, processorArchitecture=MSIL"> <Reference Include="ExcelNumberFormat, Version=1.1.0.0, Culture=neutral, PublicKeyToken=23c6f5d73be07eca, processorArchitecture=MSIL">
<HintPath>..\packages\ExcelNumberFormat.1.1.0\lib\net20\ExcelNumberFormat.dll</HintPath> <HintPath>..\packages\ExcelNumberFormat.1.1.0\lib\net20\ExcelNumberFormat.dll</HintPath>
</Reference> </Reference>
<Reference Include="halcondotnet">
<HintPath>Dll\halcondotnet.dll</HintPath>
</Reference>
<Reference Include="hdevenginedotnet">
<HintPath>Dll\hdevenginedotnet.dll</HintPath>
</Reference>
<Reference Include="HZH_Controls">
<HintPath>..\..\..\..\..\版博士\源码\V2.0\halftoneproject-master\BanBoShi\Dlls\HZH_Controls.dll</HintPath>
</Reference>
<Reference Include="IKapBoardClassLibrary"> <Reference Include="IKapBoardClassLibrary">
<HintPath>C:\Program Files\I-TEK OptoElectronics\IKapLibrary\Dll\C#\IKapBoardClassLibrary.dll</HintPath> <HintPath>C:\Program Files\I-TEK OptoElectronics\IKapLibrary\Dll\C#\IKapBoardClassLibrary.dll</HintPath>
</Reference> </Reference>
@ -86,6 +95,9 @@
<Reference Include="OpenCvSharp.Extensions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6adad1e807fea099, processorArchitecture=MSIL"> <Reference Include="OpenCvSharp.Extensions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6adad1e807fea099, processorArchitecture=MSIL">
<HintPath>..\packages\OpenCvSharp4.Extensions.4.7.0.20230115\lib\net48\OpenCvSharp.Extensions.dll</HintPath> <HintPath>..\packages\OpenCvSharp4.Extensions.4.7.0.20230115\lib\net48\OpenCvSharp.Extensions.dll</HintPath>
</Reference> </Reference>
<Reference Include="PG_Detect">
<HintPath>Dll\PG_Detect.dll</HintPath>
</Reference>
<Reference Include="S7.Net, Version=0.20.0.0, Culture=neutral, PublicKeyToken=d5812d469e84c693, processorArchitecture=MSIL"> <Reference Include="S7.Net, Version=0.20.0.0, Culture=neutral, PublicKeyToken=d5812d469e84c693, processorArchitecture=MSIL">
<HintPath>..\packages\S7netplus.0.20.0\lib\net462\S7.Net.dll</HintPath> <HintPath>..\packages\S7netplus.0.20.0\lib\net462\S7.Net.dll</HintPath>
</Reference> </Reference>

View File

@ -64,6 +64,9 @@ namespace LeatherApp.Page
private bool init_Cloud; private bool init_Cloud;
// //
private bool _residueWarnningLenStop; private bool _residueWarnningLenStop;
//判断是否已经扫码获取erp信息
private bool _IsGetErpCode = false;
public FHome(FProductInfo frm) public FHome(FProductInfo frm)
{ {
InitializeComponent(); InitializeComponent();
@ -804,6 +807,8 @@ namespace LeatherApp.Page
// //
pStopWatch.Restart(); pStopWatch.Restart();
errCode = 19; errCode = 19;
//扫码成功
_IsGetErpCode = true;
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -1590,6 +1595,11 @@ namespace LeatherApp.Page
//System.GC.Collect(); //System.GC.Collect();
} }
} }
/// <summary>
/// 处理完成回调
/// </summary>
/// <param name="res"></param>
private void callBackDefectEvent(Device.DefectLib.DefectTask res) private void callBackDefectEvent(Device.DefectLib.DefectTask res)
{ {
{ {
@ -1791,7 +1801,9 @@ namespace LeatherApp.Page
} }
} }
} }
/// <summary>
/// 数据保存状态
/// </summary>
private bool _isDefect = false; private bool _isDefect = false;
private async void saveCurrRecord(int key, string batchId, string reelId, double erpLen) private async void saveCurrRecord(int key, string batchId, string reelId, double erpLen)
{ {
@ -1892,6 +1904,14 @@ namespace LeatherApp.Page
//启动 //启动
private void btnStart_Click(object sender, EventArgs e) private void btnStart_Click(object sender, EventArgs e)
{ {
if(!_IsGetErpCode)
{
AddTextEvent(DateTime.Now, "启动", "还未扫码获取检测信息!", WarningEnum.Low);
return;
}
devContainer.devCamer1.resetScanIndex();
devContainer.devCamer2.resetScanIndex();
AddTextEvent(DateTime.Now,"启动", "下发启动指令..."); AddTextEvent(DateTime.Now,"启动", "下发启动指令...");
if (!Config.StopPLC) if (!Config.StopPLC)
this.devContainer.devPlc.runDev(); this.devContainer.devPlc.runDev();
@ -2042,11 +2062,13 @@ namespace LeatherApp.Page
pStopWatch.Stop(); pStopWatch.Stop();
this.btnStart.Enabled = true; this.btnStart.Enabled = true;
this.btnEnd.Enabled = this.btnPause.Enabled = false;//这里有问题应该是devPlc回调设置 this.btnEnd.Enabled = this.btnPause.Enabled = false;//这里有问题应该是devPlc回调设置
_IsGetErpCode = false;
} }
else else
{ {
AddTextEvent(DateTime.Now, "结束验布", "无数据结束验布!"); AddTextEvent(DateTime.Now, "结束验布", "无数据结束验布!");
_isDefect = false; _isDefect = false;
_IsGetErpCode = false;
} }
} }
private void lstboxLog_DrawItem(object sender, DrawItemEventArgs e) private void lstboxLog_DrawItem(object sender, DrawItemEventArgs e)

View File

@ -1,10 +1,12 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xaml; using System.Xaml;
using DocumentFormat.OpenXml.Vml; using DocumentFormat.OpenXml.Vml;
using HalconDotNet;
using OpenCvSharp; using OpenCvSharp;
using OpenCvSharp.XImgProc; using OpenCvSharp.XImgProc;
namespace LeatherApp.Utils namespace LeatherApp.Utils
@ -1241,5 +1243,155 @@ namespace LeatherApp.Utils
return result; return result;
} }
#region MatToHalcon
public static void MatToHObject(Mat imgMat, out HObject imgHOject)
{
int ImageWidth = imgMat.Width;
int ImageHeight = imgMat.Height;
int channel = imgMat.Channels();
long size = ImageWidth * ImageHeight * channel;
int col_byte_num = ImageWidth * channel;
byte[] rgbValues = new byte[size];
unsafe
{
for (int i = 0; i < ImageHeight; i++)
{
IntPtr c = imgMat.Ptr(i);
// 一行一行将mat 像素复制到byte[]
Marshal.Copy(c, rgbValues, i * col_byte_num, col_byte_num);
}
void* p;
IntPtr ptr;
fixed (byte* pc = rgbValues)
{
p = (void*)pc;
ptr = new IntPtr(p);
}
if (channel == 1)
{
HOperatorSet.GenImage1(out imgHOject, "byte", ImageWidth, ImageHeight, ptr);
}
else
{
HOperatorSet.GenImageInterleaved(out imgHOject, ptr, "bgr", ImageWidth, ImageHeight, 0, "byte", 0, 0, 0, 0, -1, 0);
}
}
}
#if false
/// <summary>
/// 把OpenCV图像转换到Halcon图像
/// </summary>
/// <param name="mImage">OpenCV图像_Mat</param>
/// <returns>Halcon图像_HObject</returns>
public HObject MatToHImage(Mat mImage)
{
try
{
HObject hImage;
int matChannels = 0; // 通道数
Type matType = null;
int width, height; // 宽,高
width = height = 0; // 宽,高初始化
// 获取通道数
matChannels = mImage.Channels();
if (matChannels == 0)
{
return null;
}
if (matChannels == 1) // 单通道
{
IntPtr ptr; // 灰度图通道
Mat[] mats = mImage.Split();
// 改自Mat.GetImagePointer1(mImage, out ptr, out matType, out width, out height); // ptr=2157902018096 cType=byte width=830 height=822
ptr = mats[0].Data; // 取灰度图值
matType = mImage.GetType(); // byte
height = mImage.Rows; // 高
width = mImage.Cols; // 宽
// 改自hImage = new HObject(new OpenCvSharp.Size(width, height), MatType.CV_8UC1, new Scalar(0));
byte[] dataGrayScaleImage = new byte[width * height]; //Mat dataGrayScaleImage = new Mat(new OpenCvSharp.Size(width, height), MatType.CV_8UC1);
unsafe
{
fixed (byte* ptrdata = dataGrayScaleImage)
{
#region
//for (int i = 0; i < height; i++)
//{
// CopyMemory((IntPtr)(ptrdata + width * i), new IntPtr((long)ptr + width * i), width);
//}
#endregion
CopyMemory((IntPtr)ptrdata, new IntPtr((long)ptr), width * height);
HOperatorSet.GenImage1(out hImage, "byte", width, height, (IntPtr) ptrdata);
}
}
return hImage;
}
else if (matChannels == 3) // 三通道
{
IntPtr ptrRed; // R通道图
IntPtr ptrGreen; // G通道图
IntPtr ptrBlue; // B通道图
Mat[] mats = mImage.Split();
ptrRed = mats[0].Data; // 取R通道值
ptrGreen = mats[1].Data; // 取G通道值
ptrBlue = mats[2].Data; // 取B通道值
matType = mImage.GetType(); // 类型
height = mImage.Rows; // 高
width = mImage.Cols; // 宽
// 改自hImage = new HObject(new OpenCvSharp.Size(width, height), MatType.CV_8UC1, new Scalar(0));
byte[] dataRed = new byte[width * height]; //Mat dataGrayScaleImage = new Mat(new OpenCvSharp.Size(width, height), MatType.CV_8UC1);
byte[] dataGreen = new byte[width * height];
byte[] dataBlue = new byte[width * height];
unsafe
{
fixed (byte* ptrdataRed = dataRed, ptrdataGreen = dataGreen, ptrdataBlue = dataBlue)
{
#region
//HImage himg = new HImage("byte", width, height, (IntPtr)ptrdataRed);
//for (int i = 0; i < height; i++)
//{
// CopyMemory((IntPtr)(ptrdataRed + width * i), new IntPtr((long)ptrRed + width * i), width);
// CopyMemory((IntPtr)(ptrdataGreen + width * i), new IntPtr((long)ptrGreen + width * i), width);
// CopyMemory((IntPtr)(ptrdataBlue + width * i), new IntPtr((long)ptrBlue + width * i), width);
//}
#endregion
CopyMemory((IntPtr)ptrdataRed, new IntPtr((long)ptrRed), width * height); // 复制R通道
CopyMemory((IntPtr)ptrdataGreen, new IntPtr((long)ptrGreen), width * height); // 复制G通道
CopyMemory((IntPtr)ptrdataBlue, new IntPtr((long)ptrBlue), width * height); // 复制B通道
HOperatorSet.GenImage3(out hImage, "byte", width, height, (IntPtr)ptrdataRed, (IntPtr)ptrdataGreen, (IntPtr)ptrdataBlue); // 合成
}
}
return hImage;
}
else
{
return null;
}
}
catch (Exception ex)
{
throw ex;
}
}
#endif
#endregion
} }
} }

View File

@ -1 +1 @@
{"Direction":0,"IN_OP_SHOW":["XXXX XXXL","XXXX XXXX","XXXX XXXX","XXXX XXXX"],"IN_Waiting_Timeout":0,"OUT_OP_SHOW":["XXXX XXXH","XXXX XXXX","XXXX XXXX","XXXX XXXX"],"SleepPre":0,"SleepLater":0,"AsynRun":false,"Disable":false} {"Direction":0,"IN_OP_SHOW":["XXXX XXXH","XXXX XXXX","XXXX XXXX","XXXX XXXX"],"IN_Waiting_Timeout":0,"OUT_OP_SHOW":["XXXX XXXH","XXXX XXXX","XXXX XXXX","XXXX XXXX"],"SleepPre":0,"SleepLater":0,"AsynRun":false,"Disable":false}