Raw2Dicom 1.0.0

dotnet add package Raw2Dicom --version 1.0.0
                    
NuGet\Install-Package Raw2Dicom -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Raw2Dicom" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Raw2Dicom" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Raw2Dicom" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Raw2Dicom --version 1.0.0
                    
#r "nuget: Raw2Dicom, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Raw2Dicom@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Raw2Dicom&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Raw2Dicom&version=1.0.0
                    
Install as a Cake Tool

Raw2Dicom.Core

License: MIT .NET DICOM Medical Imaging

🇺🇸 English | 🇷🇺 Русский

Overview

Raw2Dicom.Core is a powerful .NET library for converting RAW medical imaging data to DICOM format. It provides comprehensive tools for working with raw pixel data from various medical imaging devices, including CR (Computed Radiography) and DR (Digital Radiography) systems.

Key Features

Format Detection: Automatic analysis of RAW files to determine image parameters
JSON Configuration: Predefined format configurations for known imaging systems
DICOM Compliance: Generates fully compliant DICOM files with proper metadata
Multiple Bit Depths: Support for 8-bit, 12-bit, 14-bit, and 16-bit images
Flexible Input: Handle files directly or work with byte arrays in memory
Windowing Support: Configurable brightness and contrast settings
Unicode Support: Full support for international patient names and descriptions
Comprehensive Testing: Extensive unit test coverage for reliability

Quick Start

Installation

Add the FellowOakDicom dependency to your project:

<PackageReference Include="fo-dicom.Desktop" Version="5.0.4" />

Basic Usage

using Raw2Dicom.Core;
using FellowOakDicom;

// Method 1: Using JSON configuration (Recommended)
var patient = new PatientContext(
    PatientName: "DOE^JOHN^",
    PatientId: "P12345",
    StudyDescription: "CHEST PA"
);

var provider = RawProvider.FromFileWithConfig(
    rawFilePath: "image.raw",
    configFilePath: "raw_formats.json",
    patient: patient
);

DicomFile dicomFile = provider.GetDicomFile();
dicomFile.Save("output.dcm");

// Method 2: Manual specification
var spec = new RawSpec(
    Width: 2048,
    Height: 2048,
    BitsAllocated: 16,
    BitsStored: 16,
    HighBit: 15,
    Signed: false,
    LittleEndian: true
);

byte[] rawData = File.ReadAllBytes("image.raw");
var manualProvider = new RawProvider(rawData, spec, patient);
DicomFile manualDicom = manualProvider.GetDicomFile();

Core Components

1. RawSpec - Image Format Specification

public record RawSpec(
    int Width,             // Image width in pixels
    int Height,            // Image height in pixels
    int BitsAllocated,     // Bits allocated per pixel (8 or 16)
    int BitsStored,        // Bits actually used (8-16)
    int HighBit,           // Index of highest bit (0-based)
    bool Signed,           // Signed pixel values (rarely used)
    bool LittleEndian      // Byte order (true = Little Endian)
);

2. PatientContext - DICOM Metadata

public record PatientContext(
    string PatientName,        // Patient name (DICOM format: "LAST^FIRST^MIDDLE")
    string PatientId,          // Unique patient identifier
    string StudyDescription    // Description of the study/examination
);

3. RawProvider - Main Processing Class

The RawProvider class encapsulates raw pixel data and provides methods to generate DICOM files:

// Create from file with JSON configuration
var provider = RawProvider.FromFileWithConfig(
    "path/to/image.raw", 
    "raw_formats.json", 
    patientContext
);

// Adjust display parameters
provider.WindowCenter = 2000; // Brightness
provider.WindowWidth = 4000;  // Contrast

// Generate DICOM
DicomFile dicom = provider.GetDicomFile();

JSON Configuration System

Instead of guessing image parameters, use predefined configurations in raw_formats.json:

[
  {
    "name": "Kodak CR 2048x2048 16-bit",
    "description": "Standard Kodak Computed Radiography format",
    "width": 2048,
    "height": 2048,
    "bitsAllocated": 16,
    "bitsStored": 16,
    "highBit": 15,
    "signed": false,
    "littleEndian": true,
    "recommendedWindowCenter": 2000,
    "recommendedWindowWidth": 4000,
    "tags": ["CR", "Kodak", "High-Resolution"]
  }
]

Configuration Management

// Load configurations
var configs = RawFormatManager.LoadFromJson("raw_formats.json");

// Find matching formats by file size
var matches = RawFormatManager.FindMatchingConfigs(configs, fileSize);

// Filter by tags
var crFormats = RawFormatManager.FilterByTags(configs, "CR");

// Find specific format
var kodakFormat = RawFormatManager.FindByName(configs, "Kodak CR 2048x2048 16-bit");

Advanced Features

RAW File Analysis

The library includes a powerful file analyzer that can determine image parameters by examining pixel data statistics:

// Analyze a RAW file
var analysis = RawFileAnalyzer.AnalyzeFile("unknown_image.raw");

// Get detailed report
string report = RawFileAnalyzer.GenerateReport(analysis);
Console.WriteLine(report);

// Use recommended format
if (analysis.RecommendedFormat != null)
{
    var provider = new RawProvider(rawData, analysis.RecommendedFormat, patient);
}

Format Guessing (Legacy)

For backward compatibility, automatic format guessing is available:

// Guess format from data
byte[] rawData = File.ReadAllBytes("image.raw");
var guessedSpec = RawSpecGuesser.GuessSpec(rawData);

// Or guess from file
var fileSpec = RawSpecGuesser.GuessSpecFromFile("image.raw");

Example Applications

1. Command Line Interface (CLI)

See Raw2Dicom.Cli for a complete command-line conversion tool that:

  • Loads JSON configurations
  • Finds matching formats by file size
  • Converts RAW files to DICOM with proper metadata
  • Handles multiple format suggestions

2. File Analyzer

The Raw2Dicom.Analyzer project provides:

  • Deep content analysis of RAW files
  • Pixel statistics and histograms
  • Format comparison tools
  • Confidence scoring for format detection

Supported Image Formats

Format Type Bit Depth Common Sizes Description
CR (Computed Radiography) 8, 14, 16-bit 1024×1024, 2048×2048 Traditional CR cassette systems
DR (Digital Radiography) 14, 16-bit 1024×1024, 2048×2048, 3072×3072 Flat panel detectors
Mammography 16-bit 2560×3328, 4096×5120 Specialized breast imaging
Portable/Mobile 16-bit 512×512, 1024×1024 Mobile X-ray units

Testing

The library includes comprehensive unit tests covering:

  • DICOM file generation and validation
  • Different bit depths and pixel formats
  • Unicode support for international names
  • Window/Level parameter handling
  • Format configuration validation
  • File I/O operations

Run tests using:

dotnet test Raw2Dicom.Tests

Dependencies

  • FellowOakDicom: DICOM file format handling
  • System.Text.Json: JSON configuration parsing
  • .NET 5.0+: Runtime platform

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE.txt file for details.


Русская версия

Обзор

Raw2Dicom.Core — это мощная библиотека .NET для конвертации RAW-данных медицинских изображений в формат DICOM. Она предоставляет комплексные инструменты для работы с сырыми пиксельными данными от различных устройств медицинской визуализации, включая системы CR (компьютерная рентгенография) и DR (цифровая рентгенография).

Основные возможности

Определение формата: Автоматический анализ RAW-файлов для определения параметров изображения
JSON-конфигурация: Предустановленные конфигурации форматов для известных систем визуализации
DICOM-совместимость: Генерация полностью совместимых DICOM-файлов с корректными метаданными
Множественная битность: Поддержка 8-, 12-, 14- и 16-битных изображений
Гибкий ввод: Работа с файлами напрямую или с массивами байтов в памяти
Поддержка окон: Настраиваемые параметры яркости и контрастности
Unicode-поддержка: Полная поддержка международных имен пациентов и описаний
Комплексное тестирование: Обширное покрытие модульными тестами для надежности

Быстрый старт

Установка

Добавьте зависимость FellowOakDicom в ваш проект:

<PackageReference Include="fo-dicom.Desktop" Version="5.0.4" />

Базовое использование

using Raw2Dicom.Core;
using FellowOakDicom;

// Способ 1: Использование JSON-конфигурации (рекомендуется)
var patient = new PatientContext(
    PatientName: "ИВАНОВ^ИВАН^ИВАНОВИЧ",
    PatientId: "П12345",
    StudyDescription: "РЕНТГЕН ГРУДНОЙ КЛЕТКИ"
);

var provider = RawProvider.FromFileWithConfig(
    rawFilePath: "image.raw",
    configFilePath: "raw_formats.json",
    patient: patient
);

DicomFile dicomFile = provider.GetDicomFile();
dicomFile.Save("output.dcm");

// Способ 2: Ручная спецификация
var spec = new RawSpec(
    Width: 2048,
    Height: 2048,
    BitsAllocated: 16,
    BitsStored: 16,
    HighBit: 15,
    Signed: false,
    LittleEndian: true
);

byte[] rawData = File.ReadAllBytes("image.raw");
var manualProvider = new RawProvider(rawData, spec, patient);
DicomFile manualDicom = manualProvider.GetDicomFile();

Основные компоненты

1. RawSpec - Спецификация формата изображения

public record RawSpec(
    int Width,             // Ширина изображения в пикселях
    int Height,            // Высота изображения в пикселях
    int BitsAllocated,     // Биты, выделенные на пиксель (8 или 16)
    int BitsStored,        // Биты, фактически используемые (8-16)
    int HighBit,           // Индекс старшего бита (отсчет от 0)
    bool Signed,           // Знаковые значения пикселей (редко используется)
    bool LittleEndian      // Порядок байтов (true = Little Endian)
);

2. PatientContext - DICOM-метаданные

