Skip to content

Instantly share code, notes, and snippets.

@valgur
Last active February 24, 2024 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valgur/c246f57d0fa0c3bd69707b087419a3b4 to your computer and use it in GitHub Desktop.
Save valgur/c246f57d0fa0c3bd69707b087419a3b4 to your computer and use it in GitHub Desktop.
Decode an LZW-compressed ViewStation DICOM image section
"""
The code below is part of pdfminer (http://pypi.python.org/pypi/pdfminer/)
Copyright (c) 2004-2010 Yusuke Shinyama <yusuke at cs dot nyu dot edu>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import sys
from io import BytesIO
class LZWDecoder(object):
debug = 0
def __init__(self, fp):
self.fp = fp
self.buff = 0
self.bpos = 8
self.nbits = 9
self.table = None
self.prevbuf = None
def readbits(self, bits):
v = 0
while True:
# the number of remaining bits we can get from the current buffer.
r = 8 - self.bpos
if bits <= r:
# |-----8-bits-----|
# |-bpos-|-bits-| |
# | |----r----|
v = (v << bits) | ((self.buff >> (r - bits)) & ((1 << bits) - 1))
self.bpos += bits
break
else:
# |-----8-bits-----|
# |-bpos-|---bits----...
# | |----r----|
v = (v << r) | (self.buff & ((1 << r) - 1))
bits -= r
x = self.fp.read(1)
if not x:
raise EOFError
self.buff = ord(x)
self.bpos = 0
return v
def feed(self, code):
x = bytearray()
if code == 256:
self.table = [bytearray([c]) for c in range(256)] # 0-255
self.table.append(None) # 256
self.table.append(None) # 257
self.prevbuf = bytearray()
self.nbits = 9
elif code == 257:
pass
elif not self.prevbuf:
x = self.prevbuf = self.table[code]
else:
if code < len(self.table):
x = self.table[code]
self.table.append(self.prevbuf + x[:1])
else:
self.table.append(self.prevbuf + self.prevbuf[:1])
x = self.table[code]
l = len(self.table)
if l == 511:
self.nbits = 10
elif l == 1023:
self.nbits = 11
elif l == 2047:
self.nbits = 12
self.prevbuf = x
return x
def run(self):
while True:
try:
code = self.readbits(self.nbits)
except EOFError:
break
x = self.feed(code)
yield x
if self.debug:
print('nbits=%d, code=%d, output=%r, table=%r' % (self.nbits, code, x, self.table[258:]), file=sys.stderr)
def lzw_decode(data):
fp = BytesIO(data)
return b''.join(LZWDecoder(fp).run())
# ----------------
import struct
import numpy as np
import matplotlib.pyplot as plt
def crc16(data):
msb = 0
lsb = 0
for c in data:
x = c ^ msb
x ^= (x >> 4)
msb = (lsb ^ (x >> 3) ^ (x << 4)) & 0xFF
lsb = (x ^ (x << 5)) & 0xFF
return (msb << 8) + lsb
path = "/home/martin/Downloads/001B2978.org"
file_data = open(path, "rb").read()
header = file_data[:50]
body = file_data[50:]
info = {}
(
info["patientID"],
info["imageNum"],
info["numBytes"],
info["dataBits"],
info["height"],
info["width"],
info["widthStored"],
info["storageType"],
info["version"],
_,
info["pixrep"],
_,
info["headerCRC"],
) = struct.unpack(">IIHHIIIH3scH14sI", header)
assert info["headerCRC"] == crc16(header[:-4])
(
info["bodyLen"],
info["numBands"],
) = struct.unpack(">II", body[:8])
info["bodyCRC"] = struct.unpack(">I", body[-4:])[0]
assert info["bodyLen"] == len(body) - 8
assert info["bodyCRC"] == crc16(body[:-4])
bands = []
pos = 8
for band_idx in range(info["numBands"]):
orig_len, compr_len = struct.unpack(">II", body[pos:][:8])
data = body[pos+8:][:compr_len]
pos += 8 + compr_len
bands.append((orig_len, compr_len, data))
dtype = np.dtype(np.uint16 if info["numBytes"] == 2 else np.uint8)
dtype = dtype.newbyteorder(">")
canvas = np.zeros((512, 512), dtype=dtype)
w = info["width"]
h = info["height"]
for i, (orig_len, compr_len, raw_data) in enumerate(bands):
if orig_len != 0:
raw_data = lzw_decode(raw_data)
arr = np.frombuffer(raw_data, dtype=dtype)
img = arr.reshape(-1, info["width"])
canvas[i * (info["height"] // len(bands)):][:img.shape[0]] = img
fig, ax = plt.subplots()
ax.set_aspect(1)
ax.imshow(canvas, vmin=0, vmax=0xFFFF, cmap="gray")
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment