Example #1
0
        //得到车牌的所有信息通过不同的方法
        public static PlateInfo GetPlateInfoByMutilMethod(PlateInfo plateInfo, PlateColor plateColor)
        {
            PlateInfo        plateInfoByOriginal = GetPlateInfo(plateInfo, plateColor, CharSplitMethod.原图);
            PlateInfo        plateInfoByGamma    = GetPlateInfo(plateInfo, plateColor, CharSplitMethod.伽马);
            PlateInfo        plateInfoByIndex    = GetPlateInfo(plateInfo, plateColor, CharSplitMethod.指数);
            PlateInfo        plateInfoByLog      = GetPlateInfo(plateInfo, plateColor, CharSplitMethod.对数);
            List <PlateInfo> plateInfos          = new List <PlateInfo>();

            if (plateInfoByOriginal.CharInfos != null && plateInfoByOriginal.CharInfos.Count != 0)
            {
                plateInfos.Add(plateInfoByOriginal);
            }
            if (plateInfoByGamma.CharInfos != null && plateInfoByGamma.CharInfos.Count != 0)
            {
                plateInfos.Add(plateInfoByGamma);
            }
            if (plateInfoByIndex.CharInfos != null && plateInfoByIndex.CharInfos.Count != 0)
            {
                plateInfos.Add(plateInfoByIndex);
            }
            if (plateInfoByLog.CharInfos != null && plateInfoByLog.CharInfos.Count != 0)
            {
                plateInfos.Add(plateInfoByLog);
            }
            if (plateInfos.Count == 0)
            {
                return(new PlateInfo());
            }
            plateInfos.Sort(new PlateInfoComparer_DESC());
            PlateInfo result = plateInfos[0];

            return(result);
        }
Example #2
0
        public bool SetRetransferTime(int equipId, DateTime StartTime, DateTime EndTime)
        {
            T_PathIdentifyEquip equip = CurrentEquipList.Where(it => it.Id == equipId).FirstOrDefault();

            PlateInfo.DisConnect(equip.ParentId);
            return(PlateInfo.SetEquipReTranTime(equipId, StartTime, EndTime));
        }
Example #3
0
        //
        public static PlateInfo GetPlateInfo(PlateInfo plateInfo, PlateColor plateColor, CharSplitMethod
                                             splitMethod)
        {
            PlateInfo result = new PlateInfo();

            result.PlateCategory     = plateInfo.PlateCategory;
            result.OriginalMat       = plateInfo.OriginalMat;
            result.OriginalRect      = plateInfo.OriginalRect;
            result.PlateLocateMethod = plateInfo.PlateLocateMethod;
            result.PlateColor        = plateColor;
            List <CharInfo> charInfos = new List <CharInfo>();

            switch (splitMethod)
            {
            case CharSplitMethod.伽马:
                charInfos = CharSegment_V3.SplitePlateByGammaTransform(plateInfo.OriginalMat,
                                                                       plateColor);
                break;

            case CharSplitMethod.指数:
                charInfos = CharSegment_V3.SplitePlateByIndexTransform(plateInfo.OriginalMat, plateColor);
                break;

            case CharSplitMethod.对数:
                charInfos = CharSegment_V3.SplitePlateByLogTransform(plateInfo.OriginalMat, plateColor);
                break;

            case CharSplitMethod.原图:
            default:
                charInfos = CharSegment_V3.SplitePlateByOriginal(plateInfo.OriginalMat,
                                                                 plateInfo.OriginalMat, plateColor);
                break;
            }
            //启动SVM识别字符并将其中的非字符去除
            for (int index = charInfos.Count - 1; index >= 0; index--)
            {
                CharInfo  charInfo  = charInfos[index];
                PlateChar plateChar = PlateChar_SVM.Test(charInfo.OriginalMat);
                if (plateChar == PlateChar.非字符)
                {
                    charInfos.RemoveAt(index);
                }
                charInfo.PlateChar = plateChar;
            }
            result.CharInfos = charInfos;
            //检测
            CheckLeftAndRightToRemove(result);
            CheckPlateColor(result);
            return(result);
        }
Example #4
0
        //确定车牌的颜色
        private static void CheckPlateColor(PlateInfo plateInfo)
        {
            if (plateInfo.PlateCategory == PlateCategory.非车牌)
            {
                return;
            }
            switch (plateInfo.PlateCategory)
            {
            case PlateCategory.普通车牌:
                break;

            case PlateCategory.普通车牌_两行:
                plateInfo.PlateColor = PlateColor.黄牌;
                break;
            }
        }
        public void MoveMonster(Monster monster) // 플레이어가 존재하는 스테이지의 몬스터만 이동
        {
            List <Point> points = new List <Point>();
            int          stage  = monster.stage;
            int          xPos   = monster.xPos - 1;
            int          yPos   = monster.yPos - 1;

            //이동 가능 위치 계산
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    PlateInfo plate = WhatExists(stage, xPos + i, yPos + j);
                    if (plate == PlateInfo.empty || plate == PlateInfo.player)
                    {
                        points.Add(new Point(xPos + i, yPos + j));
                    }
                }
            }
            xPos++; yPos++;

            //이동가능한 위치가 없을경우 그냥 리턴
            if (points.Count == 0)
            {
                return;
            }

            int index = r.Next(0, points.Count);

            //이동할 위치가 빈공간이면 이동 / 플레이어면 lifepoint-- 하고 제자리에 남기
            if (WhatExists(stage, points[index].X, points[index].Y) == PlateInfo.empty)
            {
                stages[stage].Location[xPos, yPos] = PlateInfo.empty;
                labels[xPos, yPos].Text            = GetPlateString(PlateInfo.empty);

                monster.MoveTo(points[index].X, points[index].Y);

                stages[stage].Location[monster.xPos, monster.yPos] = PlateInfo.monster;
                labels[monster.xPos, monster.yPos].Text            = GetPlateString(PlateInfo.monster);
            }
            else if (WhatExists(stage, points[index].X, points[index].Y) == PlateInfo.player)
            {
                MessageBox.Show("몬스터로부터 공격받았습니다!\n 체력이 1 감소합니다");
                player.Attacked();
            }
        }
Example #6
0
	GameObject MakeRecipePanel(PlateInfo plateInfo)
	{
		GameObject recipePanel = Instantiate(RecipePanel);

		foreach (Ingredient ingredient in plateInfo.Recipe.Ingredients)
		{
			GameObject ingredientPanel = MakeIngredientPanel(ingredient);
			ingredientPanel.transform.SetParent(recipePanel.transform, false);
		}
        
        //Parent the recipe panel to the plate label image
        UIPlateNumberLabel plateLabel = GameObject.FindObjectsOfType<UIPlateNumberLabel>().Where(p => p.PlateNumber == plateInfo.Bench.PlateNumber).ToList()[0];
        recipePanel.transform.SetParent(plateLabel.transform);
        recipePanel.GetComponent<RectTransform>().anchoredPosition = new Vector3(90, 0, 0);
        recipePanel.GetComponent<RectTransform>().localScale = new Vector3(1.8f, 1.8f, 1.8f);

        return recipePanel;
	}
Example #7
0
        //对图片进行处理(分割加识别,一条龙)
        public static List <PlateInfo> Recognite(Mat matSource)
        {
            List <PlateInfo> result           = new List <PlateInfo>();
            List <PlateInfo> plateInfosLocate = PlateLocator_V3.LocatePlates(matSource);

            Console.WriteLine("{0}", plateInfosLocate.Count);
            for (int index = 0; index < plateInfosLocate.Count; index++)
            {
                PlateInfo plateInfo          = plateInfosLocate[index];
                PlateInfo plateInfoOfHandled = GetPlateInfoByMutilMethodAndMutilColor(plateInfo);
                if (plateInfoOfHandled != null)
                {
                    plateInfoOfHandled.PlateCategory = plateInfo.PlateCategory;
                    result.Add(plateInfoOfHandled);
                }
            }
            return(result);
        }
Example #8
0
        private FQID AddNewBookmark(PlateInfo plateInfo, IList <OpenALPRmilestoneCameraName> cameras)
        {
            Bookmark bookmark = null;

            foreach (OpenALPRmilestoneCameraName camera in cameras)
            {
                try
                {
                    FQID fqid = MilestoneServer.GetCameraByName(camera.MilestoneName);

                    if (fqid == null)
                    {
                        Program.Log.Info($"No mapping found for camera: {plateInfo.CameraId.ToString()}");
                        continue; // As Matt suggest, this will remove this job from the queue
                    }

                    bookmark = null;
                    bookmark = BookmarkService.Instance.BookmarkCreate(
                        fqid,
                        plateInfo.EpochStart.AddSeconds(-EpochStartSecondsBefore),          //subtracted 3 secondes from the start time to give more chances to capture the video
                        plateInfo.EpochStart,                                               //timeTrigged
                        plateInfo.EpochEnd.AddSeconds(EpochEndSecondsAfter),                //added 3 secondes to give more chances to capture the video
                        "openalpr",                                                         //so we can reterive openalpr bookmarks only in the plug-in
                        plateInfo.BestPlateNumber,
                        $"Make={plateInfo.Make};MakeModel={plateInfo.MakeModel};BodyType={plateInfo.BodyType};Color={plateInfo.Color};BestRegion={plateInfo.BestRegion};Candidates={plateInfo.CandidatesPlate}");


                    if (bookmark == null)
                    {
                        Program.Log.Warn($"Failed to create a Bookmark for Plate number: {plateInfo.BestPlateNumber}");
                    }
                    else
                    {
                        Program.Log.Info($"Created Bookmark for Plate number: {plateInfo.BestPlateNumber}");
                    }
                }
                catch (Exception ex)
                {
                    Program.Log.Error(null, ex);
                }
            }

            return(bookmark?.BookmarkFQID); // bookmark for the last camera used.
        }
Example #9
0
 void displayDataset(MainDataset datasetIn)
 {
     for (int i = 0; i < datasetIn.data.Count; i++)
     {
         PlateInfo plateInfo = datasetIn.data[i];
         Debug.Log("------------------------------------------------\n");
         Debug.Log("Ruta: ");
         foreach (int Ruta in plateInfo.Ruta)
         {
             Debug.Log(Ruta);
         }
         Debug.Log("\nTrips:");
         foreach (int trip in plateInfo.Viaje)
         {
             Debug.Log(trip);
         }
         Debug.Log("Start: " + plateInfo.inicio);
     }
 }
Example #10
0
        //判断是否使正确的车牌
        public static bool JudgePlateRightful(PlateInfo plateInfo)
        {
            if (plateInfo.CharInfos == null || plateInfo.CharInfos.Count == 0)
            {
                return(false);
            }
            if (plateInfo.PlateColor == PlateColor.未知)
            {
                return(false);
            }
            int charCount = 0;

            foreach (var charInfo in plateInfo.CharInfos)
            {
                if (charInfo.PlateChar != PlateChar.非字符)
                {
                    charCount++;
                }
            }
            return(charCount >= 5);
        }
Example #11
0
        public static List <PlateInfo> RecogPlateAndChar(Mat matSource)
        {
            List <PlateInfo> PlateInfoList = PlateRecognition_V3.Recognite(matSource);

            if (PlateInfoList.Count == 0)
            {
                PlateCategory PlateCategory = PlateCategory.非车牌;

                Rect OriginalRect   = new Rect();
                Mat  OriginalMatnew = new Mat();
                PlateLocateMethod PlateLocateMethod = PlateLocateMethod.未知;
                List <CharInfo>   CharInfos         = null;

                PlateInfo noPlateInfo = new PlateInfo(PlateCategory, OriginalRect, OriginalMatnew, CharInfos, PlateLocateMethod);
                PlateInfoList.Add(noPlateInfo);
                return(PlateInfoList);
            }
            else
            {
                return(PlateInfoList);
            }
        }
Example #12
0
        private void OnEquipStatusChanged(PathIdEquipStatusChangedEventArgs args)
        {
            T_PathIdentifyEquip equip = CurrentEquipList.Where(it => it.Id == args.equipId).FirstOrDefault();

            if (args.status == 5)
            {
                PlateInfo.Connect(equip.ParentId);
            }
            if (DeviceStatusNotifyHandler != null)
            {
                if (equip == null)
                {
                    throw new Exception("信路威驱动在回调设备状态时发生错误:未能找到目标设备,EQUIPID=" + args.equipId.ToString());
                }
                DeviceStatus statusInfo = new DeviceStatus();
                statusInfo.Device     = equip;
                statusInfo.GatherTime = args.currentDateTime;
                statusInfo.Status     = args.status;
                statusInfo.StatusDesc = args.statusDes;
                DeviceStatusNotifyHandler.Invoke(this, statusInfo);
            }
        }
        public string GetPlateString(PlateInfo info)
        {
            string s = "";

            switch (info)
            {
            case PlateInfo.empty:
                s = "▩";    break;

            case PlateInfo.player:
                s = "■";    break;

            case PlateInfo.monster:
                s = "Σ";    break;

            case PlateInfo.portal:
                s = "●";    break;

            case PlateInfo.exit:
                s = "◎";    break;
            }
            return(s);
        }
Example #14
0
        public static PlateInfo GetPlateInfoByMutilMethodAndMutilColor(PlateInfo plateInfo)
        {
            PlateInfo result = null;

            if (plateInfo.OriginalMat == null)
            {
                return(result);
            }
            PlateInfo plateInfo_Blue = GetPlateInfoByMutilMethod(plateInfo, PlateColor.蓝牌);

            if (JudgePlateRightful(plateInfo_Blue) == true)
            {
                plateInfo_Blue.PlateColor = PlateColor.蓝牌;
                return(plateInfo_Blue);
            }
            PlateInfo plateInfo_Yello = GetPlateInfoByMutilMethod(plateInfo, PlateColor.黄牌);

            if (JudgePlateRightful(plateInfo_Yello) == true)
            {
                plateInfo_Yello.PlateColor = PlateColor.黄牌;
                return(plateInfo_Yello);
            }
            return(result);
        }