public record PatientContext(
    string PatientName,        // Имя пациента (формат DICOM: "ФАМИЛИЯ^ИМЯ^ОТЧЕСТВО")
    string PatientId,          // Уникальный идентификатор пациента
    string StudyDescription    // Описание исследования/обследования
);

3. RawProvider - Основной класс обработки

Класс RawProvider инкапсулирует сырые пиксельные данные и предоставляет методы для генерации DICOM-файлов:

// Создание из файла с JSON-конфигурацией
var provider = RawProvider.FromFileWithConfig(
    "путь/к/image.raw", 
    "raw_formats.json", 
    patientContext
);

// Настройка параметров отображения
provider.WindowCenter = 2000; // Яркость
provider.WindowWidth = 4000;  // Контрастность

// Генерация DICOM
DicomFile dicom = provider.GetDicomFile();

Система JSON-конфигурации

Вместо угадывания параметров изображения используйте предустановленные конфигурации в raw_formats.json:

[
  {
    "name": "Kodak CR 2048x2048 16-bit",
    "description": "Стандартный формат Kodak компьютерной рентгенографии",
    "width": 2048,
    "height": 2048,
    "bitsAllocated": 16,
    "bitsStored": 16,
    "highBit": 15,
    "signed": false,
    "littleEndian": true,
    "recommendedWindowCenter": 2000,
    "recommendedWindowWidth": 4000,
    "tags": ["CR", "Kodak", "Высокое-разрешение"]
  }
]

Управление конфигурациями

// Загрузка конфигураций
var configs = RawFormatManager.LoadFromJson("raw_formats.json");

// Поиск подходящих форматов по размеру файла
var matches = RawFormatManager.FindMatchingConfigs(configs, fileSize);

// Фильтрация по тегам
var crFormats = RawFormatManager.FilterByTags(configs, "CR");

// Поиск конкретного формата
var kodakFormat = RawFormatManager.FindByName(configs, "Kodak CR 2048x2048 16-bit");

Расширенные возможности

Анализ RAW-файлов

Библиотека включает мощный анализатор файлов, который может определить параметры изображения путем исследования статистики пиксельных данных:

// Анализ RAW-файла
var analysis = RawFileAnalyzer.AnalyzeFile("неизвестное_изображение.raw");

// Получение подробного отчета
string report = RawFileAnalyzer.GenerateReport(analysis);
Console.WriteLine(report);

// Использование рекомендуемого формата
if (analysis.RecommendedFormat != null)
{
    var provider = new RawProvider(rawData, analysis.RecommendedFormat, patient);
}

Угадывание формата (устаревшее)

Для обратной совместимости доступно автоматическое угадывание формата:

// Угадывание формата из данных
byte[] rawData = File.ReadAllBytes("image.raw");
var guessedSpec = RawSpecGuesser.GuessSpec(rawData);

// Или угадывание из файла
var fileSpec = RawSpecGuesser.GuessSpecFromFile("image.raw");

Примеры приложений

1. Интерфейс командной строки (CLI)

См. Raw2Dicom.Cli для полного инструмента конвертации из командной строки, который:

  • Загружает JSON-конфигурации
  • Находит подходящие форматы по размеру файла
  • Конвертирует RAW-файлы в DICOM с правильными метаданными
  • Обрабатывает множественные предложения форматов

2. Анализатор файлов

Проект Raw2Dicom.Analyzer предоставляет:

  • Глубокий анализ содержимого RAW-файлов
  • Статистику пикселей и гистограммы
  • Инструменты сравнения форматов
  • Оценку достоверности для определения формата

Поддерживаемые форматы изображений

Тип формата Битность Обычные размеры Описание
CR (Компьютерная рентгенография) 8, 14, 16-бит 1024×1024, 2048×2048 Традиционные системы CR-кассет
DR (Цифровая рентгенография) 14, 16-бит 1024×1024, 2048×2048, 3072×3072 Плоскопанельные детекторы
Маммография 16-бит 2560×3328, 4096×5120 Специализированная визуализация груди
Портативные/Мобильные 16-бит 512×512, 1024×1024 Мобильные рентгеновские аппараты

Тестирование

Библиотека включает комплексные модульные тесты, покрывающие:

  • Генерацию и валидацию DICOM-файлов
  • Различные битности и форматы пикселей
  • Поддержку Unicode для международных имен
  • Обработку параметров окна/уровня
  • Валидацию конфигурации формата
  • Файловые операции ввода/вывода

Запуск тестов:

dotnet test Raw2Dicom.Tests

Зависимости

  • FellowOakDicom: Обработка формата DICOM-файлов
  • System.Text.Json: Парсинг JSON-конфигурации
  • .NET 5.0+: Платформа выполнения

Участие в разработке

  1. Сделайте форк репозитория
  2. Создайте ветку для новой функции
  3. Добавьте тесты для новой функциональности
  4. Убедитесь, что все тесты проходят
  5. Отправьте pull request

Лицензия

Этот проект лицензирован под лицензией MIT - см. файл LICENSE.txt для подробностей.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 145 9/12/2025