Skip to content

Instantly share code, notes, and snippets.

@jdhenckel
Created November 2, 2022 21:36
Show Gist options
  • Save jdhenckel/41a6da81a3973682c132f896e6fb8669 to your computer and use it in GitHub Desktop.
Save jdhenckel/41a6da81a3973682c132f896e6fb8669 to your computer and use it in GitHub Desktop.
Small utility to convert EvilDicomObject into a heirarchy of simple types (dict, list, string, int, double) and eventually serialized to JSON
using EvilDICOM.Core;
using EvilDICOM.Core.Dictionaries;
using System.Text.Json;
using System.Linq;
namespace DotnetDicom
{
internal class Program
{
/// <summary>
/// A utility function to convert a Evil DICOM Object into a heirarchy
/// of ordinary Dictionary and List collections.
/// </summary>
/// <param name="dcm">A dicom object</param>
/// <returns>a dictionary</returns>
static Dictionary<string, object> ToDict(DICOMObject dcm)
{
var dict = new Dictionary<string, object>();
foreach (var elem in dcm.Elements)
{
var key = TagDictionary.GetDescription(elem.Tag);
if (key == "Unknown Tag")
key = elem.Tag.CompleteID;
if (key.StartsWith("Group header"))
continue;
// This is a weird edge case, but sometimes DICOM allows duplicated tags
// in the same collection (which is not valid for Dict or Json) so we
// append a numeral in order to make the key unique.
if (dict.ContainsKey(key))
{
var i = 1;
var prefix = key + "_";
do { key = prefix + i++; } while(dict.ContainsKey(key));
}
if (elem.DData is DICOMObject)
{
var list = new List<object>();
foreach (DICOMObject d in elem.DData_)
{
list.Add(ToDict(d));
}
dict[key] = list;
}
else if (elem.DData_.Count > 1)
{
if (key == "PixelData" || elem.DData_.Count > 1000)
{
var t = elem.DData.GetType().ToString();
if (t.StartsWith("System."))
t = t.Substring(7);
dict[key] = "Array of " + elem.DData_.Count + " " + t + "(s)";
}
else if (elem.DData is double)
{
// Fix negative zeros
dict[key] = elem.DData_.Cast<double>().Select(t => t==0 ? 0 : t);
}
else
dict[key] = elem.DData_;
}
else
{
if (elem.DData == null)
dict[key] = null;
else if (elem.VR == EvilDICOM.Core.Enums.VR.Date)
dict[key] = ((DateTime)elem.DData).ToString("yyyy-MM-dd");
else if (elem.VR == EvilDICOM.Core.Enums.VR.Time)
dict[key] = ((DateTime)elem.DData).ToString("HH:mm:ss");
else if (elem.VR == EvilDICOM.Core.Enums.VR.DateTime)
dict[key] = ((DateTime)elem.DData).ToString("yyyy-MM-dd HH:mm:ss");
else
dict[key] = elem.DData;
}
}
return dict;
}
static void Main(string[] args)
{
var filename = "../../../0d630a57.dcm";
if (args.Length > 0) filename = args[0];
var dcm = DICOMObject.Read(filename);
var d = ToDict(dcm);
var options = new JsonSerializerOptions { WriteIndented = true };
var s = JsonSerializer.Serialize(d, options);
Console.WriteLine(s);
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment