Commit 39196f16 LN

取图片修改

1 个父辈 77cdfaaf
......@@ -45,9 +45,9 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\增广夹爪\log4net.dll</HintPath>
</Reference>
<Reference Include="MvCameraControl.Net, Version=2.4.1.2, Culture=neutral, processorArchitecture=MSIL">
<Reference Include="MvCameraControl.Net, Version=3.2.0.2, Culture=neutral, PublicKeyToken=52fddfb3f94be800, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\dll\MvCameraControl.Net.dll</HintPath>
<HintPath>..\dll\MvCameraControl.Net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
......
......@@ -2,7 +2,10 @@
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using HalconDotNet;
using MvCamCtrl.NET;
......@@ -22,45 +25,54 @@ namespace CodeLibrary
public override void Close(int index)
{
if (cameraCurr[index] != null)
lock (cameraCurr)
{
_isOpen[index] = false;
cameraCurr[index].MV_CC_CloseDevice_NET();
cameraCurr[index].MV_CC_DestroyDevice_NET();
cameraCurr[index] = null;
if (cameraCurr[index] != null)
{
_isOpen[index] = false;
cameraCurr[index].MV_CC_CloseDevice_NET();
cameraCurr[index].MV_CC_DestroyDevice_NET();
cameraCurr[index] = null;
}
}
}
public override void Close(string name)
{
int index = cameraName.FindIndex(s => s == name);
if (index == -1)
{
_errInfo = "Not find";
return;
}
if (cameraCurr[index] != null)
lock (cameraCurr)
{
_isOpen[index] = false;
cameraCurr[index].MV_CC_CloseDevice_NET();
cameraCurr[index].MV_CC_DestroyDevice_NET();
cameraCurr[index] = null;
int index = cameraName.FindIndex(s => s == name);
if (index == -1)
{
_errInfo = "Not find";
return;
}
if (cameraCurr[index] != null)
{
_isOpen[index] = false;
cameraCurr[index].MV_CC_CloseDevice_NET();
cameraCurr[index].MV_CC_DestroyDevice_NET();
cameraCurr[index] = null;
}
}
}
public override void CloseAll()
{
if (cameraCurr == null)
return;
HDLogUtil.info(" cameraCurr.Length : " + cameraCurr.Length.ToString());
for (int i = 0; i < cameraCurr.Length; i++)
lock (cameraCurr)
{
if (cameraCurr[i] != null)
HDLogUtil.info(" cameraCurr.Length : " + cameraCurr.Length.ToString());
for (int i = 0; i < cameraCurr.Length; i++)
{
HDLogUtil.info($" cameraCurr[{i}] ");
_isOpen[i] = false;
cameraCurr[i].MV_CC_CloseDevice_NET();
cameraCurr[i].MV_CC_DestroyDevice_NET();
cameraCurr[i] = null;
if (cameraCurr[i] != null)
{
HDLogUtil.info($" cameraCurr[{i}] ");
_isOpen[i] = false;
cameraCurr[i].MV_CC_CloseDevice_NET();
cameraCurr[i].MV_CC_DestroyDevice_NET();
cameraCurr[i] = null;
}
}
}
}
......@@ -75,13 +87,8 @@ namespace CodeLibrary
try
{
int rtn = cameraCurr[index].MV_CC_StartGrabbing_NET();
if (rtn != MyCamera.MV_OK)
{
_errInfo = "Can not grab one : " + rtn;
return null;
}
return ImageCapture(index);
return ImageCapture2(index);
_errInfo = "OK";
// return true;
}
......@@ -159,54 +166,57 @@ namespace CodeLibrary
public override bool Open(int index)
{
// _index = index;
if (index < 0 || index >= _count)
{
_errInfo = "Not find";
HDLogUtil.error("open camera " + index + " error : " + _errInfo);
return false;
}
if (cameraCurr[index] != null) Close(index);
try
lock (cameraCurr)
{
MyCamera.MV_CC_DEVICE_INFO device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(cameraAll.pDeviceInfo[index], typeof(MyCamera.MV_CC_DEVICE_INFO));
cameraCurr[index] = new MyCamera();
int nRet = cameraCurr[index].MV_CC_CreateDevice_NET(ref device);
if (nRet != MyCamera.MV_OK) return false;
nRet = cameraCurr[index].MV_CC_OpenDevice_NET();
if (nRet != MyCamera.MV_OK)
// _index = index;
if (index < 0 || index >= _count)
{
cameraCurr[index].MV_CC_DestroyDevice_NET();
_errInfo = "Can not open";
_errInfo = "Not find";
HDLogUtil.error("open camera " + index + " error : " + _errInfo);
return false;
}
if (cameraCurr[index] != null) Close(index);
try
{
MyCamera.MV_CC_DEVICE_INFO device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(cameraAll.pDeviceInfo[index], typeof(MyCamera.MV_CC_DEVICE_INFO));
cameraCurr[index] = new MyCamera();
if (device.nTLayerType == MyCamera.MV_GIGE_DEVICE)
int nRet = cameraCurr[index].MV_CC_CreateDevice_NET(ref device);
if (nRet != MyCamera.MV_OK) return false;
nRet = cameraCurr[index].MV_CC_OpenDevice_NET();
if (nRet != MyCamera.MV_OK)
{
cameraCurr[index].MV_CC_DestroyDevice_NET();
_errInfo = "Can not open";
HDLogUtil.error("open camera " + index + " error : " + _errInfo);
return false;
}
if (device.nTLayerType == MyCamera.MV_GIGE_DEVICE)
{
int nPacketSize = cameraCurr[index].MV_CC_GetOptimalPacketSize_NET();
if (nPacketSize > 0) nRet = cameraCurr[index].MV_CC_SetIntValue_NET("GevSCPSPacketSize", (uint)nPacketSize);
}
//cameraCurr[index].MV_CC_SetEnumValue_NET("AcquisitionMode", 2); //工作在连续模式
cameraCurr[index].MV_CC_SetEnumValue_NET("TriggerMode", 0); //连续模式
MyCamera.MVCC_INTVALUE pstValue = new MyCamera.MVCC_INTVALUE();
nRet = cameraCurr[index].MV_CC_GetWidth_NET(ref pstValue);
_width[index] = (int)pstValue.nCurValue;
nRet = cameraCurr[index].MV_CC_GetHeight_NET(ref pstValue);
_height[index] = (int)pstValue.nCurValue;
_isOpen[index] = true;
_errInfo = "OK";
HDLogUtil.info("open camera " + index + _errInfo);
return true;
}
catch (Exception ex)
{
int nPacketSize = cameraCurr[index].MV_CC_GetOptimalPacketSize_NET();
if (nPacketSize > 0) nRet = cameraCurr[index].MV_CC_SetIntValue_NET("GevSCPSPacketSize", (uint)nPacketSize);
HDLogUtil.error("打开相机出错:" + ex.ToString());
_errInfo = ex.Message;
return false;
}
//cameraCurr[index].MV_CC_SetEnumValue_NET("AcquisitionMode", 2); //工作在连续模式
cameraCurr[index].MV_CC_SetEnumValue_NET("TriggerMode", 0); //连续模式
MyCamera.MVCC_INTVALUE pstValue = new MyCamera.MVCC_INTVALUE();
nRet = cameraCurr[index].MV_CC_GetWidth_NET(ref pstValue);
_width[index] = (int)pstValue.nCurValue;
nRet = cameraCurr[index].MV_CC_GetHeight_NET(ref pstValue);
_height[index] = (int)pstValue.nCurValue;
_isOpen[index] = true;
_errInfo = "OK";
HDLogUtil.info("open camera " + index + _errInfo);
return true;
}
catch (Exception ex)
{
HDLogUtil.error("打开相机出错:" + ex.ToString());
_errInfo = ex.Message;
return false;
}
}
......@@ -242,21 +252,30 @@ namespace CodeLibrary
}
public override bool OpenAll()
{
bool rtn = true;
for (int i = 0; i < cameraName.Count; i++)
lock (cameraCurr)
{
rtn = Open(i);
if (!rtn) break;
bool rtn = true;
for (int i = 0; i < cameraName.Count; i++)
{
rtn = Open(i);
if (!rtn) break;
}
return rtn;
}
return rtn;
}
private Bitmap ImageCapture(int index)
{
int rtn = cameraCurr[index].MV_CC_StartGrabbing_NET();
if (rtn != MyCamera.MV_OK)
{
_errInfo = "Can not grab one : " + rtn;
return null;
}
MyCamera.MVCC_INTVALUE stParam = new MyCamera.MVCC_INTVALUE();
int rtn = cameraCurr[index].MV_CC_GetIntValue_NET("PayloadSize", ref stParam);
rtn = cameraCurr[index].MV_CC_GetIntValue_NET("PayloadSize", ref stParam);
if (rtn != MyCamera.MV_OK) return null;
uint dataSize = stParam.nCurValue;
byte[] dataArr = new byte[dataSize];
......@@ -347,6 +366,104 @@ namespace CodeLibrary
return _image;
}
}
private Bitmap ImageCapture2(int index)
{
MyCamera.MV_FRAME_OUT FrameInfo = new MyCamera.MV_FRAME_OUT();
try
{
int rtn = cameraCurr[index].MV_CC_StartGrabbing_NET();
if (rtn != MyCamera.MV_OK)
{
_errInfo = "Can not grab one : " + rtn;
HDLogUtil.error("CaptureOnImage [" + index + "] error : " + _errInfo);
return null;
}
int nRet = cameraCurr[index].MV_CC_GetImageBuffer_NET(ref FrameInfo, 3000);
// ch:获取一帧图像 | en:Get one image
if (MyCamera.MV_OK == nRet)
{
HDLogUtil.debug("Get Image Buffer:" + "Width[" + Convert.ToString(FrameInfo.stFrameInfo.nWidth) + "] , Height[" + Convert.ToString(FrameInfo.stFrameInfo.nHeight)
+ "] , FrameNum[" + Convert.ToString(FrameInfo.stFrameInfo.nFrameNum) + "]");
Bitmap bmpcopy = null;
try
{
Bitmap bmp;
HDLogUtil.info(FrameInfo.stFrameInfo.enPixelType.ToString());
bmp = new Bitmap(FrameInfo.stFrameInfo.nWidth, FrameInfo.stFrameInfo.nHeight, FrameInfo.stFrameInfo.nWidth * 1, PixelFormat.Format8bppIndexed, FrameInfo.pBufAddr);
ColorPalette pal = bmp.Palette;
for (int i = 0; i <= 255; i++)
{
pal.Entries[i] = Color.FromArgb(i, i, i);
}
bmp.Palette = pal;
bmpcopy = DeepClone(bmp);
bmp.Dispose();
}
catch (Exception ex)
{
HDLogUtil.error(ex.ToString());
}
if (FrameInfo.pBufAddr != IntPtr.Zero)
{
nRet = cameraCurr[index].MV_CC_FreeImageBuffer_NET(ref FrameInfo);
if (nRet != MyCamera.MV_OK)
{
HDLogUtil.error(" [" + index + "] Free Image Buffer fail:" + nRet);
}
}
//return ho_Imagetemp;
return bmpcopy;
}
else
{
HDLogUtil.error(" [" + index + "] MV_CC_GetImageBuffer_NET No data: " + nRet);
}
}
catch (Exception ex)
{
_errInfo = ex.Message;
return null;
}
finally
{
cameraCurr[index].MV_CC_StopGrabbing_NET();
try
{
cameraCurr[index].MV_CC_FreeImageBuffer_NET(ref FrameInfo);
}
catch (Exception ex)
{
HDLogUtil.error(" [" + index + "] MV_CC_FreeImageBuffer_NET 出错:" + ex.ToString());
}
}
return null;
}
public static T DeepClone<T>(T _object)
{
try
{
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;
}
catch (Exception e)
{
HDLogUtil.error("DeepClone" + e.ToString());
return default;
}
}
public override HObject CaptureOnImage(string name)
{
var r = CaptureOnImage(name, out Bitmap bmp);
......@@ -358,6 +475,7 @@ namespace CodeLibrary
{
HObject hoImage = null;
bmp = null;
Bitmap bmpcopy;
int index = cameraName.FindIndex(s => s == name);
if (index == -1)
{
......@@ -367,11 +485,21 @@ namespace CodeLibrary
}
if (cameraCurr[index] != null)
{
HDLogUtil.info("CaptureOnImage [" + name + "] 相机已打开 ");
}
else
{
HDLogUtil.info("CaptureOnImage [" + name + "] 先打开相机 ");
Open(name);
if (!Open(name))
{
CloseAll();
Thread.Sleep(100);
if (!Open(name))
{
HDLogUtil.info("CaptureOnImage [" + name + "] 第二次打开相机失败 ");
return null;
}
}
}
MyCamera.MV_FRAME_OUT FrameInfo = new MyCamera.MV_FRAME_OUT();
......@@ -384,8 +512,8 @@ namespace CodeLibrary
HDLogUtil.error("CaptureOnImage [" + name + "] error : " + _errInfo);
return hoImage;
}
int nRet = cameraCurr[index].MV_CC_GetImageBuffer_NET(ref FrameInfo, 1000);
HDLogUtil.info("CaptureOnImage [" + name + "] MV_CC_StartGrabbing_NET ");
int nRet = cameraCurr[index].MV_CC_GetImageBuffer_NET(ref FrameInfo, 6000);
// ch:获取一帧图像 | en:Get one image
if (MyCamera.MV_OK == nRet)
{
......@@ -400,13 +528,15 @@ namespace CodeLibrary
HDLogUtil.info(FrameInfo.stFrameInfo.enPixelType.ToString());
bmp = new Bitmap(FrameInfo.stFrameInfo.nWidth, FrameInfo.stFrameInfo.nHeight, FrameInfo.stFrameInfo.nWidth * 1, PixelFormat.Format8bppIndexed, FrameInfo.pBufAddr);
ColorPalette pal = bmp.Palette;
bmpcopy = new Bitmap(FrameInfo.stFrameInfo.nWidth, FrameInfo.stFrameInfo.nHeight, FrameInfo.stFrameInfo.nWidth * 1, PixelFormat.Format8bppIndexed, FrameInfo.pBufAddr);
ColorPalette pal = bmpcopy.Palette;
for (int i = 0; i <= 255; i++)
{
pal.Entries[i] = Color.FromArgb(i, i, i);
}
bmp.Palette = pal;
bmpcopy.Palette = pal;
bmp = DeepClone(bmpcopy);
bmpcopy.Dispose();
}
catch (Exception ex)
......@@ -440,12 +570,7 @@ namespace CodeLibrary
cameraCurr[index].MV_CC_StopGrabbing_NET();
try
{
int nRet = cameraCurr[index].MV_CC_FreeImageBuffer_NET(ref FrameInfo);
if (nRet != MyCamera.MV_OK)
{
HDLogUtil.error(" [" + name + "] Free Image Buffer fail:" + nRet + ",set hoImage= null ");
hoImage = null;
}
cameraCurr[index].MV_CC_FreeImageBuffer_NET(ref FrameInfo);
}
catch (Exception ex)
{
......
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace CodeLibrary
{
unsafe partial class EyemDecode
{
//结构体
[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))
//接口
[DllImport("eyemLib.dll", CharSet = CharSet.None, CallingConvention = CallingConvention.Cdecl)]
private static extern int eyemTrackFeature(EyemImage tpImage, EyemImage tpMask, EyemRect tpRoi, IntPtr tpRois, int ipRoiNum, EyemHSVModel tpHSVModel, [MarshalAs(UnmanagedType.LPArray)] int[] ipResults, out EyemImage tpDstImg);
///////////////////使用///////////////////
public static int[] ReelCheck(string deviceName, Bitmap bitmap)
{
EyemImage image = eyemCvtToEyemImage(bitmap);
//绿色分割模型
EyemHSVModel tpHsvModel = new EyemHSVModel();
tpHsvModel.dpRangeL = new double[] { 55, 10, 35 }; tpHsvModel.dpRangeU = new double[] { 100, 255, 255 };
tpHsvModel.dpRangeLExt = new double[] { 0, 0, 0 }; tpHsvModel.dpRangeUExt = new double[] { 0, 0, 0 };
//裁剪区域
EyemRect tpRoi = new EyemRect();
tpRoi.iXs = 0; tpRoi.iYs = 0;
tpRoi.iWidth = image.iWidth;
tpRoi.iHeight = image.iHeight;
//添加需要监控的位置信息
List<EyemRect> tpRois = new List<EyemRect>();
EyemRect roi1 = new EyemRect();
roi1.iXs = 533; roi1.iYs = 187; roi1.iWidth = 345; roi1.iHeight = 310;
EyemRect roi2 = new EyemRect();
roi2.iXs = 900; roi2.iYs = 137; roi2.iWidth = 240; roi2.iHeight = 197;
tpRois.Add(roi1); tpRois.Add(roi2);
//转指针
IntPtr hGlobal = eyemStructArray2IntPtr(tpRois.ToArray());
//加载mask
EyemImage mask;
eyemImageRead("mask.png", -1, out mask);
//检测
int[] ipResults = new int[tpRois.Count];
eyemTrackFeature(image, mask, tpRoi, hGlobal, ipResults.Length, tpHsvModel, ipResults, out EyemImage tpDstImg);
for (int i = 0; i < ipResults.Length; i++)
{
if (ipResults[i] == 1)
{
Console.WriteLine("检测到{0}位置有料盘", i);
}
}
string date = deviceName.Trim().Replace('_', '-') + "-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + DateTime.Now.Millisecond;
string imageName = date + ".bmp";
Bitmap dstBitmap = eyemCvtToBitmap(tpDstImg);
if (dstBitmap != null)
{
dstBitmap.Save("D:\\ResOut\\" + imageName);
}
//释放资源
Marshal.FreeHGlobal(hGlobal);
//每运行检测一次释放一次
eyemImageFree(ref tpDstImg);
eyemImageFree(ref image);
//mask可以在程序启动与关闭时加载/释放
eyemImageFree(ref mask);
return ipResults;
}
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;
Buffer.MemoryCopy((byte*)(bd.Scan0.ToPointer()) + offsetSrc, (byte*)(tpImage.vpImage.ToPointer()) + offsetDst, bytesToCopy, bytesToCopy);
}
}
finally
{
bitmap.UnlockBits(bd);
}
return tpImage;
}
//public static void eyemCvtToEyemImage(Bitmap bitmap, out EyemImage tpImage)
//{
// int channels = 0;
// switch (bitmap.PixelFormat)
// {
// case PixelFormat.Format8bppIndexed:
// channels = 1;
// break;
// case PixelFormat.Format24bppRgb:
// channels = 3;
// break;
// case PixelFormat.Format32bppArgb:
// channels = 4;
// break;
// default:
// break;
// }
// //锁定数据区
// BitmapData bd = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
// ImageLockMode.ReadOnly, bitmap.PixelFormat);
// try
// {
// eyemImageFromBitmap(bd.Scan0, bd.Width, bd.Height, 0, channels, out tpImage);
// }
// finally
// {
// bitmap.UnlockBits(bd);
// }
//}
public static IntPtr eyemStructArray2IntPtr<T>(T[] tpArray)
{
if (tpArray == null)
throw new ArgumentNullException(typeof(T).Name.ToString());
//分配结构体需要的内存,需要释放
IntPtr hGlobal = Marshal.AllocHGlobal(checked(Marshal.SizeOf(typeof(T)) * tpArray.Length));
for (int index = 0; index < tpArray.Length; index++)
{
Marshal.StructureToPtr(tpArray[index], (IntPtr)(checked((long)hGlobal + index * Marshal.SizeOf(typeof(T)))), false);
}
return hGlobal;
}
public static Bitmap eyemCvtToBitmap(EyemImage tpImage)
{
if (tpImage.vpImage == IntPtr.Zero || tpImage.iDepth != 0)
return null;
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);
Buffer.MemoryCopy((byte*)(tpImage.vpImage.ToPointer()) + offsetSrc, (byte*)(bd.Scan0.ToPointer()) + offsetDst, bytesToCopy, bytesToCopy);
}
}
finally
{
bitmap.UnlockBits(bd);
}
return bitmap;
}
}
}
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!