CameraPointTest.cs 17.7 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 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
using CodeLibrary;
using Newtonsoft.Json;
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace DeviceLibrary
{
    [Serializable]
    public enum TestStorePointPort {
       入口, 出口, 上层左侧, 上层右侧, 下层左侧, 下层右侧,贴标,接标台
    }
    [Serializable]
    public class tstoredata {
        public string name="";
        public List<int> value = new List<int>();
        public List<string> ngMsg = new List<string>();
    }
    public class CameraPointTest
    {
        static CameraData CameraData;
        public static Dictionary<TestStorePointPort, List<string>> StoreState = new Dictionary<TestStorePointPort, List<string>>();
        public static void Init()
        {
            var fd = File.ReadAllText("Config\\CameraPointTest.json");
            CameraData = JsonConvert.DeserializeObject<CameraData>(fd);
            for (int i = 0; i < 5; i++)
            {
                inArea.Add(new tstoredata());
                inArea[i].name = "L" + ((char)(0x41 + i)).ToString();
                for (int j = 0; j < 4; j++)
                {
                    inArea[i].value.Add(0);
                    inArea[i].ngMsg.Add("");
                }
            }
            for (int i = 0; i < 5; i++)
            {
                outArea.Add(new tstoredata());
                outArea[i].name = "U" + ((char)(0x41 + i)).ToString();
                outArea[i].value.Add(0);
                outArea[i].ngMsg.Add("");
            }
        }
        public static event EventHandler<Bitmap> TestStorePointEvent;

        public static List<tstoredata> inArea = new List<tstoredata>();
        public static List<tstoredata> outArea = new List<tstoredata>();
        public static List<string> GetThingStoreName(TestStorePointPort tp,bool TestHas=true) {
            //var tl = Test(tp);
            try
            {
                int startindex = 0;
                List<string> haslistStoreName = new List<string>();
                List<int> haslistindex;
                switch (tp)
                {
                    case TestStorePointPort.入口:
                        startindex = RobotManage.AllPositionMapNumList.IndexOf("LA1");
                        haslistindex = TestStorePoint(RobotManage.CameraA.GetImage(0), TestStorePointPort.入口);
                        Dictionary<int, string> ngmsglist = new Dictionary<int, string>();
                        RobotManage.mainMachine.NGInfoList.ForEach(ng=> { 
                        var sindex = RobotManage.AllPositionMapNumList.IndexOf(ng.PosID)-startindex;
                            if (!ngmsglist.ContainsKey(sindex))
                                ngmsglist.Add(sindex, ng.NgMsg);
                        });
                        int index = 0;
                        for (int i = 0; i < 5; i++) {
                            for (int j = 0; j < 4; j++)
                            {
                                inArea[i].value[j]=haslistindex[index];
                                if (ngmsglist.ContainsKey(index))
                                {
                                    inArea[i].ngMsg[j] = ngmsglist[index];
                                    inArea[i].value[j] = -1;
                                }
                                index++;
                            }
                        }
                        break;
                    case TestStorePointPort.出口:
                        startindex = RobotManage.AllPositionMapNumList.IndexOf("UA1");
                        haslistindex = TestStorePoint(RobotManage.CameraA.GetImage(1), TestStorePointPort.出口);
                        index = 0;
                        for (int i = 0; i < 5; i++)
                        {
                            outArea[i].value[0]=haslistindex[index];
                            index++;
                        }
                        break;
                    case TestStorePointPort.上层左侧:
                        startindex = RobotManage.AllPositionMapNumList.IndexOf("SA1");
                        haslistindex = TestStorePoint(RobotManage.CameraA.GetImage(2), TestStorePointPort.上层左侧);
                        break;
                    case TestStorePointPort.上层右侧:
                        startindex = RobotManage.AllPositionMapNumList.IndexOf("SA1");
                        haslistindex = TestStorePoint(RobotManage.CameraA.GetImage(3), TestStorePointPort.上层右侧);
                        break;
                    case TestStorePointPort.下层左侧:
                        startindex = RobotManage.AllPositionMapNumList.IndexOf("SH1");
                        haslistindex = TestStorePoint(RobotManage.CameraA.GetImage(2), TestStorePointPort.下层左侧);
                        break;
                    case TestStorePointPort.下层右侧:
                        startindex = RobotManage.AllPositionMapNumList.IndexOf("SH7");
                        haslistindex = TestStorePoint(RobotManage.CameraA.GetImage(3), TestStorePointPort.下层右侧);
                        break;
                    default:
                        haslistindex = new List<int>();
                        break;
                }
                if (startindex == -1)
                    return new List<string>();

                for (int i = 0; i < haslistindex.Count; i++)
                {
                    if (haslistindex[i] == 1)
                    {
                        haslistStoreName.Add(RobotManage.AllPositionMapNumList[startindex + i]);
                    }
                }
                //StoreState[TestStorePointPort.入口] = haslistStoreName;
                //LogUtil.info("haslistStoreName:" + string.Join(",", haslistStoreName));
                return haslistStoreName;
            }
            catch (AccessViolationException) { return new List<string>(); }
            catch (Exception ex)
            {
                LogUtil.error("haslistStoreName:" + ex.ToString());
                return new List<string>();
            }
        }
        [HandleProcessCorruptedStateExceptions]
        public static List<int> TestStorePoint(Bitmap bmp, TestStorePointPort tp)
        {

            //TestStorePointEvent?.Invoke(tp, bmp);

            string Name = tp.ToString();
            if (CameraData[Name].ObjectPoint.Count == 0)
            {
                CameraData[Name].ObjectPoint = CalcStoreBMP(CameraData[Name].WCols, CameraData[Name].HLines, CameraData[Name].PointList);
            }

            List<Point> points = CameraData[Name].ObjectPoint;
            if (bmp == null)
                return Enumerable.Repeat(0, points.Count).ToList();
            
            List<int> haslist = new List<int>();
            BitmapData bd=null;
            try
            {
                bd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);
                for (int i = 0; i < points.Count; i++)
                {
                    var p = points[i];
                    p.X = p.X - 8;
                    p.Y = p.Y - 8;
                    var cl = new List<ColorHSV>();
                    for (int j = 0; j < 32; j++)
                    {
                        for (int k = 0; k < 32; k++)
                        {
                            var x = p.X + j;
                            var y = p.Y + k;
                            var addr = y * bd.Stride + x * 4;
                            var cr = Marshal.ReadByte(bd.Scan0, addr + 2);
                            var cg = Marshal.ReadByte(bd.Scan0, addr + 1);
                            var cb = Marshal.ReadByte(bd.Scan0, addr);
                            var hh = ColorHelper.RgbToHsv(new ColorRGB(cr, cg, cb));
                            cl.Add(hh);
                        }
                    }
                    var h = cl.Average(cc => cc.H);
                    var s = cl.Average(cc => cc.S);
                    var v = cl.Average(cc => cc.V);

                    var has = s > CameraData[Name].S && h > 60 && h < 200;
                    haslist.Add(has ? 1 : 0);
                }
            }
            catch (AccessViolationException ex)
            {
                LogUtil.error("TestStorePoint AccessViolationException:" + ex.ToString());
            }catch (Exception ex)
            {
                LogUtil.error("TestStorePoint:" + ex.ToString());
            }
            finally
            {
                if (bd!=null)
                    bmp.UnlockBits(bd);
            }
            //Size pointsize = new Size(30, 30);
            SolidBrush red = new SolidBrush(Color.Red);
            SolidBrush gray = new SolidBrush(Color.Gray);
            try
            {
                var g = Graphics.FromImage(bmp);
                for (int i = 0; i < CameraData[Name].ObjectPoint.Count; i++)
                {
                    g.FillEllipse(haslist[i] == 1 ? red : gray, GetCR(CameraData[Name].ObjectPoint[i], 30));
                }
                g.Save();
                bmp.Save(tp.ToString() + ".bmp");
            }
            catch (Exception ex)
            {
                LogUtil.error("TestStorePoint:" + ex.ToString());
            }
            TestStorePointEvent?.Invoke(tp, bmp);
            return haslist;
        }

        public static TestStorePointPort GetTestStorePointPort(string posname) {

            TestStorePointPort testStorePointPort;
            if (Regex.IsMatch(posname, "^S[A-G]"))
                testStorePointPort= TestStorePointPort.上层左侧;
            else if (Regex.IsMatch(posname, "^S[H-N][1-6]$"))
                testStorePointPort = TestStorePointPort.下层左侧;
            else
                testStorePointPort = TestStorePointPort.下层右侧;

            LogUtil.info($"GetTestStorePointPort: {posname}={testStorePointPort}");
            return testStorePointPort;
        }

        /// <summary>
        /// 检测标签是否被取走
        /// </summary>
        /// <returns></returns>
        public static bool TestHasLabelOnDock(bool checkstatus) {
            var r = CameraPointTest.CameraData[TestStorePointPort.接标台.ToString()].PointList;
            Point checkpoint = r[0];
            var bmp = RobotManage.CameraA.GetImage(0);
            if (bmp == null)
                return true;

            //bmp = new Bitmap("d:\\新建分组1_监控点1_106_20220818172856_3997146.bmp");

            BitmapData bd = null;
            try
            {
                bd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);

                var p = checkpoint;
                p.X = p.X - 8;
                p.Y = p.Y - 8;
                var cl = new List<ColorHSV>();
                for (int j = 0; j < 16; j++)
                {
                    for (int k = 0; k < 16; k++)
                    {
                        var x = p.X + j;
                        var y = p.Y + k;
                        var addr = y * bd.Stride + x * 4;
                        var cr = Marshal.ReadByte(bd.Scan0, addr + 2);
                        var cg = Marshal.ReadByte(bd.Scan0, addr + 1);
                        var cb = Marshal.ReadByte(bd.Scan0, addr);
                        var hh = ColorHelper.RgbToHsv(new ColorRGB(cr, cg, cb));
                        cl.Add(hh);
                    }
                }
                var h = cl.Average(cc => cc.H);
                var s = cl.Average(cc => cc.S);
                var v = cl.Average(cc => cc.V);

                var has = (h>180 && h<260) || s<10;
                has =  s < 15;
                LogUtil.info($"TestHasLabelOnDock checkstatus:{checkstatus}, h:{h},s:{s},v:{v},config_s:{CameraData[TestStorePointPort.接标台.ToString()].S}");

                if (has != checkstatus)
                {
                    Directory.CreateDirectory("\\image\\LabelDock");
                    bmp.Save("\\image\\LabelDock\\"+ checkstatus +"_"+ DateTime.Now.ToString("yyyyMMddHHmmss")+".jpg");
                }
                return has;
            }
            catch (AccessViolationException ex)
            {
                LogUtil.error("TestHasLabelOnDock AccessViolationException:" + ex.ToString());
            }
            catch (Exception ex)
            {
                LogUtil.error("TestHasLabelOnDock:" + ex.ToString());
            }
            finally
            {
                if (bd != null)
                    bmp.UnlockBits(bd);
            }
            return false;
        }
        /// <summary>
        /// 按中心点扩展一个矩形区域
        /// </summary>
        /// <param name="point"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        static Rectangle GetCR(Point point,int size) {

            return new Rectangle(point.X - size / 2, point.Y - size / 2, size, size);
        }
        /// <summary>
        /// 获取库位像素点位
        /// </summary>
        /// <param name="w"></param>
        /// <param name="h"></param>
        /// <param name="points"></param>
        /// <returns></returns>
        static List<Point> CalcStoreBMP(int w, int h, List<Point> points)
        {

            List<Point> StorePoint = new List<Point>();
            

            //var g = Graphics.FromImage(bmp);

            var la = Common.getAngle(points[0], points[3]);
            var ld = Common.distance(points[0], points[3]);
            var ra = Common.getAngle(points[1], points[2]);
            var rd = Common.distance(points[1], points[2]);
            for (int j = 0; j < h; j++)
            {
                var pa = Common.PointWithAngle(points[0], la, ld / (h - 1) * j);
                var pb = Common.PointWithAngle(points[1], ra, rd / (h - 1) * j);
                var ag = Common.getAngle(pa, pb);
                var ad = Common.distance(pa, pb);
                for (int i = 0; i < w; i++)
                {
                    if (ad == 0)
                        StorePoint.Add(pa);
                    else
                    {
                        var p = Common.PointWithAngle(pa, ag, ad / (w - 1) * i);
                        StorePoint.Add(p);
                    }
                    //g.FillEllipse(red, new Rectangle(p, pointsize));
                }
            }

            //g.Save();
            //bmp.Save(@"D:\rick\vs\SO20031_TinStorage\料架照片\1.bmp");
            return StorePoint;
        }

        public static bool ScanRectangle() {
            var r = CameraData[TestStorePointPort.贴标.ToString()].PointList;
            Point Start = r[0];
            Point End = r[1];
            int width = End.X - Start.X;
            int height = End.Y - Start.Y;
            LogUtil.info($"开始扫描绿色区域:{Start},{width}x{height}");
            var bmp = Camera._cam.GrabOneImage(CodeManager.hikNameList[0], PixelType.RGB8);
            //var bmp = new Bitmap("Image_20221208134139341.bmp");
            var bd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
            int HeightCount = 0;
            int errlinecount = 0;
            try {
                
                for (int i = 0; i < height; i=i+2)
                {
                    int linecount = 0;
                    
                    for (int j = 0; j < width; j=j+3)
                    {
                        var x = Start.X+ j;
                        var y = Start.Y + height - i;
                        var addr = y * bd.Stride + x * 3;
                        var cr = Marshal.ReadByte(bd.Scan0, addr + 2);
                        var cg = Marshal.ReadByte(bd.Scan0, addr + 1);
                        var cb = Marshal.ReadByte(bd.Scan0, addr);
                        var hh = ColorHelper.RgbToHsv(new ColorRGB(cr, cg, cb));
                        var s = hh.S;
                        var h = hh.H;
                        var has = s > 15 && h > 90 && h < 150;
                        if (has)
                        {
                            linecount++;//本行绿色计数
                            Marshal.WriteByte(bd.Scan0, addr + 2, 0xFF);
                            Marshal.WriteByte(bd.Scan0, addr + 1, 0);
                            Marshal.WriteByte(bd.Scan0, addr, 0);
                        }
                    }
                    if (linecount*3 < width * 0.6)
                    {
                        errlinecount++;
                        HeightCount = 0;
                        if (errlinecount > 60)
                        {
                            return false;
                        }
                        //return HeightCount;
                    }
                    else {
                        HeightCount++;
                        if (HeightCount*2 > 50) {
                            return true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("ScanRectangle:" + ex.ToString());
            }
            finally
            {
                bmp.UnlockBits(bd);
                bmp.Save("\\Image\\LabelDebug\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + "-"+ errlinecount +"-"+ HeightCount + ".bmp");
            }            
            return false;
        }
    }
    public class CameraData : Dictionary<string, CameraPointData> { }

    public class CameraPointData
    {
        public int S = 20;
        public int WCols;
        public int HLines;
        public List<Point> PointList = new List<Point>();
        [JsonIgnore]
        public List<Point> ObjectPoint = new List<Point>();
    }
}