Example #15
0
        public bool InitDriver(List <T_PathIdentifyEquip> Equips)
        {
            CurrentEquipList = Equips;
            //innerDriver = new PlateInfo();
            List <PathIdEquip> innerEquipList = new List <PathIdEquip>();

            foreach (T_PathIdentifyEquip e in Equips)
            {
                PathIdEquip item = new PathIdEquip();
                item.equipId   = e.Id;
                item.equipType = e.EquipType;
                item.ip        = e.Ip;
                item.parentId  = e.ParentId;
                item.port      = e.Port ?? 8088;
                item.usercode  = e.LoginUserName;
                item.password  = e.LoginPwd;
                innerEquipList.Add(item);
            }
            bool setStatusEvent  = PlateInfo.SetPathIdEquipStatusHandler(OnEquipStatusChanged);
            bool setReceiveEvent = PlateInfo.SetPathIdEquipVehicleInfoHandler(OnVehicleInfoReceived);
            bool initRel         = PlateInfo.InitPathIdentificationDriver(innerEquipList);

            //foreach (var item in innerEquipList)
            //{
            //    bool connrel = PlateInfo.Connect(item.parentId);
            //    Debug.Print(connrel.ToString());
            //}
            if (setStatusEvent && setReceiveEvent && initRel)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #16
0
        private bool ProcessAlprGroupOrResults(OpenALPRData palteInfo)
        {
            if (palteInfo != null)
            {
                List <string> candidates = palteInfo.Candidates.GroupBy(candidate => candidate.Plate)
                                           .Select(grp => grp.First())
                                           .Select(p => p.Plate)
                                           .ToList();

                PlateInfo bestPlateInfo = new PlateInfo
                {
                    DataType        = palteInfo.Data_type,
                    CameraId        = palteInfo.Camera_id,
                    BestPlateNumber = palteInfo.Best_plate_number,
                    BestRegion      = palteInfo.Best_region,
                    CandidatesPlate = string.Join(",", candidates)
                };

                bestPlateInfo.EpochStart = Epoch2LocalDateTime(palteInfo.Epoch_start);
                bestPlateInfo.EpochEnd   = Epoch2LocalDateTime(palteInfo.Epoch_end);

                if (palteInfo.Vehicle != null)
                {
                    if (palteInfo.Vehicle.Make != null)
                    {
                        Make make = palteInfo.Vehicle.Make.OrderByDescending(m => m.Confidence).FirstOrDefault();
                        if (make != null)
                        {
                            bestPlateInfo.Make = make.Name;
                        }
                    }

                    if (palteInfo.Vehicle.Body_type != null)
                    {
                        BodyType body_type = palteInfo.Vehicle.Body_type.OrderByDescending(m => m.Confidence).FirstOrDefault();
                        if (body_type != null)
                        {
                            bestPlateInfo.BodyType = body_type.Name;
                        }
                    }

                    if (palteInfo.Vehicle.Make_model != null)
                    {
                        MakeModel makeModel = palteInfo.Vehicle.Make_model.OrderByDescending(m => m.Confidence).FirstOrDefault();
                        if (makeModel != null)
                        {
                            bestPlateInfo.MakeModel = makeModel.Name;
                        }
                    }

                    if (palteInfo.Vehicle.Color != null)
                    {
                        Color color = palteInfo.Vehicle.Color.OrderBy(c => c.Confidence).FirstOrDefault();
                        if (color != null)
                        {
                            bestPlateInfo.Color = color.Name;
                        }
                    }
                }
                else
                {
                    Program.Log.Warn("Vehicle json data returned null object.");
                }

                if (!string.IsNullOrEmpty(palteInfo.Best_plate_number) && palteInfo.Camera_id != 0)
                {
                    FQID bookmarkFQID = null;
                    IList <OpenALPRmilestoneCameraName> cameras = GetCameraFromMapping(bestPlateInfo.CameraId.ToString());

                    if (AddBookmarks)
                    {
                        bookmarkFQID = AddNewBookmark(bestPlateInfo, cameras);
                    }

                    if (cameras.Count != 0)
                    {
                        SendAlarm(bestPlateInfo, cameras[cameras.Count - 1].MilestoneName, bookmarkFQID); // Send Alert for the last Camera since we recieved the bookmarkFQID for the last camera used in AddNewBookmark.
                    }
                }
                else
                {
                    Program.Log.Warn("Best_plate_number is empty or Camera_id == 0");
                }
            }

            return(true);
        }
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            int xPos = player.xPos;
            int yPos = player.yPos;

            switch (e.KeyCode)
            {
            case Keys.Right:
                yPos++;
                break;

            case Keys.Left:
                yPos--;
                break;

            case Keys.Up:
                xPos--;
                break;

            case Keys.Down:
                xPos++;
                break;

            default:
                return;
            }

            PlateInfo info = WhatExists(player.stage, xPos, yPos);

            switch (info)
            {
            case PlateInfo.empty:
                MoveTo(xPos, yPos);
                break;

            case PlateInfo.portal:
                Portal portal = stages[player.stage].WhereToGo(xPos, yPos); // 이동할 스테이지의 포탈
                int[]  pos    = CalcLocation(portal);                       // 이동할 위치 계산
                if (pos[0] == -1 && pos[1] == -1)
                {
                    MessageBox.Show("이동가능한 위치가 없습니다!");
                    break;
                }
                MoveStage(portal.stage, pos[0], pos[1]);
                ShowStage(portal.stage);
                labels[player.xPos, player.yPos].Text = GetPlateString(PlateInfo.player);
                break;

            case PlateInfo.exit:
                Result result = new Result(true);
                result.ShowDialog();
                this.Close();
                break;

            case PlateInfo.monster:     // 일단 몬스터와 맵 밖으로는 이동할 수 없게 구현
                return;

            case PlateInfo.notExist:
                return;
            }

            //플레이어 이동한 후 해당 스테이지의 몬스터 이동
            for (int i = 0; i < stages[player.stage].monsters.Count; i++)
            {
                MoveMonster(stages[player.stage].monsters[i]);
            }
            //결과 반영
            ShowLifeAndStage();
        }
        public List <PlateInfo> QueryPlateData(DateTime startT, DateTime endT, RealtimeCameraInfo[] SelectedCrowdCameraInfo, string plateNum, uint vehicleColor, uint plateColor, IVX.Controls.DAO.VehicleBrand[] m_CheckedVehicleModels, long m_Brand, int m_NVehicleDetailType, bool isStart = true)
        {
            List <PlateInfo> PlateDatas = new List <PlateInfo>();

            m_page = isStart ? 0 : m_page;
            string cameras   = "";
            string startTime = Convert.ToUInt64(startT.Subtract(DataModel.Common.ZEROTIME).TotalSeconds).ToString();
            string endTime   = Convert.ToUInt64(endT.Subtract(DataModel.Common.ZEROTIME).TotalSeconds).ToString();

            if (SelectedCrowdCameraInfo != null && SelectedCrowdCameraInfo.Length > 0)
            {
                foreach (var item in SelectedCrowdCameraInfo)
                {
                    cameras += "\"" + item.CameraCode + "\",";
                }
                cameras = cameras.TrimEnd(',');
            }
            string modelids = "";

            if (m_CheckedVehicleModels != null && m_CheckedVehicleModels.Length > 0)
            {
                foreach (var item in m_CheckedVehicleModels)
                {
                    modelids += "\"" + item.Id + "\",";
                }
                modelids = modelids.TrimEnd(',');
            }
            //string m_Brand = "";
            //string plateNum = "";
            //string m_NVehicleDetailType = "";

            using (MySql.Data.MySqlClient.MySqlConnection conn
                       = new MySql.Data.MySqlClient.MySqlConnection(string.Format(m_connString, RTRISServerIP, "rtrs_server_db")))
            {
                try
                {
                    string sql = "SELECT "
                                 + " info.ID, "
                                 + " info.CAMERA_CODE, "
                                 + " info.TIME_STAMP_SEC, "
                                 + " info.TIME_STAMP_MILLI_SEC, "
                                 + " info.OBJECT_TYPE, "
                                 + " info.RELIABILITY, "
                                 + " info.PLATE_NUM, "
                                 + " info.PLATE_NUM_ROW, "
                                 + " info.PLATE_COLOR, "
                                 + " info.VEHICLE_COLOR, "
                                 + " info.VEHICLE_TYPE, "
                                 + " info.VEHICLE_TYPE_DETAIL, "
                                 + " info.VEHICLE_LABEL, "
                                 + " info.VEHICLE_LABEL_DETAIL, "
                                 + " info.VEHICLE_SPEED, "
                                 + " info.DIRECTION, "
                                 + " info.ROAD_WAY_NUM, "
                                 + " info.PLATE_COORDX, "
                                 + " info.PLATE_COORDY, "
                                 + " info.PLATE_COORD_WIDTH, "
                                 + " info.PLATE_COORD_HEIGHT, "
                                 + " info.PLATE_IMG_SIZE, "
                                 + " info.PLAT_IMG_DATA, "
                                 + " info.VEHIBODY_COORDX, "
                                 + " info.VEHIBODY_COORDY, "
                                 + " info.VEHIBODY_COORD_WIDTH, "
                                 + " info.VEHIBODY_COORD_HEIGHT, "
                                 + " info.FULL_IMG_WIDTH, "
                                 + " info.FULL_IMG_HEIGHT, "
                                 + " info.COMPOSE_IMG_WIDTH, "
                                 + " info.COMPOSE_IMG_HEIGHT "
                                 + " FROM rt_vehicle_detect_info as info "
                                 + " WHERE info.TIME_STAMP_SEC BETWEEN \"" + startTime + "\" AND \"" + endTime + "\"";

                    if (!string.IsNullOrEmpty(cameras))
                    {
                        sql += " AND info.CAMERA_CODE in (" + cameras + ")";
                    }

                    if (vehicleColor != 0)
                    {
                        sql += " AND info.VEHICLE_COLOR = " + vehicleColor;
                    }

                    if (plateColor != 0)
                    {
                        sql += " AND info.PLATE_COLOR = " + plateColor;
                    }

                    if (m_Brand != -1)
                    {
                        sql += " AND info.VEHICLE_LABEL = " + m_Brand;
                    }

                    if (m_NVehicleDetailType != 0)
                    {
                        sql += " AND info.VEHICLE_TYPE_DETAIL = " + m_NVehicleDetailType;
                    }

                    if (!string.IsNullOrEmpty(modelids))
                    {
                        sql += " AND info.VEHICLE_LABEL_DETAIL in (" + modelids + ")";
                    }

                    if (!string.IsNullOrEmpty(plateNum))
                    {
                        sql += " AND info.PLATE_NUM like \"*" + plateNum + "*\"";
                    }

                    sql += " LIMIT " + (m_page++) * PAGE_PER_COUNT + "," + PAGE_PER_COUNT;

                    MyLog4Net.Container.Instance.Log.Debug("QueryData sql:" + sql);

                    conn.Open();
                    MySql.Data.MySqlClient.MySqlCommand    cmd    = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
                    MySql.Data.MySqlClient.MySqlDataReader reader = cmd.ExecuteReader();
                    DataTable table = new DataTable();
                    table.Load(reader);
                    conn.Close();


                    foreach (DataRow item in table.Rows)
                    {
                        PlateInfo info = new PlateInfo();
                        info.ID                   = Convert.ToUInt64(item["ID"].ToString());
                        info.CameraCode           = item["CAMERA_CODE"].ToString();
                        info.TimeStampSec         = DataModel.Common.ZEROTIME.AddSeconds(Convert.ToUInt32(item["TIME_STAMP_SEC"].ToString())).AddMilliseconds(Convert.ToUInt64(item["TIME_STAMP_MILLI_SEC"].ToString()));
                        info.ObjectType           = Convert.ToUInt32(item["OBJECT_TYPE"].ToString());
                        info.Reliability          = Convert.ToUInt32(item["RELIABILITY"].ToString());
                        info.PlateNum             = item["PLATE_NUM"].ToString();
                        info.PlateNumRow          = Convert.ToUInt32(item["PLATE_NUM_ROW"].ToString());
                        info.PlateColor           = Convert.ToUInt32(item["PLATE_COLOR"].ToString());
                        info.VehicleColor         = Convert.ToUInt32(item["VEHICLE_COLOR"].ToString());
                        info.VehicleType          = Convert.ToUInt32(item["VEHICLE_TYPE"].ToString());
                        info.VehicleTypeDetail    = Convert.ToUInt32(item["VEHICLE_TYPE_DETAIL"].ToString());
                        info.VehicleLabelID       = Convert.ToUInt32(item["VEHICLE_LABEL"].ToString());
                        info.VehicleLabelDetailID = Convert.ToUInt32(item["VEHICLE_LABEL_DETAIL"].ToString());
                        info.VehicleSpeed         = Convert.ToUInt32(item["VEHICLE_SPEED"].ToString());
                        info.Direction            = Convert.ToUInt32(item["DIRECTION"].ToString());
                        info.RoadWayNum           = Convert.ToUInt32(item["ROAD_WAY_NUM"].ToString());
                        info.PlateCoordRect       = new Rectangle(Convert.ToInt32(item["PLATE_COORDX"].ToString()), Convert.ToInt32(item["PLATE_COORDY"].ToString()), Convert.ToInt32(item["PLATE_COORD_WIDTH"].ToString()), Convert.ToInt32(item["PLATE_COORD_HEIGHT"].ToString()));

                        byte[] bytes3 = (byte[])item["PLAT_IMG_DATA"];
                        int    len3   = Convert.ToInt32(item["PLATE_IMG_SIZE"].ToString());
                        info.PlateImgData = IVX.DataModel.Common.GetImage(bytes3, len3);

                        info.VehiBodyCoordRect = new Rectangle(Convert.ToInt32(item["VEHIBODY_COORDX"].ToString()), Convert.ToInt32(item["VEHIBODY_COORDY"].ToString()), Convert.ToInt32(item["VEHIBODY_COORD_WIDTH"].ToString()), Convert.ToInt32(item["VEHIBODY_COORD_HEIGHT"].ToString()));
                        info.FullImgSize       = new Size(Convert.ToInt32(item["FULL_IMG_WIDTH"].ToString()), Convert.ToInt32(item["FULL_IMG_HEIGHT"].ToString()));
                        info.ComposeImgSize    = new Size(Convert.ToInt32(item["COMPOSE_IMG_WIDTH"].ToString()), Convert.ToInt32(item["COMPOSE_IMG_HEIGHT"].ToString()));

                        PlateDatas.Add(info);
                    }

                    return(PlateDatas);
                }
                catch (Exception ex)
                {
                    MyLog4Net.Container.Instance.Log.DebugWithDebugView("QueryPlateData sql error:" + ex.ToString());

                    //Framework.Container.Instance.InteractionService.ShowMessageBox("数据库失败", Framework.Environment.PROGRAM_NAME);
                    return(new List <PlateInfo>());
                }
            }
        }
Example #19
0
        private void LoadConfigFormInfo()
        {
            if (m_IsInitializing == false)
            {
                ConfigForm_Load(this, EventArgs.Empty);
            }

            this.TreeView.Nodes.Clear();
            this.Panel.Controls.Clear();

            PlateInfo[] plateInfos = GlobalSetting.PlateInfos;

            for (int iIndex = 0; iIndex < plateInfos.Length; iIndex++)
            {
                PlateInfo plateInfo = plateInfos[iIndex];

                TreeNode newTreeNodeParent = new TreeNode(plateInfo.Name);

                //
                TreeNodePlateName treeNodePlateName = new TreeNodePlateName();
                treeNodePlateName.PlateName = plateInfo.Name;

                TreeNode newTreeNodeAll = new TreeNode("所有的股票");
                newTreeNodeParent.Nodes.Add(newTreeNodeAll);

                ConfigBControl configBControlAll = new ConfigBControl();
                configBControlAll.Visible = false;
                configBControlAll.Dock    = DockStyle.Fill;

                this.m_AllConfigControlInfo.Add(newTreeNodeParent, configBControlAll);
                this.m_AllConfigControlInfo.Add(newTreeNodeAll, configBControlAll);

                for (int iIndex2 = 0; iIndex2 < plateInfo.VarietyInfos.Length; iIndex2++)
                {
                    VarietyInfo varietyInfo = plateInfo.VarietyInfos[iIndex2];

                    TreeNode newTreeNodeSub = new TreeNode(varietyInfo.Name);
                    newTreeNodeParent.Nodes.Add(newTreeNodeSub);

                    //
                    treeNodePlateName.VarietyName.Add(newTreeNodeSub, varietyInfo.Name);

                    ConfigAControl configAControlSub = new ConfigAControl();
                    configAControlSub.Visible            = false;
                    configAControlSub.Dock               = DockStyle.Fill;
                    configAControlSub.ButtonSaveChanged += new EventHandler(ConfigAControl_ButtonSaveChanged);

                    this.m_AllConfigControlInfo.Add(newTreeNodeSub, configAControlSub);

                    for (int iIndex3 = 0; iIndex3 < varietyInfo.FileInfos.Length; iIndex3++)
                    {
                        FileInfo fileInfo = varietyInfo.FileInfos[iIndex3];

                        ListViewItem listViewItemSub = new ListViewItem(fileInfo.StockName);
                        ListViewItem.ListViewSubItem listViewSubItemSub1 = new ListViewItem.ListViewSubItem(listViewItemSub, fileInfo.StockSymbol);
                        ListViewItem.ListViewSubItem listViewSubItemSub2 = new ListViewItem.ListViewSubItem(listViewItemSub, fileInfo.FilePath);

                        listViewItemSub.SubItems.Add(listViewSubItemSub1);
                        listViewItemSub.SubItems.Add(listViewSubItemSub2);

                        configAControlSub.ListView.Items.Add(listViewItemSub);

                        ListViewItem listViewItemAll = new ListViewItem(fileInfo.StockName);
                        ListViewItem.ListViewSubItem listViewSubItemAll1 = new ListViewItem.ListViewSubItem(listViewItemAll, fileInfo.StockSymbol);
                        ListViewItem.ListViewSubItem listViewSubItemAll2 = new ListViewItem.ListViewSubItem(listViewItemAll, fileInfo.FilePath);

                        listViewItemAll.SubItems.Add(listViewSubItemAll1);
                        listViewItemAll.SubItems.Add(listViewSubItemAll2);

                        configBControlAll.ListView.Items.Add(listViewItemAll);
                    }

                    this.Panel.Controls.Add(configAControlSub);
                }

                this.TreeView.Nodes.Add(newTreeNodeParent);
                this.Panel.Controls.Add(configBControlAll);

                m_PlateName.Add(newTreeNodeParent, treeNodePlateName);
            }
        }
