Eyemlib.cs 13.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace AOI
{
    public class Eyemlib
    {

		public static (Bitmap,EyemImage,bool) ExtractPCB(Bitmap bitmap,RectangleF rect) {

			if (rect.IsEmpty)
			{ 
			
			}

			var image2 = eyemCvtToEyemImage(bitmap);
			EyemRect eyemRect = new EyemRect()
			{
				iXs = (int)rect.X,
				iYs = (int)rect.Y,
				iWidth = (int)rect.Width,
				iHeight = (int)rect.Height
			};
			try
			{
				eyemAOIPreprocessingForTSAV(image2, eyemRect, out EyemImage tpDstImg);
				eyemImageFree(ref image2);
				var newbmp = eyemCvtToBitmap(tpDstImg);
				eyemImageFree(ref tpDstImg);
				return (newbmp, tpDstImg, true);
			}
			catch {
				return (bitmap, image2, false);
			}
			/*
			//ShowEyemImage(image2);
			//预处理部分
			EyemHSVModel tpHsvModel = new EyemHSVModel();
			double dpRangeL_R = ConfigHelper.Config.Get("dpRangeL_R", 60d);
			double dpRangeL_G = ConfigHelper.Config.Get("dpRangeL_G", 56d);
			double dpRangeL_B = ConfigHelper.Config.Get("dpRangeL_B", 50d);

			double dpRangeU_R = ConfigHelper.Config.Get("dpRangeU_R", 80d);
			double dpRangeU_G = ConfigHelper.Config.Get("dpRangeU_G", 255d);
			double dpRangeU_B = ConfigHelper.Config.Get("dpRangeU_B", 255d);
			tpHsvModel.dpRangeL = new double[] { dpRangeL_R, dpRangeL_G, dpRangeL_B };
			tpHsvModel.dpRangeU = new double[] { dpRangeU_R, dpRangeU_G, dpRangeU_B };
			tpHsvModel.dpRangeLExt = new double[] { 0, 0, 0 };
			tpHsvModel.dpRangeUExt = new double[] { 0, 0, 0 };
			EyemImage tpMask;
			eyemBinThresholdC(image2, tpHsvModel, out tpMask);
			var bmp1 = eyemCvtToBitmap(tpMask);
			bmp1.Save("\\tpMask.bmp");
			bmp1.Dispose();
			//ShowEyemImage(tpMask);
			//预处理提取出PCB板
			var flag = eyemAOIPreprocessingForTSAV(image2, tpMask, out EyemImage tpDstImg);
			//showEyemImage(tpDstImg);

			var bmp = eyemCvtToBitmap(tpDstImg);
			eyemImageFree(ref tpMask);
			//eyemImageFree(ref tpDstImg);
			return (bmp,tpDstImg);*/
		}/*
		public static EyemImage MakeTemplate(string file)
		{
			eyemImageRead(file, -1, out EyemImage image2);
			//ShowEyemImage(image2);
			//预处理部分
			EyemHSVModel tpHsvModel = new EyemHSVModel();
			tpHsvModel.dpRangeL = new double[] { 35, 60, 20 }; tpHsvModel.dpRangeU = new double[] { 100, 255, 255 };
			tpHsvModel.dpRangeLExt = new double[] { 0, 0, 0 }; tpHsvModel.dpRangeUExt = new double[] { 0, 0, 0 };
			EyemImage tpMask;
			eyemBinThresholdC(image2, tpHsvModel, out tpMask);
			//ShowEyemImage(tpMask);
			//预处理提取出PCB板
			var flag = eyemAOIPreprocessingForTSAV(image2, tpMask, out EyemImage tpDstImg);
			//ShowEyemImage(tpDstImg);

			var bmp = eyemCvtToBitmap(tpDstImg);
			eyemImageFree(ref tpMask);
			eyemImageFree(ref image2);
			return tpDstImg;
		}*/
		public static void ShowEyemImage(EyemImage eyemImage) {
			eyemNamedWindow("test");
			eyemImshow("test", eyemImage);
			eyemWaitkey();
		}

		#region 结构体
		// 图像信息
		[StructLayout(LayoutKind.Sequential)]
		public struct EyemImage
		{
			public IntPtr vpImage;                     // 地址
			public int iWidth;                         // 图像内存 x 方向大小
			public int iHeight;                        // 图像内存 y 方向大小
			public int iDepth;                         // 图像位深度(详见说明)
			public int iChannels;                      // 图像通道数
		}

		// 矩形定义
		[StructLayout(LayoutKind.Sequential)]
		public struct EyemRect
		{
			public int iXs;                            // 起始点(左上角) x 坐标
			public int iYs;                            // 起始点(左上角) y 坐标
			public int iWidth;                         // x 方向大小(宽度)
			public int iHeight;                        // y 方向大小(高度)
		}

		[StructLayout(LayoutKind.Sequential)]
		public struct EyemHSVModel
		{
			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
			public double[] dpRangeL, dpRangeU;        // 提取下限,提取上限[H S V]
			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
			public double[] dpRangeLExt, dpRangeUExt;  // 额外提取下限,额外提取上限(针对处于跨模型颜色,比如红色)[H S V]
		}// 用于HSV颜色模型分割(H(0-180)、S(0-255)、V(0-255))

		// 模板匹配
		[StructLayout(LayoutKind.Sequential)]
		public struct EyemTargetMatch
		{
			public float fCenterX;
			public float fCenterY;
			public float fMatchScore;
			public float fMatchAngle;
		}
		#endregion


		/// <summary>
		/// 彩色图像分割
		/// </summary>
		/// <param name="tpImage">图像</param>
		/// <param name="ipRangeL">下限[0,0,0]</param>
		/// <param name="ipRangeU">上限[255,255,255]</param>
		/// <param name="tpDstImg">结果</param>
		/// <returns></returns>
		[DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
		public static extern int eyemBinThresholdC(EyemImage tpImage, EyemHSVModel tpHSVModel, out EyemImage tpDstImg);

		/// <summary>
		/// 拷贝指定位置的图像
		/// </summary>
		/// <param name="tpImage">图像</param>
		/// <param name="tpRoi">位置区域</param>
		/// <param name="tpDstImg">结果</param>
		/// <returns></returns>
		[DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
		public static extern int eyemCopyRegion(EyemImage tpImage, EyemRect tpRoi, out EyemImage tpDstImg);


		/// <summary>
		/// 统计非零像素数量
		/// </summary>
		/// <param name="tpImage">图像</param>
		/// <returns>非零像素个数</returns>
		[DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
		public static extern int eyemCountNonZero(EyemImage tpImage);

		/// <summary>
		/// 制作NCC模板
		/// </summary>
		/// <param name="tpImage">图像</param>
		/// <param name="iMinReduceArea">建立金字塔层数,小图大值,大图小值,默认256</param>
		/// <returns></returns>
		[DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
		public static extern int eyemMakeNCCModel(EyemImage tpImage, int iMinReduceArea);

		//寻找模板
		[DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
		public static extern int eyemFindNCCModel(EyemImage tpImage, double dToleranceAngle, int iNumMatches, double dMaxOverlap, double dScore, bool bDrawResult, IntPtr tpResults, out EyemImage tpDstImg);

		//创建窗口
		[DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
		public static extern void eyemNamedWindow(string winName);

		//在创建窗口上显示图像
		[DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
		public static extern void eyemImshow(string winName, EyemImage tpImage);

		//冻结窗口
		[DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
		public static extern void eyemWaitkey();


		//插件机图像预处理
		[DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
		public static extern int eyemAOIPreprocessingForTSAV(EyemImage tpImage, EyemRect tpRoi, out EyemImage tpDstImg);
		//读取图像
		[DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
		public static extern int eyemImageRead(string filename, int iFalgs, out EyemImage ucpImage);

		//释放图像资源
		[DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
		public static extern void eyemImageFree(ref EyemImage eyemImage);
		/// <summary>
		/// 从进程中的非托管内存分配指定长度的内存
		/// </summary>
		/// <param name="cb">长度</param>
		/// <returns>地址</returns>
		[DllImport("eyemLib.dll", CallingConvention = CallingConvention.Cdecl)]
		public static extern IntPtr eyemMallocMemBlock(int cb);
		/// <summary>
		/// 释放从非托管内存中分配的内存
		/// </summary>
		/// <param name="block">地址</param>
		[DllImport("eyemLib.dll", CallingConvention = CallingConvention.Cdecl)]
		public static extern void eyemFreeMemBlock(IntPtr block);
		public static EyemImage eyemCvtToEyemImage2(Bitmap bitmap)
		{
			EyemImage tpImage = new EyemImage();
			//锁定数据区
			BitmapData bd = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
				ImageLockMode.ReadOnly, bitmap.PixelFormat);

			switch (bitmap.PixelFormat)
			{
				case PixelFormat.Format8bppIndexed:
					tpImage.iChannels = 1;
					break;
				case PixelFormat.Format24bppRgb:
					tpImage.iChannels = 3;
					break;
				case PixelFormat.Format32bppArgb:
					tpImage.iChannels = 4;
					break;
				default:
					throw new Exception("Image formats are not supported");
			}
			//仅支持8位
			tpImage.iDepth = 0;
			//图像尺寸
			tpImage.iWidth = bitmap.Width; tpImage.iHeight = bitmap.Height;
			//分配内存
			tpImage.vpImage = eyemMallocMemBlock(bd.Stride * bd.Height);
			try
			{
				int pd = ((tpImage.iWidth * tpImage.iChannels) + 3) / 4 * 4;
				long bytesToCopy = tpImage.iWidth * tpImage.iChannels;
				for (int y = 0; y < tpImage.iHeight; y++)
				{
					long offsetSrc = y * pd;
					long offsetDst = y * tpImage.iWidth * tpImage.iChannels;
                    unsafe
					{
						Buffer.MemoryCopy((byte*)(bd.Scan0.ToPointer()) + offsetSrc, (byte*)(tpImage.vpImage.ToPointer()) + offsetDst, bytesToCopy, bytesToCopy);
					}
				}
			}
			finally
			{
				bitmap.UnlockBits(bd);
			}
			return tpImage;
		}
		public static EyemImage eyemCvtToEyemImage(Bitmap bitmap)
		{
			EyemImage tpImage = new EyemImage();
			//锁定数据区
			BitmapData bd = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
				ImageLockMode.ReadOnly, bitmap.PixelFormat);

			switch (bitmap.PixelFormat)
			{
				case PixelFormat.Format8bppIndexed:
					tpImage.iChannels = 1;
					break;
				case PixelFormat.Format24bppRgb:
					tpImage.iChannels = 3;
					break;
				case PixelFormat.Format32bppArgb:
					tpImage.iChannels = 4;
					break;
				default:
					throw new Exception("Image formats are not supported");
			}
			//仅支持8位
			tpImage.iDepth = 0;
			//图像尺寸
			tpImage.iWidth = bitmap.Width; tpImage.iHeight = bitmap.Height;
			//分配内存(释放不是用eyemImageFree,用Marshal.FreeHGlobal(tpImage.vpImage)),谁分配谁释放
			tpImage.vpImage = Marshal.AllocHGlobal(bd.Stride * bd.Height);
			try
			{
				int pd = ((tpImage.iWidth * tpImage.iChannels) + 3) / 4 * 4;
				long bytesToCopy = tpImage.iWidth * tpImage.iChannels;
				for (int y = 0; y < tpImage.iHeight; y++)
				{
					long offsetSrc = y * pd;
					long offsetDst = y * tpImage.iWidth * tpImage.iChannels;
					unsafe
					{
						Buffer.MemoryCopy((byte*)(bd.Scan0.ToPointer()) + offsetSrc, (byte*)(tpImage.vpImage.ToPointer()) + offsetDst, bytesToCopy, bytesToCopy);
					}
				}
			}
			finally
			{
				bitmap.UnlockBits(bd);
			}
			return tpImage;
		}
		public static List<T> eyemIntPtr2StructArray<T>(IntPtr hGlobal, int Size)
		{
			if (hGlobal == IntPtr.Zero)
				throw new ArgumentNullException(typeof(IntPtr).Name.ToString());
			//
			List<T> tpArray = new List<T>();
			for (int index = 0; index < Size; index++)
			{
				IntPtr lpArray = new IntPtr(checked(hGlobal.ToInt64() + index * Marshal.SizeOf(typeof(T))));
				var structure = Marshal.PtrToStructure<T>(lpArray);
				tpArray.Add(structure);
			}
			return tpArray;
		}
		#region EyemImage转换成Bitmap
		public static Bitmap eyemCvtToBitmap(EyemImage tpImage)
		{
			if (tpImage.vpImage == IntPtr.Zero)
				throw new ArgumentNullException("图像不存在");

			if (tpImage.iDepth != 0)
				throw new ArgumentException("图像必须是8位无符号整型");

			PixelFormat format;

			switch (tpImage.iChannels)
			{
				case 1:
					format = PixelFormat.Format8bppIndexed;
					break;
				case 3:
					format = PixelFormat.Format24bppRgb;
					break;
				case 4:
					format = PixelFormat.Format32bppArgb;
					break;
				default:
					return null;
			}

			Bitmap bitmap = new Bitmap(tpImage.iWidth, tpImage.iHeight, format);

			//对于输出灰度图像
			if (format == PixelFormat.Format8bppIndexed)
			{
				ColorPalette palette = bitmap.Palette;
				for (int i = 0; i < 256; i++)
				{
					palette.Entries[i] = Color.FromArgb(i, i, i);
				}
				bitmap.Palette = palette;
			}

			//锁定数据区
			BitmapData bd = bitmap.LockBits(new Rectangle(0, 0, tpImage.iWidth, tpImage.iHeight),
				ImageLockMode.WriteOnly, format);

			try
			{
				int pd = ((tpImage.iWidth * tpImage.iChannels) + 3) / 4 * 4;

				long bytesToCopy = tpImage.iWidth * tpImage.iChannels;

				for (int y = 0; y < tpImage.iHeight; y++)
				{
					long offsetSrc = (y * tpImage.iWidth * tpImage.iChannels);
					long offsetDst = (y * pd);
                    unsafe
					{
						Buffer.MemoryCopy((byte*)(tpImage.vpImage.ToPointer()) + offsetSrc, (byte*)(bd.Scan0.ToPointer()) + offsetDst, bytesToCopy, bytesToCopy);
					}
				}
			}
			finally
			{
				bitmap.UnlockBits(bd);
			}
			return bitmap;
		}
		#endregion
		public static T DeepClone<T>(T _object)
		{
			T dstobject;
			using (MemoryStream mStream = new MemoryStream())
			{
				BinaryFormatter bf = new BinaryFormatter();
				bf.Serialize(mStream, _object);
				mStream.Seek(0, SeekOrigin.Begin);//指定当前流的位置为流的开头。
				dstobject = (T)bf.Deserialize(mStream);
				mStream.Close();
			}
			return dstobject;
		}
	}
}