139 lines
6.2 KiB
Swift
139 lines
6.2 KiB
Swift
import CoreGraphics
|
|
import Foundation
|
|
import simd
|
|
|
|
struct DICOMVolume {
|
|
enum Plane: String, CaseIterable, Identifiable {
|
|
case slices = "Срезы серии"
|
|
case coronal = "Поперёк рядов"
|
|
case sagittal = "Поперёк столбцов"
|
|
|
|
var id: Self { self }
|
|
}
|
|
|
|
let size: SIMD3<Int>
|
|
let spacing: SIMD3<Double>?
|
|
let pixels: [Float]
|
|
let rgb: Data?
|
|
let pixelSpacing: SIMD2<Double>?
|
|
let window: SIMD2<Float>?
|
|
let inverted: Bool
|
|
let minimum: Float
|
|
let maximum: Float
|
|
|
|
init(urls: [URL]) throws {
|
|
guard !urls.isEmpty, urls.count <= 4096 else { throw DICOMError.geometry }
|
|
let first = try DICOMImage(url: urls[0])
|
|
let planeSize = first.width * first.height
|
|
guard planeSize <= 64_000_000 / urls.count else { throw DICOMError.unsupported }
|
|
size = SIMD3(first.width, first.height, urls.count == 1 ? first.frames : urls.count)
|
|
window = first.window
|
|
inverted = first.monochrome1
|
|
rgb = first.rgb
|
|
pixelSpacing = first.geometry?.spacing ?? first.frameGeometry?.first?.spacing
|
|
if urls.count == 1 {
|
|
if first.rgb == nil, first.frames > 1, let geometry = first.frameGeometry,
|
|
let sorted = try? Self.sortSlices(geometry) {
|
|
spacing = sorted.spacing
|
|
pixels = sorted.order.flatMap { frame in
|
|
first.pixels[(frame * planeSize)..<((frame + 1) * planeSize)]
|
|
}
|
|
} else {
|
|
spacing = nil
|
|
pixels = first.pixels
|
|
}
|
|
} else {
|
|
guard first.rgb == nil, let series = first.series, !series.isEmpty else { throw DICOMError.geometry }
|
|
var slices: [[Float]] = []
|
|
var geometry: [DICOMImage.Geometry] = []
|
|
for (index, url) in urls.enumerated() {
|
|
let image = index == 0 ? first : try DICOMImage(url: url)
|
|
guard image.rgb == nil, image.frames == 1, image.series == series, image.width == first.width,
|
|
image.height == first.height, image.monochrome1 == first.monochrome1,
|
|
let frame = image.geometry ?? image.frameGeometry?.first else { throw DICOMError.geometry }
|
|
geometry.append(frame)
|
|
slices.append(image.pixels)
|
|
}
|
|
let sorted = try Self.sortSlices(geometry)
|
|
spacing = sorted.spacing
|
|
pixels = sorted.order.flatMap { slices[$0] }
|
|
}
|
|
minimum = pixels.min() ?? 0
|
|
maximum = pixels.max() ?? 1
|
|
}
|
|
|
|
private static func sortSlices(_ geometry: [DICOMImage.Geometry]) throws
|
|
-> (spacing: SIMD3<Double>, order: [Int]) {
|
|
guard geometry.count > 1, let basis = geometry.first,
|
|
abs(simd_length(basis.row) - 1) < 0.001,
|
|
abs(simd_length(basis.column) - 1) < 0.001,
|
|
abs(simd_dot(basis.row, basis.column)) < 0.001 else { throw DICOMError.geometry }
|
|
let normal = simd_normalize(simd_cross(basis.row, basis.column))
|
|
let slices = try geometry.enumerated().map { index, frame in
|
|
let offset = frame.origin - basis.origin
|
|
let depth = simd_dot(offset, normal)
|
|
guard depth.isFinite, simd_length(offset - depth * normal) < 0.1,
|
|
simd_distance(frame.row, basis.row) < 0.001,
|
|
simd_distance(frame.column, basis.column) < 0.001,
|
|
simd_distance(frame.spacing, basis.spacing) < 0.001 else { throw DICOMError.geometry }
|
|
return (index: index, depth: depth)
|
|
}.sorted { $0.depth < $1.depth }
|
|
let step = (slices[slices.count - 1].depth - slices[0].depth) / Double(slices.count - 1)
|
|
guard (0.001...1000).contains(step), zip(slices, slices.dropFirst()).allSatisfy({
|
|
abs($1.depth - $0.depth - step) <= max(0.01, step * 0.02)
|
|
}) else { throw DICOMError.geometry }
|
|
return (SIMD3(basis.spacing.x, basis.spacing.y, step), slices.map(\.index))
|
|
}
|
|
|
|
func count(_ plane: Plane) -> Int {
|
|
switch plane {
|
|
case .slices: return size.z
|
|
case .coronal: return size.y
|
|
case .sagittal: return size.x
|
|
}
|
|
}
|
|
|
|
func image(_ plane: Plane, index: Int, center: Float, span: Float) -> (CGImage, Double)? {
|
|
let values: [Float]
|
|
let width: Int
|
|
let height: Int
|
|
let pitch = spacing ?? SIMD3(pixelSpacing?.x ?? 1, pixelSpacing?.y ?? 1, 1)
|
|
if let rgb, plane == .slices {
|
|
let stride = size.x * size.y * 3
|
|
let frame = rgb[(index * stride)..<((index + 1) * stride)]
|
|
guard let provider = CGDataProvider(data: frame as CFData),
|
|
let image = CGImage(width: size.x, height: size.y, bitsPerComponent: 8, bitsPerPixel: 24,
|
|
bytesPerRow: size.x * 3, space: CGColorSpaceCreateDeviceRGB(),
|
|
bitmapInfo: [], provider: provider, decode: nil, shouldInterpolate: true,
|
|
intent: .defaultIntent) else { return nil }
|
|
return (image, Double(size.x) * pitch.x / (Double(size.y) * pitch.y))
|
|
}
|
|
let aspect: Double
|
|
switch plane {
|
|
case .slices:
|
|
width = size.x
|
|
height = size.y
|
|
let start = index * width * height
|
|
values = Array(pixels[start..<(start + width * height)])
|
|
aspect = Double(width) * pitch.x / (Double(height) * pitch.y)
|
|
case .coronal:
|
|
width = size.x
|
|
height = size.z
|
|
values = (0..<height).reversed().flatMap { z in
|
|
let start = (z * size.y + index) * width
|
|
return pixels[start..<(start + width)]
|
|
}
|
|
aspect = Double(width) * pitch.x / (Double(height) * pitch.z)
|
|
case .sagittal:
|
|
width = size.y
|
|
height = size.z
|
|
values = (0..<height).reversed().flatMap { z in
|
|
(0..<width).map { y in pixels[(z * size.y + y) * size.x + index] }
|
|
}
|
|
aspect = Double(width) * pitch.y / (Double(height) * pitch.z)
|
|
}
|
|
return DICOMImage.grayscale(values, width: width, height: height, center: center,
|
|
span: span, invert: inverted).map { ($0, aspect) }
|
|
}
|
|
}
|