Example #20
0
        /// <summary>
        /// 开始训练
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (this.samplePath == "")
            {
                return;
            }

            List <PlateInfo> plateSamples = new List <PlateInfo>();

            string[] subDirectories = Directory.GetDirectories(this.samplePath);
            for (int index = 0; index < subDirectories.Length; index++)
            {
                string subDirectory   = subDirectories[index];
                string shortDirectory = subDirectory.Substring(subDirectory.LastIndexOf(@"\") + 1);

                PlateCategory category = (PlateCategory)Enum.Parse(typeof(PlateCategory), shortDirectory);

                string[] fileNames = Directory.GetFiles(subDirectory, "*.jpg");

                for (int i = 0; i < fileNames.Length; i++)
                {
                    string fileName = fileNames[i];
                    this.txtinfo.AppendText(string.Format("{0}  类型:{1}\r\n", fileName, category));

                    Mat matPlate = Cv2.ImRead(fileName);

                    PlateInfo plateInfo = new PlateInfo();
                    plateInfo.PlateMat = matPlate;
                    plateInfo.Category = category;

                    plateSamples.Add(plateInfo);
                }
            }

            //将样本的元数据转化为SVM的样品数据和标签数据
            Mat trainData  = new Mat();
            Mat trainLabel = new Mat(plateSamples.Count, 1, MatType.CV_32SC1);

            for (int index = 0; index < plateSamples.Count; index++)
            {
                PlateInfo plateInfo = plateSamples[index];
                float[]   hog       = Plate_SVM.GetHog(plateInfo.PlateMat);

                if (index == 0)
                {
                    trainData = Mat.Zeros(plateSamples.Count, hog.Length, MatType.CV_32FC1);
                }

                for (int colIndex = 0; colIndex < hog.Length; colIndex++)
                {
                    trainData.Set <float>(index, colIndex, hog[colIndex]);
                }

                trainLabel.Set <int>(index, 0, (int)plateInfo.Category);

                this.txtinfo.AppendText(hog.Length.ToString() + "\r\n");
            }

            Plate_SVM.Train(trainData, trainLabel);

            this.txtinfo.AppendText("训练已完成\r\n");
        }
Example #21
0
	void CompleteRecipePanel(PlateInfo plateInfo)
	{
		CanvasRenderer[] renderers = plateInfo.UI.GetComponentsInChildren<CanvasRenderer>();
		float currentAlpha = renderers[0].GetAlpha();

		if (currentAlpha > 0)
		{
			foreach (CanvasRenderer renderer in renderers)
			{
				renderer.SetAlpha(currentAlpha - fadeOutRate);
			}
		}
		else
		{
			RemoveRecipePanel(plateInfo);

            //Increment score
            GameObject.FindObjectOfType<StarsManager>().OrdersCompleted++;

         

            //Do plate animation
            plateInfo.Bench.DoRecipeCompleteAnim();            
        }       
	}
Example #22
0
        private void InitOptionFormInfo()
        {
            this.SuspendLayout();
            {
                m_TreeNodeSetting.Nodes.Add(m_TreeNodeSettingSub);

                m_SettingControl         = new OptionAControl();
                m_SettingControl.Dock    = DockStyle.Fill;
                m_SettingControl.Visible = false;

                this.m_AllOptionControlInfo.Add(m_TreeNodeSetting, m_SettingControl);
                this.m_AllOptionControlInfo.Add(m_TreeNodeSettingSub, m_SettingControl);

                this.Panel.Controls.Add(m_SettingControl);

                m_SettingControl.CheckBoxPopupInfo.Checked = GlobalSetting.IsPopStartupInfo;
                m_SettingControl.NumericUpDownKLine.Value  = (decimal)GlobalSetting.ShowKLineLength;
                m_SettingControl.TrackBarKLine.Value       = (int)GlobalSetting.ShowKLineLength;
                m_SettingControl.SetConfigFile            += new EventHandlerNone(SettingControl_SetConfigFile);

                this.TreeView.Nodes.Add(m_TreeNodeSetting);
                //-------------------------------------

                PlateInfo[] plateInfos = GlobalSetting.PlateInfos;
                for (int iIndex = 0; iIndex < plateInfos.Length; iIndex++)
                {
                    PlateInfo plateInfo = plateInfos[iIndex];

                    TreeNode newTreeNodePlate     = new TreeNode(plateInfo.Name);
                    TreeNode newTreeNodePlateSub  = new TreeNode("常规");
                    TreeNode newTreeNodePlateSub2 = new TreeNode("所有股票");

                    newTreeNodePlate.Nodes.Add(newTreeNodePlateSub);
                    newTreeNodePlate.Nodes.Add(newTreeNodePlateSub2);

                    OptionBControl optionBControl = new OptionBControl {
                        Dock = DockStyle.Fill, Visible = false
                    };

                    this.m_AllOptionControlInfo.Add(newTreeNodePlate, optionBControl);
                    this.m_AllOptionControlInfo.Add(newTreeNodePlateSub, optionBControl);

                    this.Panel.Controls.Add(optionBControl);

                    OptionFControl optionFControl = new OptionFControl {
                        Dock = DockStyle.Fill, Visible = false
                    };

                    this.m_AllOptionControlInfo.Add(newTreeNodePlateSub2, optionFControl);

                    this.Panel.Controls.Add(optionFControl);

                    //
                    for (int iIndex2 = 0; iIndex2 < plateInfo.VarietyInfos.Length; iIndex2++)
                    {
                        VarietyInfo varietyInfo = plateInfo.VarietyInfos[iIndex2];

                        TreeNode newTreeNodePlateSub3 = new TreeNode(varietyInfo.Name);
                        newTreeNodePlate.Nodes.Add(newTreeNodePlateSub3);

                        OptionCControl optionCControlSub3 = new OptionCControl {
                            Dock = DockStyle.Fill, Visible = false
                        };

                        this.m_AllOptionControlInfo.Add(newTreeNodePlateSub3, optionCControlSub3);

                        this.Panel.Controls.Add(optionCControlSub3);

                        for (int iIndex3 = 0; iIndex3 < varietyInfo.FileInfos.Length; iIndex3++)
                        {
                            Demo.Stock.X.Common.FileInfo fileInfo = varietyInfo.FileInfos[iIndex3];

                            StockManager stockManager = GlobalStockManager.GetStockManagerByPlateAndVariety(plateInfo.Name, varietyInfo.Name);
                            StockInfo    stockInfo    = stockManager.GetStockDataByStockCode(fileInfo.StockName + "[" + fileInfo.StockSymbol + "]");

                            ListViewItem listViewItem = new ListViewItem(stockInfo.StockName, 0);
                            listViewItem.SubItems.Add(stockInfo.StockSymbol);
                            listViewItem.SubItems.Add(stockInfo.Periodicity.ToString());
                            listViewItem.SubItems.Add(stockInfo.FirstDate.ToShortDateString());
                            listViewItem.SubItems.Add(stockInfo.LastDate.ToShortDateString());
                            listViewItem.SubItems.Add(stockInfo.FirstTime.ToLongTimeString());
                            listViewItem.SubItems.Add(stockInfo.LastTime.ToLongTimeString());
                            listViewItem.SubItems.Add(stockInfo.StartTime.ToShortTimeString());
                            listViewItem.SubItems.Add(stockInfo.EndTime.ToShortTimeString());
                            listViewItem.SubItems.Add(stockInfo.CollectionDate.ToShortDateString());

                            optionCControlSub3.ListViewStockInfo.Items.Add(listViewItem);
                        }
                    }

                    this.TreeView.Nodes.Add(newTreeNodePlate);
                }
                //----------------------------------------------

                // 搜索结果
                m_TreeNodeSearch.Nodes.Add(m_TreeNodeSearchSub);

                m_SearchControl         = new OptionDControl();
                m_SearchControl.Dock    = DockStyle.Fill;
                m_SearchControl.Visible = false;

                this.m_AllOptionControlInfo.Add(m_TreeNodeSearch, m_SearchControl);
                this.m_AllOptionControlInfo.Add(m_TreeNodeSearchSub, m_SearchControl);

                this.Panel.Controls.Add(m_SearchControl);

                this.TreeView.Nodes.Add(m_TreeNodeSearch);
                //----------------------------------------------

                this.TreeView.SelectedNode = m_TreeNodeSettingSub;
            }
            this.ResumeLayout(false);
        }
Example #23
0
        private void ReloadOptionFormInfo()
        {
            this.SuspendLayout();
            {
                m_AllOptionControlInfo.Clear();
                m_CurrentOptionControl = null;

                List <Control> controlList = new List <Control>();
                foreach (Control control in this.Panel.Controls)
                {
                    if (control != m_SettingControl && control != m_SearchControl)
                    {
                        controlList.Add(control);
                    }
                }

                foreach (Control control in controlList)
                {
                    this.Panel.Controls.Remove(control);
                }

                this.TreeView.Nodes.Clear();

                this.m_AllOptionControlInfo.Add(m_TreeNodeSetting, m_SettingControl);
                this.m_AllOptionControlInfo.Add(m_TreeNodeSettingSub, m_SettingControl);

                this.TreeView.Nodes.Add(m_TreeNodeSetting);

                PlateInfo[] plateInfos = GlobalSetting.PlateInfos;
                for (int iIndex = 0; iIndex < plateInfos.Length; iIndex++)
                {
                    PlateInfo plateInfo = plateInfos[iIndex];

                    TreeNode newTreeNodePlate     = new TreeNode(plateInfo.Name);
                    TreeNode newTreeNodePlateSub  = new TreeNode("常规");
                    TreeNode newTreeNodePlateSub2 = new TreeNode("所有股票");

                    newTreeNodePlate.Nodes.Add(newTreeNodePlateSub);
                    newTreeNodePlate.Nodes.Add(newTreeNodePlateSub2);

                    OptionBControl optionBControl = new OptionBControl {
                        Dock = DockStyle.Fill, Visible = false
                    };

                    this.m_AllOptionControlInfo.Add(newTreeNodePlate, optionBControl);
                    this.m_AllOptionControlInfo.Add(newTreeNodePlateSub, optionBControl);

                    this.Panel.Controls.Add(optionBControl);

                    OptionFControl optionFControl = new OptionFControl {
                        Dock = DockStyle.Fill, Visible = false
                    };

                    this.m_AllOptionControlInfo.Add(newTreeNodePlateSub2, optionFControl);

                    this.Panel.Controls.Add(optionFControl);

                    for (int iIndex2 = 0; iIndex2 < plateInfo.VarietyInfos.Length; iIndex2++)
                    {
                        VarietyInfo varietyInfo = plateInfo.VarietyInfos[iIndex2];

                        TreeNode newTreeNodePlateSub3 = new TreeNode(varietyInfo.Name);
                        newTreeNodePlate.Nodes.Add(newTreeNodePlateSub3);

                        OptionCControl optionCControlSub3 = new OptionCControl {
                            Dock = DockStyle.Fill, Visible = false
                        };

                        this.m_AllOptionControlInfo.Add(newTreeNodePlateSub3, optionCControlSub3);

                        this.Panel.Controls.Add(optionCControlSub3);

                        for (int iIndex3 = 0; iIndex3 < varietyInfo.FileInfos.Length; iIndex3++)
                        {
                            Demo.Stock.X.Common.FileInfo fileInfo = varietyInfo.FileInfos[iIndex3];

                            StockManager stockManager = GlobalStockManager.GetStockManagerByPlateAndVariety(plateInfo.Name, varietyInfo.Name);
                            StockInfo    stockInfo    = stockManager.GetStockDataByStockCode(GlobalSetting.GetStockCode(fileInfo.StockName, fileInfo.StockSymbol));
                            if (stockInfo == null)
                            {
                                continue;
                            }

                            ListViewItem listViewItem = new ListViewItem(stockInfo.StockName, 0);
                            listViewItem.SubItems.Add(stockInfo.StockSymbol);
                            listViewItem.SubItems.Add(stockInfo.Periodicity.ToString());
                            listViewItem.SubItems.Add(stockInfo.FirstDate.ToShortDateString());
                            listViewItem.SubItems.Add(stockInfo.LastDate.ToShortDateString());
                            listViewItem.SubItems.Add(stockInfo.FirstTime.ToLongTimeString());
                            listViewItem.SubItems.Add(stockInfo.LastTime.ToLongTimeString());
                            listViewItem.SubItems.Add(stockInfo.StartTime.ToShortTimeString());
                            listViewItem.SubItems.Add(stockInfo.EndTime.ToShortTimeString());
                            listViewItem.SubItems.Add(stockInfo.CollectionDate.ToShortDateString());

                            optionCControlSub3.ListViewStockInfo.Items.Add(listViewItem);
                        }
                    }

                    this.TreeView.Nodes.Add(newTreeNodePlate);
                }

                // 搜索结果
                this.m_AllOptionControlInfo.Add(m_TreeNodeSearch, m_SearchControl);
                this.m_AllOptionControlInfo.Add(m_TreeNodeSearchSub, m_SearchControl);

                m_TreeNodeSearch.Nodes.Clear();
                m_TreeNodeSearch.Nodes.Add(m_TreeNodeSearchSub);

                this.TreeView.Nodes.Add(m_TreeNodeSearch);

                this.TreeView.SelectedNode = m_TreeNodeSetting;
            }
            this.ResumeLayout(false);
        }
Example #24
0
    void createObjectsFromDataset()
    {
        for (int i = 0; i < maxCars; i++)
        {
            PlateInfo plateInfo = dataset1.data[i];

            if (plateInfo.Ruta.Count >= 2)
            {
                GameObject tmpSpawnPoint;

                tmpSpawnPoint = new GameObject();
                Transform tmpTransform = tmpSpawnPoint.GetComponent <Transform>();

                Transform[] tmpTransforms = { spawn1.transform, spawn2.transform, spawn3.transform, spawn4.transform, spawn5.transform, spawn11.transform, spawn12.transform };
                foreach (var tmpVar1 in tmpTransforms)
                {
                    //Debug.Log("Getting transforms: " + tmpVar1.transform.position.x + " | " + tmpVar1.position.y + " | " + tmpVar1.position.z);
                }
                bool shouldIContinue = true;
                try
                {
                    switch (plateInfo.Ruta[0])
                    {
                    case 1:
                        tmpTransform.position = tmpTransforms[plateInfo.Ruta[0] - 1].position;
                        tmpTransform.rotation = tmpTransforms[plateInfo.Ruta[0] - 1].rotation;
                        break;

                    case 2:
                        tmpTransform.position = tmpTransforms[plateInfo.Ruta[0] - 1].position;
                        tmpTransform.rotation = tmpTransforms[plateInfo.Ruta[0] - 1].rotation;
                        break;

                    case 3:
                        tmpTransform.position = tmpTransforms[plateInfo.Ruta[0] - 1].position;
                        tmpTransform.rotation = tmpTransforms[plateInfo.Ruta[0] - 1].rotation;
                        break;

                    case 4:
                        tmpTransform.position = tmpTransforms[plateInfo.Ruta[0] - 1].position;
                        tmpTransform.rotation = tmpTransforms[plateInfo.Ruta[0] - 1].rotation;
                        break;

                    case 5:
                        tmpTransform.position = tmpTransforms[plateInfo.Ruta[0] - 1].position;
                        tmpTransform.rotation = tmpTransforms[plateInfo.Ruta[0] - 1].rotation;
                        break;

                    case 11:
                        tmpTransform.position = tmpTransforms[5].position;
                        tmpTransform.rotation = tmpTransforms[5].rotation;
                        break;

                    case 12:
                        tmpTransform.position = tmpTransforms[6].position;
                        tmpTransform.rotation = tmpTransforms[6].rotation;
                        break;

                    default:
                        shouldIContinue = false;
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Debug.Log("Error para ruta: " + plateInfo.Ruta[0]);
                }

                if (shouldIContinue)
                {
                    //Debug.Log("Detected<" + plateInfo.Ruta[0] + ">: " + tmpTransform.position.x + " | " + tmpTransform.position.y + " | " + tmpTransform.position.z);

                    if (!nodeQueueTransform.ContainsKey(plateInfo.Ruta[0].ToString()))
                    {
                        Debug.Log("New Plate <" + plateInfo.Ruta[0] + "> " + tmpSpawnPoint.transform.position.x + " | " + tmpSpawnPoint.transform.position.y + " | " + tmpSpawnPoint.transform.position.z);
                        nodeQueueTransform.Add(plateInfo.Ruta[0].ToString(), tmpSpawnPoint);
                        spawnsCount.Add(plateInfo.Ruta[0], 1);
                    }
                    else
                    {
                        float displacementForSpawn = 15.0f;
                        tmpTransform.position += new Vector3(0, 0, displacementForSpawn * spawnsCount[plateInfo.Ruta[0]]);
                        nodeQueueTransform[plateInfo.Ruta[0].ToString()] = tmpSpawnPoint;
                        spawnsCount[plateInfo.Ruta[0]]++;
                    }
                    //Debug.Log("Creating car <" + plateInfo.Ruta[0] + "> at: " + nodeQueueTransform[plateInfo.Ruta[0].ToString()].GetComponent<Transform>().position.x + " , " + nodeQueueTransform[plateInfo.Ruta[0].ToString()].GetComponent<Transform>().position.y + " , " + nodeQueueTransform[plateInfo.Ruta[0].ToString()].GetComponent<Transform>().position.z);

                    GameObject tmpObject = Instantiate(carPrefab, nodeQueueTransform[plateInfo.Ruta[0].ToString()].GetComponent <Transform>());

                    List <Path> tmpPathList = new List <Path>();
                    for (int j = 2; j < plateInfo.Ruta.Count; j++)
                    {
                        Debug.Log("Ruta: " + plateInfo.Ruta[j - 1] + " | " + plateInfo.Ruta[j] + " | Duration: " + plateInfo.Viaje[j - 1]);
                        //Debug.Log("Finding: " + "Path " + plateInfo.Ruta[j - 1] + "-" + plateInfo.Ruta[j]);

                        string tmpDictionaryKey = plateInfo.Ruta[j - 1] + "-" + plateInfo.Ruta[j];
                        tmpPathList.Add(GameObject.Find("Path " + plateInfo.Ruta[j - 1] + "-" + plateInfo.Ruta[j]).GetComponent <Path>());
                        tmpPathList[tmpPathList.Count - 1].pathName = tmpDictionaryKey;


                        if (carDensity.ContainsKey(tmpDictionaryKey))
                        {
                            carDensity[tmpDictionaryKey]++;
                        }
                        else
                        {
                            carDensity.Add(tmpDictionaryKey, 1);
                        }
                    }
                    tmpObject.GetComponent <CarEngine>().paths = tmpPathList;
                    //Debug.Log("Start: " + plateInfo.start);
                }
            }
            else
            {
                //Debug.Log("No hay suficientes puntos de ruta <" + plateInfo.plate + ">");
            }
        }
    }
Example #25
0
        //颜色法
        private static List <PlateInfo> LocatePlatesByColor(Mat matSource,
                                                            int blur_Size         = 5,
                                                            int morph_Size_Width  = 17,
                                                            int morph_Size_Height = 3,
                                                            int minWidth          = 60, int maxWidth      = 180,
                                                            int minHeight         = 18, int maxHeight     = 80,
                                                            float minRatio        = 0.15f, float maxRatio = 0.70f)
        {
            List <PlateInfo> plateInfos = new List <PlateInfo>();

            if (matSource.Empty())
            {
                return(plateInfos);
            }
            Mat hsv = matSource.CvtColor(ColorConversionCodes.BGR2HSV);

            Mat[] hsvSplits = hsv.Split();
            hsvSplits[2] = hsvSplits[2].EqualizeHist();
            Mat hsvEqualizeHist = new Mat();

            Cv2.Merge(hsvSplits, hsvEqualizeHist);
            Scalar blueStart   = new Scalar(100, 70, 70);
            Scalar blueEnd     = new Scalar(140, 255, 255);
            Mat    blue        = hsvEqualizeHist.InRange(blueStart, blueEnd);
            Scalar yellowStart = new Scalar(15, 70, 70);
            Scalar yellowEnd   = new Scalar(40, 255, 255);
            Mat    yellow      = hsvEqualizeHist.InRange(yellowStart, yellowEnd);
            Mat    add         = blue + yellow;
            Mat    threshold   = add.Threshold(0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
            Mat    element     = Cv2.GetStructuringElement(MorphShapes.Rect,
                                                           new OpenCvSharp.Size(morph_Size_Width,
                                                                                morph_Size_Height));
            Mat threshold_Close = threshold.MorphologyEx(MorphTypes.Close, element);
            Mat element_Erode   = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3,
                                                                                                   3));
            Mat threshold_Erode = threshold_Close.Erode(element_Erode);

            OpenCvSharp.Point[][] contours   = null;
            HierarchyIndex[]      hierarchys = null;
            Cv2.FindContours(threshold_Erode, out contours, out hierarchys,
                             RetrievalModes.External, ContourApproximationModes.ApproxNone);
            for (int index = 0; index < contours.Length; index++)
            {
                Rect rectROI = Cv2.BoundingRect(contours[index]);
                if (VerifyPlateSize(rectROI.Size,
                                    minWidth,
                                    maxWidth,
                                    minHeight,
                                    maxHeight,
                                    minRatio,
                                    maxRatio))
                {
                    Mat           matROI        = matSource.SubMat(rectROI);
                    PlateCategory plateCategory = PlateCategory_SVM.Test(matROI);
                    if (plateCategory == PlateCategory.非车牌)
                    {
                        continue;
                    }
                    PlateInfo plateInfo = new PlateInfo();
                    plateInfo.OriginalRect      = rectROI;
                    plateInfo.OriginalMat       = matROI;
                    plateInfo.PlateCategory     = plateCategory;
                    plateInfo.PlateLocateMethod = PlateLocateMethod.颜色法;
                    plateInfos.Add(plateInfo);
                }
            }
            return(plateInfos);
        }
Example #26
0
	bool CheckPlateRecipeForChanges(PlateInfo plateInfo)
	{
		var existingRecipe = plateInfo.Recipe;
		var newRecipe = plateInfo.Bench.Recipe;

		if (existingRecipe != newRecipe)
		{
			// recipe changed
			if (newRecipe != null)
			{
				// new recipe
				if (existingRecipe != null)
				{
					// old still around
					RemoveRecipePanel(plateInfo);
				}

				plateInfo.Recipe = newRecipe;
				plateInfo.UI = MakeRecipePanel(plateInfo);
			}

			return true;
		}

		return false;
	}
Example #27
0
        private void SendAlarm(PlateInfo plateInfo, string milestoneCameraName, FQID bookmarkFQID)//, string plateFromAlertList, string descFromAlertList)
        {
            FQID fqid = MilestoneServer.GetCameraByName(milestoneCameraName);

            DateTime temp = AlertListHelper.GetLastWriteTime();

            if (temp != lastAlertUpdateTime)
            {
                AlertListHelper.LoadAlertList(dicBlack);
                lastAlertUpdateTime = temp;
                Program.Log.Info("Reload Alert list");
            }

            string plateFromAlertList = plateInfo.BestPlateNumber;

            bool existsInAlertList = dicBlack.ContainsKey(plateInfo.BestPlateNumber);

            if (!existsInAlertList)
            {
                Program.Log.Info($"{plateFromAlertList} not listed in the alert list.");
                Program.Log.Info($"looking if any candidates listed in the alert list");

                existsInAlertList = plateInfo.CandidatesPlate.Split(',').Any(p => dicBlack.ContainsKey(p));
                if (existsInAlertList)
                {
                    plateFromAlertList = plateInfo.CandidatesPlate.Split(',').FirstOrDefault(p => dicBlack.ContainsKey(p));
                    Program.Log.Info($"Candidate {plateFromAlertList} listed in the alert list");
                }
                else
                {
                    Program.Log.Info($"No any candidates plate number listed in the alert list");
                }
            }
            else
            {
                Program.Log.Info($"{plateFromAlertList} found in the alert list");
            }

            if (existsInAlertList)
            {
                string descFromAlertList = dicBlack[plateFromAlertList];

                Program.Log.Info($"Sending an alert for {plateInfo.BestPlateNumber}");

                string cameraName = MilestoneServer.GetCameraName(fqid.ObjectId);

                EventSource eventSource = new EventSource()
                {
                    FQID = fqid,
                    Name = cameraName
                };

                EventHeader eventHeader = new EventHeader()
                {
                    ID              = Guid.NewGuid(),
                    Class           = "Analytics",
                    Type            = null,
                    Timestamp       = plateInfo.EpochStart,
                    Message         = "OpenALPR Alarm",
                    Name            = plateInfo.BestPlateNumber,
                    Source          = eventSource,
                    Priority        = 2,
                    PriorityName    = "Medium",
                    MessageId       = Guid.Empty,
                    CustomTag       = plateFromAlertList,// the value we got from the config file
                    ExpireTimestamp = DateTime.Now.AddDays(EventExpireAfterDays),
                    Version         = null
                };


                AnalyticsEvent analyticsEvent = new AnalyticsEvent();
                analyticsEvent.EventHeader = eventHeader;
                analyticsEvent.Location    = cameraName;
                analyticsEvent.Description = "OpenALPR Alarm Event";
                analyticsEvent.Vendor      = new Vendor {
                    CustomData = plateInfo.ToString()
                };
                //analyticsEvent.Vendor.Name = "OpenAlpr";


                EnvironmentManager.Instance.SendMessage(
                    new VideoOS.Platform.Messaging.Message(MessageId.Server.NewEventCommand)
                {
                    Data = analyticsEvent
                });

                Alarm alarm = new Alarm()
                {
                    EventHeader   = eventHeader,
                    StateName     = "In progress",
                    State         = 4,
                    AssignedTo    = null,
                    Count         = 0,
                    Description   = descFromAlertList,
                    EndTime       = plateInfo.EpochStart.AddSeconds(EpochEndSecondsAfter),
                    ReferenceList = new ReferenceList {
                        new Reference {
                            FQID = bookmarkFQID
                        }
                    },
                    StartTime = plateInfo.EpochStart.AddSeconds(-EpochStartSecondsBefore),
                    Vendor    = new Vendor {
                        CustomData = plateInfo.ToString()
                    }
                };

                try
                {
                    using (Impersonation impersonation = new Impersonation(BuiltinUser.NetworkService))
                        EnvironmentManager.Instance.SendMessage(new Message(MessageId.Server.NewAlarmCommand)
                        {
                            Data = alarm
                        });
                }
                catch (Exception ex)
                {
                    Program.Log.Error(null, ex);
                }
            }
        }
Example #28
0
        public static List <PlateInfo> LocatePlatesForAutoSample(Mat matSource,
                                                                 out Mat matProcess,
                                                                 int blur_Size         = 5,
                                                                 int sobel_Scale       = 1,
                                                                 int sobel_Delta       = 0,
                                                                 int sobel_X_Weight    = 1,
                                                                 int sobel_Y_Weight    = 0,
                                                                 int morph_Size_Width  = 17,
                                                                 int morph_Size_Height = 3,
                                                                 int minWidth          = 60, int maxWidth      = 180,
                                                                 int minHeight         = 18, int maxHeight     = 80,
                                                                 float minRatio        = 0.15f, float maxRatio = 0.70f)
        {
            List <PlateInfo> plateInfos = new List <PlateInfo>();

            Mat gray = null;
            Mat blur = null;

            if (matSource.Empty() || matSource.Rows == 0 || matSource.Cols == 0)
            {
                matProcess = new Mat(0, 0, MatType.CV_8UC1);
                return(plateInfos);
            }
            //灰度图
            gray = matSource.CvtColor(ColorConversionCodes.BGR2GRAY);
            //高斯模糊图
            blur = gray.GaussianBlur(new OpenCvSharp.Size(blur_Size, blur_Size), 0, 0, BorderTypes.Default);
            //HSV图
            Mat hsv = matSource.CvtColor(ColorConversionCodes.BGR2HSV);

            //将HSV图分成H、S、V通道图
            Mat[] hsvSplits = hsv.Split();
            hsvSplits[2] = hsvSplits[2].EqualizeHist();
            Mat hsvEqualizeHist = new Mat();

            //合并通道图
            Cv2.Merge(hsvSplits, hsvEqualizeHist);

            //提取蓝色
            Scalar blueStart = new Scalar(100, 70, 70);
            Scalar blueEnd   = new Scalar(140, 255, 255);
            Mat    blue      = hsvEqualizeHist.InRange(blueStart, blueEnd);
            //提取黄色
            Scalar yellowStart = new Scalar(15, 70, 70);
            Scalar yellowEnd   = new Scalar(40, 255, 255);
            Mat    yellow      = hsvEqualizeHist.InRange(yellowStart, yellowEnd);

            Mat add = blue + yellow;
            //二值化
            Mat threshold = add.Threshold(0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
            Mat element   = Cv2.GetStructuringElement(MorphShapes.Rect,
                                                      new OpenCvSharp.Size(morph_Size_Width, morph_Size_Height));

            //闭操作
            Mat threshold_Close = threshold.MorphologyEx(MorphTypes.Close, element);
            Mat element_Erode   = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3,
                                                                                                   3));

            Mat threshold_Erode = threshold_Close.Erode(element_Erode);

            matProcess = threshold_Erode;
            OpenCvSharp.Point[][] contours   = null;
            HierarchyIndex[]      hierarchys = null;
            Cv2.FindContours(threshold_Erode, out contours, out hierarchys,
                             RetrievalModes.External, ContourApproximationModes.ApproxNone);
            int isPlateCount = 0;

            for (int index = 0; index < contours.Length; index++)
            {
                RotatedRect rotatedRect = Cv2.MinAreaRect(contours[index]);
                Rect        rectROI     = Cv2.BoundingRect(contours[index]);
                if (VerifyPlateSize(rectROI.Size,
                                    minWidth,
                                    maxWidth,
                                    minHeight,
                                    maxHeight,
                                    minRatio,
                                    maxRatio))
                {
                    Mat           matROI        = matSource.SubMat(rectROI);
                    PlateCategory plateCategory = PlateCategory_SVM.Test(matROI);
                    if (plateCategory != PlateCategory.非车牌)
                    {
                        isPlateCount++;
                    }
                    PlateInfo plateInfo = new PlateInfo();
                    plateInfo.RotatedRect       = rotatedRect;
                    plateInfo.OriginalRect      = rectROI;
                    plateInfo.OriginalMat       = matROI;
                    plateInfo.PlateCategory     = plateCategory;
                    plateInfo.PlateLocateMethod = PlateLocateMethod.颜色法;
                    plateInfos.Add(plateInfo);
                }
            }
            if (isPlateCount > 0)
            {
                return(plateInfos);
            }
            blur = matSource.GaussianBlur(new OpenCvSharp.Size(blur_Size, blur_Size), 0, 0,
                                          BorderTypes.Default);
            gray = blur.CvtColor(ColorConversionCodes.BGR2GRAY);
            // 对图像进行Sobel 运算,得到的是图像的一阶水平方向导数。
            // Generate grad_x and grad_y
            MatType ddepth     = MatType.CV_16S;
            Mat     grad_x     = gray.Sobel(ddepth, 1, 0, 3, sobel_Scale, sobel_Delta, BorderTypes.Default);
            Mat     abs_grad_x = grad_x.ConvertScaleAbs();
            Mat     grad_y     = gray.Sobel(ddepth, 0, 1, 3, sobel_Scale, sobel_Delta, BorderTypes.Default);
            Mat     abs_grad_y = grad_y.ConvertScaleAbs();
            Mat     grad       = new Mat();

            Cv2.AddWeighted(abs_grad_x, sobel_X_Weight, abs_grad_y, sobel_Y_Weight, 0, grad);
            // 对图像进行二值化。将灰度图像(每个像素点有256 个取值可能)转化为二值图像(每个像素点仅有1 和0 两个取值可能)。
            threshold = grad.Threshold(0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
            // 使用闭操作。对图像进?行行闭操作以后,可以看到车牌区域被连接成一个矩形装的区域。
            element = Cv2.GetStructuringElement(MorphShapes.Rect,
                                                new OpenCvSharp.Size(morph_Size_Width,
                                                                     morph_Size_Height));
            threshold_Close = threshold.MorphologyEx(MorphTypes.Close, element);
            element_Erode   = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(5, 5));
            threshold_Erode = threshold_Close.Erode(element_Erode);
            matProcess      = threshold_Erode;
            // Find 轮廓 of possibles plates 求轮廓。求出图中所有的轮廓。这个算法会把全图的轮廓都计算出来,因此要进? 行行筛选。
            contours   = null;
            hierarchys = null;

            Cv2.FindContours(threshold_Erode, out contours, out hierarchys,
                             RetrievalModes.External, ContourApproximationModes.ApproxNone);
            // 筛选。对轮廓求最?小外接矩形,然后验证,不不满?足条件的淘汰。
            for (int index = 0; index < contours.Length; index++)
            {
                Rect rectROI = Cv2.BoundingRect(contours[index]);
                if (VerifyPlateSize(rectROI.Size,
                                    minWidth,
                                    maxWidth,
                                    minHeight,
                                    maxHeight,
                                    minRatio,
                                    maxRatio))
                {
                    RotatedRect   rotatedRect   = Cv2.MinAreaRect(contours[index]);
                    Mat           matROI        = matSource.SubMat(rectROI);
                    PlateCategory plateCategory = PlateCategory_SVM.Test(matROI);
                    PlateInfo     plateInfo     = new PlateInfo();
                    plateInfo.RotatedRect       = rotatedRect;
                    plateInfo.OriginalRect      = rectROI;
                    plateInfo.OriginalMat       = matROI;
                    plateInfo.PlateCategory     = plateCategory;
                    plateInfo.PlateLocateMethod = PlateLocateMethod.Sobel法;
                    plateInfos.Add(plateInfo);
                }
            }
            return(plateInfos);
        }
Example #29
0
 //保存图片的方式
 public static void SavePlateSample(PlateInfo plateInfo, string fileName)
 {
     plateInfo.OriginalMat.SaveImage(fileName);
 }
Example #30
0
        private void SaveConfigFormInfo()
        {
            List <PlateInfo> plateInfoList = new List <PlateInfo>();

            for (int iIndex = 0; iIndex < this.TreeView.Nodes.Count; iIndex++)
            {
                TreeNode treeNodeParent = this.TreeView.Nodes[iIndex];
                if (treeNodeParent == null)
                {
                    continue;
                }

                PlateInfo plateInfo = new PlateInfo();
                plateInfo.Name         = treeNodeParent.Text;
                plateInfo.VarietyInfos = new VarietyInfo[0];

                plateInfoList.Add(plateInfo);

                List <VarietyInfo> varietyInfoList = new List <VarietyInfo>();

                for (int iIndex2 = 1; iIndex2 < treeNodeParent.Nodes.Count; iIndex2++)
                {
                    TreeNode treeNodeParentSub = treeNodeParent.Nodes[iIndex2];
                    if (treeNodeParentSub == null)
                    {
                        continue;
                    }

                    VarietyInfo varietyInfo = new VarietyInfo();
                    varietyInfo.Name      = treeNodeParentSub.Text;
                    varietyInfo.FileInfos = new FileInfo[0];

                    varietyInfoList.Add(varietyInfo);

                    UserControl outUserControl = null;
                    if (m_AllConfigControlInfo.TryGetValue(treeNodeParentSub, out outUserControl) == true)
                    {
                        ConfigAControl outConfigAControl = outUserControl as ConfigAControl;
                        if (outConfigAControl != null)
                        {
                            List <FileInfo> fileInfoList = new List <FileInfo>();

                            for (int iIndex3 = 0; iIndex3 < outConfigAControl.ListView.Items.Count; iIndex3++)
                            {
                                ListViewItem listViewItem = outConfigAControl.ListView.Items[iIndex3];

                                FileInfo fileInfo = new FileInfo();
                                fileInfo.StockName   = listViewItem.Text;
                                fileInfo.StockSymbol = listViewItem.SubItems[1].Text;
                                fileInfo.FilePath    = listViewItem.SubItems[2].Text;

                                fileInfoList.Add(fileInfo);
                            }

                            varietyInfo.FileInfos = fileInfoList.ToArray();
                        }
                    }
                }

                plateInfo.VarietyInfos = varietyInfoList.ToArray();
            }

            GlobalSetting.SaveConfigSetting(GlobalSetting.ConfigFilePath, plateInfoList.ToArray());
        }
