/// <summary> /// Command line example: detect the encoding of the given file. /// </summary> /// <param name="filename">a filename</param> public static void DetectDemo(string filename) { // Detect from File DetectionResult result = CharsetDetector.DetectFromFile(filename); // Get the best Detection DetectionDetail resultDetected = result.Detected; // detected result may be null. if (resultDetected != null) { // Get the alias of the found encoding string encodingName = resultDetected.EncodingName; // Get the System.Text.Encoding of the found encoding (can be null if not available) Encoding encoding = resultDetected.Encoding; // Get the confidence of the found encoding (between 0 and 1) float confidence = resultDetected.Confidence; if (encoding != null) { Console.WriteLine($"Detection completed: {filename}"); Console.WriteLine($"EncodingWebName: {encoding.WebName}{Environment.NewLine}Confidence: {confidence}"); } else { Console.WriteLine($"Detection completed: {filename}"); Console.WriteLine($"(Encoding is null){Environment.NewLine}EncodingName: {encodingName}{Environment.NewLine}Confidence: {confidence}"); } } else { Console.WriteLine($"Detection failed: {filename}"); } }
/// <summary> /// Gets the <see cref="Encoding"/> from <see cref="UtfUnknown.DetectionResult"/> value. /// </summary> /// <param name="result">The result of the <see cref="UtfUnknown.CharsetDetector.DetectFromStream(Stream)"/> call.</param> /// <returns>The detected encoding.</returns> public static Encoding GetPrimaryFromCharsetDetector(DetectionResult result) { var resultOrdered = result.Details.OrderByDescending(f => f.Confidence).ThenBy( e => e.Encoding is UTF7Encoding || e.Encoding is UTF8Encoding || e.Encoding is UnicodeEncoding || e.Encoding is UTF32Encoding).ToList(); var encoding = resultOrdered.FirstOrDefault()?.Encoding; if (encoding != null) { if (encoding is UTF8Encoding) { return(new UTF8Encoding(false)); } if (encoding is UnicodeEncoding unicodeEncoding) { return(new UnicodeEncoding(unicodeEncoding.IsBigEndian(), false)); } if (encoding is UTF32Encoding utf32Encoding) { return(new UnicodeEncoding(utf32Encoding.IsBigEndian(), false)); } } return(encoding); }
protected void ShowUserGuidance(DetectionResult result) { if (!autoSnappingEnabled) { return; } if (Java.Lang.JavaSystem.CurrentTimeMillis() - lastUserGuidanceHintTs < 400) { return; } var color = Color.Red; var guideText = ""; if (result == DetectionResult.Ok) { guideText = "Don't move.\nCapturing..."; color = Color.Green; } else if (result == DetectionResult.OkButTooSmall) { guideText = "Move closer"; } else if (result == DetectionResult.OkButBadAngles) { guideText = "Perspective"; } else if (result == DetectionResult.OkButBadAspectRatio) { guideText = "Wrong aspect ratio.\n Rotate your device"; if (ignoreBadAspectRatio) { guideText = "Don't move.\nCapturing..."; color = Color.Green; } } else if (result == DetectionResult.ErrorNothingDetected) { guideText = "No Document"; } else if (result == DetectionResult.ErrorTooNoisy) { guideText = "Background too noisy"; } else if (result == DetectionResult.ErrorTooDark) { guideText = "Poor light"; } // The HandleResult callback is coming from a worker thread. Use main UI thread to update UI: userGuidanceTextView.Post(() => { userGuidanceTextView.Text = guideText; userGuidanceTextView.SetTextColor(Color.White); userGuidanceTextView.SetBackgroundColor(color); }); lastUserGuidanceHintTs = Java.Lang.JavaSystem.CurrentTimeMillis(); }
public void DrawAtLocation(DetectionResult markerResult, Vector2 positionToDrawAt) { if (!isTaken()) { if (getType() == ChessPiece.Piece.KNIGHT) { if (getPlayer() == ChessPiece.Color.BLACK) { ModelDrawer.Draw(markerResult, mModel, positionToDrawAt.X, positionToDrawAt.Y, .2, -1.5707f, true); //rotated by -90 degress } else { ModelDrawer.Draw(markerResult, mModel, positionToDrawAt.X, positionToDrawAt.Y, .2, 1.5707f, true); //rotated by 90 degress } } else if (getType() == ChessPiece.Piece.BISHOP) { if (getPlayer() == ChessPiece.Color.BLACK) { ModelDrawer.Draw(markerResult, mModel, positionToDrawAt.X, positionToDrawAt.Y, .2, -3.1414f, true); //rotated by -90 degress } else { ModelDrawer.Draw(markerResult, mModel, positionToDrawAt.X, positionToDrawAt.Y, .2, 0.0f, true); //rotated by 90 degress } } else { ModelDrawer.Draw(markerResult, mModel, positionToDrawAt.X, positionToDrawAt.Y, 0.2, 0.0f, true); } } }
public async Task <ActionResult <DetectionResult> > PostDetectionResult(DetectionResult detectionResult) { _context.Results.Add(detectionResult); await _context.SaveChangesAsync(); return(CreatedAtAction("GetDetectionResult", new { id = detectionResult.DetectionResultId }, detectionResult)); }
public static void CopyToFolder(string path, string dir, Spec spec, DetectionResult Dr, int index) { try { var FileName = Path.GetFileName(path); File.Copy(path, "." + dir + FileName); File.Copy(path.Replace(".xls", ".jpg"), "." + dir + FileName.Replace(".xls", ".jpg")); WriteDeltaToJpeg("." + dir + FileName.Replace(".xls", ".jpg"), spec, index); } catch (Exception ex) { //////if already existed if (ex.Message.ToLower().Contains("already")) { try { string timestamp = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff"); var FileName = Path.GetFileNameWithoutExtension(path); File.Copy(path, "." + dir + FileName + timestamp + ".xls"); File.Copy(path.Replace(".xls", ".jpg"), "." + dir + FileName + timestamp + ".jpg"); WriteDeltaToJpeg("." + dir + FileName + timestamp + ".jpg", spec, index); Thread.Sleep(10); } catch (Exception e) { } } } }
/// <summary> /// Extended CTOR /// </summary> /// <param name="bodyId">Id of tracked body</param> /// <param name="faceFeature">Feature of the analytics</param> /// <param name="detectionResult">Most common detection result</param> /// <param name="perc">Percentage of occurence</param> private FaceFeatureAnalytics(ulong bodyId, FaceProperty faceFeature, DetectionResult detectionResult, double perc) { _bodyId = bodyId; _faceFeature = faceFeature; _detectionResult = detectionResult; _percentage = perc; }
public void Draw(DetectionResult markerResult, Vector3 position) { if (!isTaken()) { if (getType() == ChessPiece.Piece.KNIGHT) { if (getPlayer() == ChessPiece.Color.BLACK) { ModelDrawer.Draw(markerResult, mModel, (int)position.X, (int)position.Y, .2, -1.5707f); //rotated by -90 degress } else { ModelDrawer.Draw(markerResult, mModel, (int)position.X, (int)position.Y, .2, 1.5707f); //rotated by 90 degress } } else if (getType() == ChessPiece.Piece.BISHOP) { if (getPlayer() == ChessPiece.Color.BLACK) { ModelDrawer.Draw(markerResult, mModel, (int)position.X, (int)position.Y, .2, -3.1414f); //rotated by -90 degress } else { ModelDrawer.Draw(markerResult, mModel, (int)position.X, (int)position.Y, .2, 0.0f); //rotated by 90 degress } } else { ModelDrawer.Draw(markerResult, mModel, (int)position.X, (int)position.Y, 0.2); } } }
public void Draw(DetectionResult markerResult) { if (!isTaken()) { Draw(markerResult, new Vector3((int)mPosition.X, (int)mPosition.Y, 0.2f)); } }
public async Task <IActionResult> PutDetectionResult(Guid id, DetectionResult detectionResult) { if (id != detectionResult.DetectionResultId) { return(BadRequest()); } _context.Entry(detectionResult).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!DetectionResultExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public ActionResult Create() { var model = new DetectionResult(); ViewData.Add("Physicochemical", new SelectList(EnumHelper.GetItemValueList <EnumPhysicochemical>(), "Key", "Value")); return(View("Edit", model)); }
// Compute Intersection over Union(IOU) private float ComputeIOU(DetectionResult DRa, DetectionResult DRb) { float ay1 = DRa.bbox[0]; float ax1 = DRa.bbox[1]; float ay2 = DRa.bbox[2]; float ax2 = DRa.bbox[3]; float by1 = DRb.bbox[0]; float bx1 = DRb.bbox[1]; float by2 = DRb.bbox[2]; float bx2 = DRb.bbox[3]; Debug.Assert(ay1 < ay2); Debug.Assert(ax1 < ax2); Debug.Assert(by1 < by2); Debug.Assert(bx1 < bx2); // determine the coordinates of the intersection rectangle float x_left = Math.Max(ax1, bx1); float y_top = Math.Max(ay1, by1); float x_right = Math.Min(ax2, bx2); float y_bottom = Math.Min(ay2, by2); if (x_right < x_left || y_bottom < y_top) { return(0); } float intersection_area = (x_right - x_left) * (y_bottom - y_top); float bb1_area = (ax2 - ax1) * (ay2 - ay1); float bb2_area = (bx2 - bx1) * (by2 - by1); float iou = intersection_area / (bb1_area + bb2_area - intersection_area); Debug.Assert(iou >= 0 && iou <= 1); return(iou); }
// Return a list of rectangles with detected faces private List <Rectangle> FaceDetection(string imageFileName) { string classifierData = @"%inetroot%\private\research\private\CollaborativeLibs_01\LibFaceDetect\FaceDetect\Classifier\classifier.txt"; float detectionThreshold = 0.0F; FaceDetector detector = new FaceDetector( classifierData, true, detectionThreshold); // Run Detection DetectionResult detectionResult = detector.DetectObject(imageFileName); List <ScoredRect> scoredResultList = detectionResult.GetMergedRectList(0.0F); if (scoredResultList.Count < 0) { return(null); } List <Rectangle> faceRects = new List <Rectangle>(); foreach (ScoredRect scoredRect in scoredResultList) { Rectangle rect = new Rectangle(); rect.X = scoredRect.X; rect.Y = scoredRect.Y; rect.Width = scoredRect.Width; rect.Height = scoredRect.Height; faceRects.Add(rect); } return(faceRects); }
/// <summary> /// 图片检测 /// </summary> /// <param name=""></param> /// <param name="bytes"></param> /// <returns></returns> public DetectionResult Detection(byte[] bytes) { try { var client = new AntiPorn(API_KEY, SECRET_KEY); client.Timeout = 50000; // 修改超时时间 var jsonObj = client.Detect(bytes); var ret2 = jsonObj.ToObject <BaiduImageDetectionResult>(); var ret = new DetectionResult() { Platform = "百度" }; foreach (var item in ret2.result) { // 只考虑返回概率大于50%的情况,这个后面顶一个参数吧 if (item.probability > 0.5) { ret.Items.Add(new DetectionResultItem { TypeName = item.class_name, Suggestion = item.probability * 100 }); } } var max = ret.Items.OrderByDescending(o => o.Suggestion).First(); switch (max.TypeName) { case "正常": ret.Result = DetectionResultType.Normal; break; case "色情": ret.Result = DetectionResultType.P**n; break; case "性感": ret.Result = DetectionResultType.Sexy; break; default: ret.Result = DetectionResultType.Unknow; break; } ret.SourceResult = jsonObj.ToString(); return(ret); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return(new DetectionResult { Error = ex.Message, Platform = "百度" }); } }
public async Task MultivariateDetect() { //read endpoint and apiKey string endpoint = TestEnvironment.Endpoint; string apiKey = TestEnvironment.ApiKey; string datasource = TestEnvironment.DataSource; Console.WriteLine(endpoint); var endpointUri = new Uri(endpoint); var credential = new AzureKeyCredential(apiKey); //create client AnomalyDetectorClient client = new AnomalyDetectorClient(endpointUri, credential); // train TimeSpan offset = new TimeSpan(0); DateTimeOffset start_time = new DateTimeOffset(2021, 1, 1, 0, 0, 0, offset); DateTimeOffset end_time = new DateTimeOffset(2021, 1, 2, 12, 0, 0, offset); Guid? model_id_raw = null; try { model_id_raw = await TrainAsync(client, datasource, start_time, end_time).ConfigureAwait(false); Console.WriteLine(model_id_raw); Guid model_id = model_id_raw.GetValueOrDefault(); // detect start_time = end_time; end_time = new DateTimeOffset(2021, 1, 3, 0, 0, 0, offset); DetectionResult result = await DetectAsync(client, datasource, model_id, start_time, end_time).ConfigureAwait(false); if (result != null) { Console.WriteLine(String.Format("Result ID: {0}", result.ResultId)); Console.WriteLine(String.Format("Result summary: {0}", result.Summary)); Console.WriteLine(String.Format("Result length: {0}", result.Results.Count)); } //detect last await DetectLastAsync(client, model_id).ConfigureAwait(false); // export model await ExportAsync(client, model_id).ConfigureAwait(false); // delete await DeleteAsync(client, model_id).ConfigureAwait(false); } catch (Exception e) { String msg = String.Format("Multivariate error. {0}", e.Message); if (model_id_raw != null) { await DeleteAsync(client, model_id_raw.GetValueOrDefault()).ConfigureAwait(false); } Console.WriteLine(msg); throw; } }
public void MergeSkeleton(RATKinectSkeleton srcData, Matrix4x4 transform) { if (!srcData.valid) { return; } //TODO utilize jointStates if (mergeCount == 0) { //first skeleton, set data for (int i = 0; i < JOINT_COUNT; i++) { jointPositions3D[i] = transform.MultiplyPoint(srcData.jointPositions3D[i]); jointStates[i] = srcData.jointStates[i]; } for (int i = 0; i < FACE_POSITION_COUNT; i++) { facePositions3D[i] = transform.MultiplyPoint(srcData.facePositions3D[i]); } faceOrientationYPR = srcData.faceOrientationYPR; faceOrientation = srcData.faceOrientation; glasses = srcData.glasses; happy = srcData.happy; engaged = srcData.engaged; lookingAway = srcData.lookingAway; leftEyeClosed = srcData.leftEyeClosed; rightEyeClosed = srcData.rightEyeClosed; mouthOpen = srcData.mouthOpen; mouthMoved = srcData.mouthMoved; } else { for (int i = 0; i < JOINT_COUNT; i++) { jointPositions3D[i] += transform.MultiplyPoint(srcData.jointPositions3D[i]); if (jointStates[i] > srcData.jointStates[i]) { jointStates[i] = srcData.jointStates[i]; } } for (int i = 0; i < FACE_POSITION_COUNT; i++) { facePositions3D[i] += transform.MultiplyPoint(srcData.facePositions3D[i]); } faceOrientationYPR = srcData.faceOrientationYPR; faceOrientation = srcData.faceOrientation; glasses = srcData.glasses; happy = srcData.happy; engaged = srcData.engaged; lookingAway = srcData.lookingAway; leftEyeClosed = srcData.leftEyeClosed; rightEyeClosed = srcData.rightEyeClosed; mouthOpen = srcData.mouthOpen; mouthMoved = srcData.mouthMoved; } valid = true; mergeCount++; }
/// <summary> /// Convert the FaceProperty and DetectionResult to a display string /// </summary> /// <param name="prop">The FaceProperty enum type</param> /// <param name="result">The DetectionResult of the FaceProperty</param> /// <returns></returns> private string FacePropertyToString(FaceProperty prop, DetectionResult result) { string str = ""; str += Enum.GetName(typeof(FaceProperty), prop) + ": "; str += Enum.GetName(typeof(DetectionResult), result) + "\n"; return(str); }
public ActionResult Create(FormCollection collection) { var model = new DetectionResult(); this.TryUpdateModel <DetectionResult>(model); this.IDKLManagerService.InsertDetectionResult(model); return(this.RefreshParent()); }
private FileInfo DetectMovesFromFile(FileInfo fileInfo) { AppendResult(fileInfo.DirectoryName, fileInfo.Name, "=========================================" + Environment.NewLine + "Detect Moves Start: " + DateTime.Now.ToString()); LogProvider provider = new LogProvider(); provider.OpenLog(fileInfo.FullName); MoveDetector moveDetector = MoveDetector.GetInstance(); var patterns = moveDetector.DetectAsPatternInstances(provider); // Save the results to a file. DetectionResult result = new DetectionResult(provider.LogPath, patterns); result.SaveToFile(GetSaveFileName(fileInfo.DirectoryName, fileInfo.Name)); result.ExportToCSV(GetSaveFileName(fileInfo.DirectoryName, fileInfo.Name, "csv")); var xmlDoc = new XmlDocument(); xmlDoc.Load(fileInfo.FullName); var documentChanges = provider.LoggedEvents.OfType <DocumentChange>().ToList(); foreach (MovePatternInstance pattern in patterns) { int startIndex = documentChanges.IndexOf(pattern.PrimaryEvent as DocumentChange); Delete delete = documentChanges[startIndex + 0] as Delete; Insert insert = documentChanges[startIndex + 1] as Insert; // Same file, same place if (pattern.FromFile == pattern.ToFile && delete.Offset == insert.Offset) { // Just cancel them out. xmlDoc.DocumentElement.RemoveChild(Event.FindCorrespondingXmlElementFromXmlDocument(xmlDoc, delete)); xmlDoc.DocumentElement.RemoveChild(Event.FindCorrespondingXmlElementFromXmlDocument(xmlDoc, insert)); } else { // Transform Insert -> Move and then remove Delete. SetMoveElement(xmlDoc, pattern, delete, insert); xmlDoc.DocumentElement.RemoveChild(Event.FindCorrespondingXmlElementFromXmlDocument(xmlDoc, delete)); } } string newPath = Path.Combine(fileInfo.DirectoryName, _settings.Prefix + Path.GetFileNameWithoutExtension(fileInfo.Name) + _settings.Postfix + fileInfo.Extension); xmlDoc.Save(newPath); AppendResult(fileInfo.DirectoryName, fileInfo.Name, string.Format("{0} moves have been detected and written in the log" + Environment.NewLine, patterns.Count())); return(new FileInfo(newPath)); }
private IActionResult SetRawData(string detection) { var det = new DetectionResult(detection); int leafCount = 0, ciliCount = 0; foreach (var obj in det.Detection) { Debug.Print("File Name: " + obj.Key); foreach (string s in obj.Value) { Debug.Print("Property: " + s); if (s.ToLower().Contains("leaf")) { leafCount++; } else if (s.ToLower().Contains("chilli")) { ciliCount++; } } } if (leafCount <= 0 && ciliCount <= 0) { return(Json("Nothing detected!")); } ChiliModel data = new ChiliModel { CheckedBy = "Robot Tank", Datetime = DateTime.Now.ToString("dd/MM/yyyy"), Image = JsonConvert.SerializeObject(det.URLs), LastUpdate = DateTime.Now, NumberOfFruits = ciliCount, NumberOfLeaves = leafCount, LeafColor = leafCount > 0 ? "Green" : "-", PlantId = "R", // TODO: add plant ID TreeHeight = "40", // TODO LeafLength = leafCount > 0 ? "10" : "0", // TODO LeafWidth = leafCount > 0 ? "4.84" : "0", // TODO FruitLength = ciliCount > 0 ? "12" : "-", // TODO FruitWidth = ciliCount > 0 ? "1.9" : "-", // TODO FruitColor = ciliCount > 0 ? "Green" : "-" // TODO }; var client = new RestClient("https://api.cilibot.com/DataCollect/SetRawData"); var request = new RestRequest(Method.POST); request.AddHeader("Host", "api.cilibot.com"); request.AddHeader("Content-Type", "application/json"); request.AddParameter("data", JsonConvert.SerializeObject(data), ParameterType.RequestBody); IRestResponse response = client.Execute(request); return(Json(response.Content)); }
public void DetectLanguage_Source_CorrectLanguage(Language expectedLanguage, string fileName) { var source = new TextFile(File.ReadAllText(Path.Combine(TestUtility.TestsDataPath, fileName.NormalizeDirSeparator()))); source.Name = fileName; DetectionResult detectedLanguage = ParserLanguageDetector.Detect(source); Assert.AreEqual(expectedLanguage, detectedLanguage.Language); }
static private int GenerateData(string imageFileName, List <FeaturePts> featureList) { if (null == imageFileName) { return(0); } DetectionResult detectionResult = _detector.DetectObject(imageFileName); List <ScoredRect> scoredResultList = detectionResult.GetMergedRectList(0.0F); int imageCount = 0; if (null != featureList && scoredResultList.Count > 0) { foreach (FeaturePts features in featureList) { System.Drawing.PointF point = (System.Drawing.PointF)features.ptLeftEye; Point leftEye = new Point(point.X, point.Y); point = (System.Drawing.PointF)features.ptRightEye; Point rightEye = new Point(point.X, point.Y); foreach (ScoredRect scoredRect in scoredResultList) { Rect rect = new Rect(); rect.X = scoredRect.X; rect.Y = scoredRect.Y; rect.Width = scoredRect.Width; rect.Height = scoredRect.Height; if (rect.Contains(leftEye) && rect.Contains(rightEye)) { leftEye.X = (leftEye.X - rect.X) / rect.Width; leftEye.Y = (leftEye.Y - rect.Y) / rect.Width;; rightEye.X = (rightEye.X - rect.X) / rect.Width;; rightEye.Y = (rightEye.Y - rect.Y) / rect.Width;; FaceDisp.FaceData faceData = new FaceDisp.FaceData(features.ptLeftEye, features.ptRightEye, features.ptNose, features.ptLeftMouth, features.ptRightMouth, rect); //ProcessFace(imageFileName, rect, leftEye, rightEye, 0); ProcessFace(imageFileName, rect, faceData, 0); ++imageCount; break; } } } } return(imageCount); }
/// <summary> /// Track another detection /// </summary> /// <param name="detectionResult">Result of the detection</param> public void Track(DetectionResult detectionResult) { // Add new detection result if not present yet if (!_tracking.ContainsKey(detectionResult)) { _tracking.Add(detectionResult, 0); } // Increment the tracking value _tracking[detectionResult]++; }
public GameDetection(FileInfo eawExe, FileInfo focExe) { Requires.NotNull(eawExe, nameof(eawExe)); Requires.NotNull(focExe, nameof(focExe)); Result = DetectionResult.Installed; EawExe = eawExe; FocExe = focExe; FocType = GameTypeHelper.GetGameType(this); // TODO: Don't assume eaw type is the same as foc type EawType = FocType; }
private FileInfo RemoveTyposFromFile(FileInfo fileInfo) { AppendResult(fileInfo.DirectoryName, fileInfo.Name, "=========================================" + Environment.NewLine + "Remove Typos Start: " + DateTime.Now.ToString()); LogProvider provider = new LogProvider(); provider.OpenLog(fileInfo.FullName); TypoCorrectionDetector typoDetector = TypoCorrectionDetector.GetInstance(); var patterns = typoDetector.DetectAsPatternInstances(provider); // Save the results to a file. DetectionResult result = new DetectionResult(provider.LogPath, patterns); result.SaveToFile(GetSaveFileName(fileInfo.DirectoryName, fileInfo.Name)); result.ExportToCSV(GetSaveFileName(fileInfo.DirectoryName, fileInfo.Name, "csv")); var xmlDoc = new XmlDocument(); xmlDoc.Load(fileInfo.FullName); var documentChanges = provider.LoggedEvents.OfType <DocumentChange>().ToList(); // This should be done in reverse order, to process consecutive typo corrections correctly. foreach (PatternInstance pattern in patterns.Reverse()) { // Determine the type int startIndex = documentChanges.IndexOf(pattern.PrimaryEvent as DocumentChange); // Type 1: Insert -> Delete -> Insert if (documentChanges[startIndex + 1] is Delete) { ProcessType1(xmlDoc, documentChanges, startIndex); } // Type 2: Insert -> Replace else if (documentChanges[startIndex + 1] is Replace) { ProcessType2(xmlDoc, documentChanges, startIndex); } } string newPath = Path.Combine(fileInfo.DirectoryName, _settings.Prefix + Path.GetFileNameWithoutExtension(fileInfo.Name) + _settings.Postfix + fileInfo.Extension); xmlDoc.Save(newPath); AppendResult(fileInfo.DirectoryName, fileInfo.Name, string.Format("{0} typo corrections have been removed" + Environment.NewLine, patterns.Count())); return(new FileInfo(newPath)); }
void ShowDetectedRect() { labelStatus.Text = ""; labelDetectedRect.Text = ""; labelRectInfo.Text = ""; listBoxDetectedRect.Items.Clear(); if (_ImgCol != null && listBoxImg.SelectedIndex >= 0 && listBoxImg.SelectedIndex < _ImgCol.ImgList.Count && checkBoxDetect.Checked ) { LabeledImg labeledImg = _ImgCol.ImgList[listBoxImg.SelectedIndex]; if (labeledImg != null) { List <ScoredRect> ascoredRect = null; DetectionResult detRes = DetectFaces(labeledImg); if (detRes != null) { float eThreshold = trackBarThreshold.Value * _eStepSize; if (radioButtonMergedRect.Checked) { ascoredRect = detRes.GetMergedRectList(eThreshold); } else { ascoredRect = detRes.GetRawRectList(eThreshold); } } if (ascoredRect != null) { listBoxDetectedRect.SuspendLayout(); listBoxDetectedRect.Items.Clear(); labelDetectedRect.Text = ascoredRect.Count + " rectangle(s)"; foreach (ScoredRect rect in ascoredRect) { listBoxDetectedRect.Items.Add(rect); } listBoxDetectedRect.ResumeLayout(); } } } }
public void Draw() { // Draw Board mBoard.Draw(); DetectionResult boardMarker = mBoard.getDetectionResult(); foreach (KeyValuePair <string, ChessPiece> entry in chessPieces) { if (entry.Value == mSelectedPiece && !mMoveMade) { DetectionResult selectorMarker = mSelector.getDetectionResult(); entry.Value.Draw(selectorMarker, new Vector3(4, 4, 0)); } else if (entry.Value == mSelectedPiece && mSelectedPiece.getPosition() != chosenPosition) { if (velocity.X == -1 && velocity.Y == -1) { Vector2 startPosition = previousPosition; startPosition -= new Vector2(4, 4); startPosition *= ModelDrawer.SCALE; Vector2 endPosition = chosenPosition; endPosition -= new Vector2(4, 4); endPosition *= ModelDrawer.SCALE; velocity = endPosition - startPosition; velocity.Normalize(); velocity = velocity * 1.3f; moveAlongPosition = startPosition; } moveAlongPosition += velocity; entry.Value.DrawAtLocation(boardMarker, moveAlongPosition); if ((int)(Vector2.Distance(moveAlongPosition, (chosenPosition - new Vector2(4, 4)) * ModelDrawer.SCALE)) < ModelDrawer.SCALE / 10) { entry.Value.setPosition(chosenPosition); velocity = new Vector2(-1, -1); } } else { entry.Value.Draw(boardMarker); } } // Draw Selector if (!mMoveMade) { mSelector.Draw(); } }
/// <summary> /// Analyse the feature tracker /// </summary> /// <param name="tracker">Tracker for the feature</param> /// <param name="bodyId">Id of tracked body</param> public static FaceFeatureAnalytics Analyse(FaceFeatureTracker tracker, ulong bodyId) { if (tracker == null) { throw new ArgumentException("Invalid feature tracker", "tracker"); } if (bodyId == 0) { throw new ArgumentException("Invalid body Id", "bodyId"); } // Get most frequent result DetectionResult frequentResult = DetectionResult.Unknown; // Create details list List <FaceFeatureDetailsAnalytics> featureDetails = new List <FaceFeatureDetailsAnalytics>(); int totalOccurences = 0; int detectionOcc = -1; foreach (KeyValuePair <DetectionResult, int> pair in tracker.Results) { // Determin if this occured more if (pair.Value > detectionOcc) { frequentResult = pair.Key; detectionOcc = pair.Value; } // Add to details list featureDetails.Add(new FaceFeatureDetailsAnalytics(pair.Key, pair.Value)); // Increment total totalOccurences += pair.Value; } double perc = 0; featureDetails.ForEach(ffda => ffda.CalculatePercentage(totalOccurences)); // Calculate percentage if (tracker.Results.ContainsKey(frequentResult)) { perc = Math.Round((((double)tracker.Results[frequentResult] / (double)totalOccurences) * 100), 2); } return(new FaceFeatureAnalytics(bodyId, tracker.FaceProperty, frequentResult, perc) { FaceFeatureDetails = featureDetails }); }
public Task <Message> TransformAsync(DetectionResult result, IContext context) { var lines = result.Text.Split('\n'); return(Task.FromResult( new Message( string.Format( context.IsDryRun ? "Meigen by {0}:\n{1}": "g!meigen make {0} {1}", lines.First().Split(' ').FirstOrDefault(), string.Join('\n', lines.Skip(1)) ) ) )); }
private static Encoding AnalyzeAndGuessEncoding(DetectionResult result) { Encoding encoding = result.Detected.Encoding; var confidence = result.Detected.Confidence; var foundBetterMatch = false; // Let's treat ASCII as UTF-8 for better accuracy if (EncodingUtility.Equals(encoding, Encoding.ASCII)) { encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); } // If confidence is above 80%, we should just use it if (confidence > 0.80f && result.Details.Count == 1) { return(encoding); } // Try find a better match based on User's current Windows ANSI code page // Priority: UTF-8 > SystemDefaultANSIEncoding (Codepage: 0) > CurrentCultureANSIEncoding if (!(encoding is UTF8Encoding)) { foreach (var detail in result.Details) { if (detail.Confidence <= 0.5f) { continue; } if (detail.Encoding is UTF8Encoding) { foundBetterMatch = true; } else if (EncodingUtility.TryGetSystemDefaultANSIEncoding(out var systemDefaultEncoding) && EncodingUtility.Equals(systemDefaultEncoding, detail.Encoding)) { foundBetterMatch = true; } else if (EncodingUtility.TryGetCurrentCultureANSIEncoding(out var currentCultureEncoding) && EncodingUtility.Equals(currentCultureEncoding, detail.Encoding)) { foundBetterMatch = true; } if (foundBetterMatch) { encoding = detail.Encoding; confidence = detail.Confidence; break; } }
/// <summary> /// Track another detection /// </summary> /// <param name="detectionResult">Result of the detection</param> public void Track(DetectionResult detectionResult) { // Add new detection result if not present yet if (!_tracking.ContainsKey(detectionResult)) _tracking.Add(detectionResult, 0); // Increment the tracking value _tracking[detectionResult]++; }
/// <summary> /// Convert the FaceProperty and DetectionResult to a display string /// </summary> /// <param name="prop">The FaceProperty enum type</param> /// <param name="result">The DetectionResult of the FaceProperty</param> /// <returns></returns> private string FacePropertyToString(FaceProperty prop, DetectionResult result) { string str = ""; str += Enum.GetName(typeof(FaceProperty), prop) + ": "; str += Enum.GetName(typeof(DetectionResult), result) + "\n"; return str; }
/// <summary> /// Default CTOR /// </summary> public FaceFeatureDetailsAnalytics(DetectionResult detResult, double counter) { _detectionResult = detResult; _counter = counter; }
/// <summary> /// Calls Action depending on DetectionResult /// </summary> /// <param name="detectionResult"></param> /// <param name="resultYes">call when DetectionResult.Yes</param> /// <param name="resultNo">call when DetectionResult.No</param> private void CallAction(DetectionResult detectionResult, Action<object, EventArgs> resultYes, Action<object, EventArgs> resultNo) { switch (detectionResult) { case DetectionResult.Yes: resultYes(null, null); break; case DetectionResult.No: resultNo(null, null); break; } }