Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Parsing the JSON files with coordinates from our Machine Learning model
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection.Emit;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Recognize_TextSdk;
namespace ImageCut
{
public static class JsonParser
{
private static int count = 1;
public static List<SubPicture> GetData(string jsonPath, string imagePath)
{
Image img = Image.FromFile(imagePath);
string json = File.ReadAllText(jsonPath);
// In case of a Json that was tranfered from the XML file
Model model = JsonConvert.DeserializeObject<Model>(json);
List<SubPicture> subPictures = model.Annotation.Objects;
//In case of a Json file that was returned from the ML
// List<SubPicture> subPictures = JsonConvert.DeserializeObject<List<SubPicture>>(json);
foreach (SubPicture subPicture in subPictures)
{
if (subPicture.Label == "label")
{
Bitmap newImg = CropImage(img, subPicture.TopLeft.X, subPicture.TopLeft.Y, subPicture.BottomRight.X, subPicture.BottomRight.Y);
newImg.Save($@".\{count}.jpg", ImageFormat.Jpeg);
Task<string> task = TextExtractor.ExtractTextAsync($@".\{count++}.jpg");
var label = task.GetAwaiter().GetResult();
subPicture.Label = $"label_{label}";
}
}
return subPictures;
}
private static Bitmap CropImage(Image source, int x1, int y1, int x2, int y2)
{
Rectangle crop = new Rectangle(x1, y1, x2 - x1, y2 - y1);
var bmp = new Bitmap(crop.Width, crop.Height);
using (var gr = Graphics.FromImage(bmp))
{
gr.DrawImage(source, new Rectangle(0, 0, bmp.Width, bmp.Height), crop, GraphicsUnit.Pixel);
}
return bmp;
}
}
public class Model
{
public Annotation Annotation { get; set; }
}
public class Annotation
{
public List<SubPicture> Objects { get; set; }
public Annotation()
{
this.Objects = new List<SubPicture>();
}
}
public class SubPicture
{
public Point TopLeft { get; set; }
public Point BottomRight { get; set; }
public string Label { get; set; }
public SubPicture()
{
this.TopLeft = new Point();
this.BottomRight = new Point();
}
public override string ToString()
{
return $"{this.Label} ({this.TopLeft.X}, {this.TopLeft.Y})";
}
}
public class Point
{
public int X { get; set; }
public int Y { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.