Example #31
0
	public void RemoveRecipePanel(PlateInfo plateInfo)
	{
		Destroy(plateInfo.UI);
		plateInfo.Recipe = null;
		plateInfo.UI = null;
		plateInfo.Bench.Clear();
	}
Example #32
0
        //对一些特殊车牌经行检测和处理
        private static void CheckLeftAndRightToRemove(PlateInfo plateInfo)
        {
            if (plateInfo.PlateCategory == PlateCategory.非车牌)
            {
                return;
            }
            if (plateInfo.CharInfos == null)
            {
                return;
            }
            if (plateInfo.CharInfos.Count < 4)
            {
                return;
            }
            int charCount = plateInfo.CharInfos.Count;

            //两头的先除开,去掉中间的汉字
            for (int index = charCount - 1 - 1; index > 0 + 1; index--)
            {
                CharInfo charInfo      = plateInfo.CharInfos[index];
                int      charInfoValue = (int)charInfo.PlateChar;
                if (charInfoValue >= (int)PlateChar.京 && charInfoValue <= (int)PlateChar.川)
                {
                    plateInfo.CharInfos.RemoveAt(index);
                }
            }
            charCount = plateInfo.CharInfos.Count;
            CharInfo second          = plateInfo.CharInfos[1];
            int      secondValue     = (int)second.PlateChar;
            CharInfo lastSecond      = plateInfo.CharInfos[charCount - 2];
            int      lastSecondValue = (int)lastSecond.PlateChar;

            switch (plateInfo.PlateCategory)
            {
            case PlateCategory.普通车牌:
                break;

            case PlateCategory.普通车牌_两行:
                break;
            }
            charCount = plateInfo.CharInfos.Count;
            if (charCount < 7)
            {
                return;
            }
            CharInfo first      = plateInfo.CharInfos[0];
            int      firstValue = (int)first.PlateChar;

            second      = plateInfo.CharInfos[1];
            secondValue = (int)second.PlateChar;
            CharInfo lastFirst      = plateInfo.CharInfos[charCount - 1];
            int      lastFirstValue = (int)lastFirst.PlateChar;

            switch (plateInfo.PlateCategory)
            {
            case PlateCategory.普通车牌:
                if (lastFirstValue >= (int)PlateChar.京 && lastFirstValue <= (int)PlateChar.川)
                {
                    plateInfo.CharInfos.RemoveAt(charCount - 1); //去掉最后⼀一位汉字
                }
                if (firstValue <= (int)PlateChar.点)
                {
                    plateInfo.CharInfos.Remove(first); //如果第⼀一位为非汉字,删除
                }
                if (secondValue >= (int)PlateChar._0 && secondValue <= (int)PlateChar._9)
                {
                    plateInfo.CharInfos.Remove(second); //如果第⼆二位为数字,删除
                }
                break;
            }
        }
Example #33
0
        private void SendAlarm(PlateInfo plateInfo, string milestoneCameraName, FQID bookmarkFQID)//, string plateFromAlertList, string descFromAlertList)
        {
            var fqid = MilestoneServer.GetCameraByName(milestoneCameraName);

            var temp = AlertListHelper.GetLastWriteTime();

            if (temp != lastAlertUpdateTime)
            {
                AlertListHelper.LoadAlertList(dicBlack);
                lastAlertUpdateTime = temp;
                Program.Logger.Log.Info("Reload Alert list");
            }

            var plateFromAlertList = plateInfo.BestPlateNumber;

            var existsInAlertList = dicBlack.ContainsKey(plateInfo.BestPlateNumber);

            if (!existsInAlertList)
            {
                Program.Logger.Log.Info($"{plateFromAlertList} not listed in the alert list.");
                Program.Logger.Log.Info($"looking if any candidates listed in the alert list");

                existsInAlertList = plateInfo.CandidatesPlate.Split(',').Any(p => dicBlack.ContainsKey(p));
                if (existsInAlertList)
                {
                    plateFromAlertList = plateInfo.CandidatesPlate.Split(',').FirstOrDefault(p => dicBlack.ContainsKey(p));
                    Program.Logger.Log.Info($"Candidate {plateFromAlertList} listed in the alert list");
                }
                else
                {
                    Program.Logger.Log.Info($"No any candidates plate number listed in the alert list");
                }
            }
            else
            {
                Program.Logger.Log.Info($"{plateFromAlertList} found in the alert list");
            }

            if (existsInAlertList)
            {
                var descFromAlertList = dicBlack[plateFromAlertList];

                Program.Logger.Log.Info($"Sending an alert for {plateInfo.BestPlateNumber}");

                var cameraName = MilestoneServer.GetCameraName(fqid.ObjectId);

                var eventSource = new EventSource()
                {
                    FQID = fqid,
                    Name = cameraName,
                    //Description = "",
                    //ExtensionData =
                };

                var eventHeader = new EventHeader()
                {
                    //The unique ID of the event.
                    ID = Guid.NewGuid(),

                    //The class of the event, e.g. "Analytics", "Generic", "User-defined".
                    Class = "Analytics",

                    //The type - a sub-classification - of the event, if applicable.
                    Type = null,

                    //The time of the event.
                    Timestamp = plateInfo.EpochStart,

                    //The event message. This is the field that will be matched with the AlarmDefinition message when sending this event to the Event Server.
                    Message = "OpenALPR Alarm",

                    //The event name.
                    Name = plateInfo.BestPlateNumber,

                    //The source of the event. This can represent e.g. a camera, a microphone, a user-defined event, etc.
                    Source = eventSource,

                    //The priority of the event.
                    Priority = 2,

                    //The priority name of the event.
                    PriorityName = "Medium",

                    //optional
                    //The message id of the event. The message id coorsponds to the ID part returned in ItemManager.GetKnownEventTypes.
                    MessageId = Guid.Empty,

                    //A custom tag set by the user to filter the events.
                    CustomTag = plateFromAlertList,// the value we got from the config file

                    //The expire time of the event. The event will be deleted from the event database when the time is reached. When creating events a value of DateTime.MinValue (default value) indicates that the default event expire time should be used.
                    ExpireTimestamp = DateTime.Now.AddDays(EventExpireAfterDays),

                    //ExtensionData = System.Runtime .Serialization.
                    //The version of this document schema.
                    Version = null
                };

                var alarm = new Alarm()
                {
                    //The EventHeader, containing information common for all Milestone events.
                    EventHeader = eventHeader,

                    //The current state name.
                    StateName = "In progress",

                    //The current state of the alarm. 0: Any 1: New 4: In progress 9: On hold 11: Closed.
                    State = 4,

                    //The user to which the alarm is currently assigned. Can be seen in the Smart Client dropdown
                    AssignedTo = null,//Environment.UserName,

                    // Other fields could be filled out, e.g. objectList

                    //The current category of the alarm. This should be created first on the Client Management under Alarms then Alaem Data Settings
                    //Category = 0,

                    //The current category name.
                    //CategoryName = null,//"Critical",

                    //The count value, if the alarm is a counting alarm. Default: 0 (no count).
                    Count = 0,

                    //The description of the alarm.
                    Description = descFromAlertList,

                    //The end time of the alarm, if it takes plate over a period of time.
                    EndTime = plateInfo.EpochStart.AddSeconds(EpochEndSecondsAfter),

                    //  ExtensionData =

                    //The location of the alarm (this will typically be the same as the camera's location).
                    //Location = null,

                    //The ObjectList, containing information about the detected object(s) in the scene. //new AnalyticsObjectList()
                    //ObjectList = null,

                    // The ReferenceList, containing any number of references to other entities in the system, e.g. alarms or cameras, by FQID.
                    ReferenceList = new ReferenceList {
                        new Reference {
                            FQID = bookmarkFQID
                        }
                    },                                                                            // save bookmark id

                    //The RuleList, containing information contains information about the rule(s), which triggered the alarm.
                    //RuleList = null,//new RuleList(),

                    //The SnapshotList, containing any number of images related to the alarm. If the Source is a camera, it is not neccesary to attach a snapshot from that camera at the time of the alarm.
                    //SnapshotList = null,// new SnapshotList(),

                    //The start time of the alarm, if it takes plate over a period of time.
                    StartTime = plateInfo.EpochStart.AddSeconds(-EpochStartSecondsBefore),

                    //The Vendor, containing information about the analytics vendor including any custom data.
                    Vendor = new Vendor {
                        CustomData = plateInfo.ToString()
                    }                                                         // save json data
                };

                // Send the Alarm directly to the EventServer, to store in the Alarm database. No rule is being activated.
                try
                {
                    using (var impersonation = new Impersonation(BuiltinUser.NetworkService))
                        EnvironmentManager.Instance.SendMessage(new Message(MessageId.Server.NewAlarmCommand)
                        {
                            Data = alarm
                        });
                }
                catch (Exception ex)
                {
                    Program.Logger.Log.Error(null, ex);
                }
            }
        }
Example #34
0
        private static List <PlateInfo> LocatePlatesBySobel(Mat matSource,
                                                            int blur_Size         = 5,
                                                            int sobel_Scale       = 1,
                                                            int sobel_Delta       = 0,
                                                            int sobel_X_Weight    = 1,
                                                            int sobel_Y_Weight    = 0,
                                                            int morph_Size_Width  = 17,
                                                            int morph_Size_Height = 3,
                                                            int minWidth          = 60, int maxWidth      = 180,
                                                            int minHeight         = 18, int maxHeight     = 80,
                                                            float minRatio        = 0.15f, float maxRatio = 0.70f)
        {
            List <PlateInfo> plateInfos = new List <PlateInfo>();

            if (matSource.Empty())
            {
                return(plateInfos);
            }
            Mat blur = null;
            Mat gray = null;

            blur = matSource.GaussianBlur(new OpenCvSharp.Size(blur_Size, blur_Size), 0, 0,
                                          BorderTypes.Default);
            gray = blur.CvtColor(ColorConversionCodes.BGR2GRAY);
            // 对图像进行Sobel 运算,得到的是图像的一阶水平方向导数。
            // Generate grad_x and grad_y
            MatType ddepth     = MatType.CV_16S;
            Mat     grad_x     = gray.Sobel(ddepth, 1, 0, 3, sobel_Scale, sobel_Delta, BorderTypes.Default);
            Mat     abs_grad_x = grad_x.ConvertScaleAbs();
            Mat     grad_y     = gray.Sobel(ddepth, 0, 1, 3, sobel_Scale, sobel_Delta, BorderTypes.Default);
            Mat     abs_grad_y = grad_y.ConvertScaleAbs();
            Mat     grad       = new Mat();

            Cv2.AddWeighted(abs_grad_x, sobel_X_Weight, abs_grad_y, sobel_Y_Weight, 0, grad);
            // 对图像进行二值化。将灰度图像(每个像素点有256 个取值可能)转化为二值图像(每个像素点仅有1 和0 两个取值可能)。
            Mat threshold = grad.Threshold(0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
            // 使用闭操作。对图像进行闭操作以后,可以看到车牌区域被连接成一个矩形装的区域。
            Mat element = Cv2.GetStructuringElement(MorphShapes.Rect,
                                                    new OpenCvSharp.Size(morph_Size_Width,
                                                                         morph_Size_Height));
            Mat threshold_Close = threshold.MorphologyEx(MorphTypes.Close, element);
            Mat element_Erode   = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(5,
                                                                                                   5));
            Mat threshold_Erode = threshold_Close.Erode(element_Erode);

            // Find 轮廓 of possibles plates 求轮廓。求出图中所有的轮廓。这个算法会把全图的轮廓都计算出来,因此要进行筛选。
            OpenCvSharp.Point[][] contours   = null;
            HierarchyIndex[]      hierarchys = null;
            Cv2.FindContours(threshold_Erode, out contours, out hierarchys,
                             RetrievalModes.External, ContourApproximationModes.ApproxNone);
            // 筛选。对轮廓求最小外接矩形,然后验证,不满足条件的淘汰。
            for (int index = 0; index < contours.Length; index++)
            {
                Rect rectROI = Cv2.BoundingRect(contours[index]);
                if (VerifyPlateSize(rectROI.Size,
                                    minWidth,
                                    maxWidth,
                                    minHeight,
                                    maxHeight,
                                    minRatio,
                                    maxRatio))
                {
                    Mat           matROI        = matSource.SubMat(rectROI);
                    PlateCategory plateCategory = PlateCategory_SVM.Test(matROI);
                    if (plateCategory == PlateCategory.非车牌)
                    {
                        continue;
                    }
                    PlateInfo plateInfo = new PlateInfo();
                    plateInfo.OriginalRect      = rectROI;
                    plateInfo.OriginalMat       = matROI;
                    plateInfo.PlateCategory     = plateCategory;
                    plateInfo.PlateLocateMethod = PlateLocateMethod.Sobel法;
                    plateInfos.Add(plateInfo);
                }
            }
            return(plateInfos);
        }