Skip to content

Commit

Permalink
adding pixel examples
Browse files Browse the repository at this point in the history
  • Loading branch information
vsoch committed Dec 12, 2017
1 parent 78d0b50 commit 3549623
Show file tree
Hide file tree
Showing 8 changed files with 332 additions and 186 deletions.
1 change: 1 addition & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
include README.md LICENSE
recursive-include deid *
recursive-exclude * __pycache__
recursive-exclude * app
recursive-exclude * *.pyc
recursive-exclude * *.pyo
recursive-exclude * *.orig
3 changes: 1 addition & 2 deletions deid/dicom/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from .fields import extract_sequence

from .pixels import (
clean_pixels,
has_burned_pixels,
has_burned_pixels_single
DicomCleaner
)
2 changes: 2 additions & 0 deletions deid/dicom/pixels/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from .detect import has_burned_pixels
from .clean import DicomCleaner
149 changes: 149 additions & 0 deletions deid/dicom/pixels/clean.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
'''
clean.py: functions for pixel scrubbing
Copyright (c) 2017 Vanessa Sochat
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.
'''

from deid.logger import bot
from pydicom import read_file
import tempfile
import os
import re

bot.level = 3

class DicomCleaner():
'''take an input dicom file, check for burned pixels, and then clean,
with option to save / output in multiple formats. This object should
map to one dicom file, and the usage flow is the following:
cleaner = DicomCleaner()
summary = cleaner.detect(dicom_file)
cleaner.clean()
'''

def __init__(self, output_folder=None,
add_padding=False,
margin=3,
deid=None):

if output_folder is None:
output_folder = tempfile.mkdtemp()

self.output_folder = output_folder
self.deid = deid
self.results = None

def detect(self, dicom_file):
'''detect will initiate the cleaner for a new dicom file.
'''
from .detect import has_burned_pixels
self.results = has_burned_pixels(dicom_file)
self.dicom_file = dicom_file
return self.results


def clean(self):
'''
take a dicom image and a list of pixel coordinates, and return
a cleaned file (if output file is specified) or simply plot
the cleaned result (if no file is specified)
Parameters
==========
add_padding: add N=margin pixels of padding
margin: pixels of padding to add, if add_padding True
'''

if not self.results:
bot.warning('Use %s.detect() to find coordinates first.' %self)

elif self.results['flagged'] is False:
bot.info('Image was not flagged, nothing to clean.' %self)

else:
bot.info('Cleaning %s.' %self.dicom_file)

# Load in dicom file, and image data
dicom = read_file(self.dicom_file,force=True)

# We will set original image to image, cleaned to clean
self.image = dicom._get_pixel_array()
self.clean = self.image.copy()

# Compile coordinates from result
coordinates = []
for item in self.results['results']:
if len(item['coordinates']) > 0:
coordinates.append(item['coordinates']) # [[1,2,3,4],...[1,2,3,4]]

print("Blanking %s coordinate boxes" %(len(coordinates)))
for coordinate in coordinates:
minr, minc, maxr, maxc = coordinate
self.clean[minr:maxr, minc:maxc] = 0 # should fill with black


def get_figure(self, show=False):
'''get a figure for a cleaned image, if exists.'''
from matplotlib import pyplot as plt
plt = None

if hasattr(self,"clean"):
fig, ax = plt.subplots(figsize=(10, 6))
ax.imshow(self.clean)
if show is True:
plt.show()
return plt


def _get_clean_name(self, extension='dcm'):
basename = re.sub('[.]dicom|[.]dcm', '', os.path.basename(self.dicom_file))
return "%s/cleaned-%s.%s" %(output_folder, basename, extension)

def save_png(self, output_folder=None):
'''save a cleaned dicom as png to disk'''
from matplotlib import pyplot as plt

if output_folder is None:
output_folder = self.output_folder

if hasattr(self,"clean"):
png_file = self._get_clean_name('png')
fig, ax = plt.subplots(figsize=(10, 6))
ax.imshow(self.clean)
plt.savefig(png_file)


def save_dicom(self, output_folder=None):
'''save a cleaned dicom to disk'''
if output_folder is None:
output_folder = self.output_folder

# Having clean also means has dicom image
if hasattr(self,"clean"):
dicom_name = self._get_clean_name()
dicom = read_file(self.dicom_file,force=True)
dicom.PixelData = self.clean.tostring()
dicom.save_as(dicom_name)
return dicom_name
else:
bot.warning('use detect() --> clean() before saving clean is possible.')
Loading

0 comments on commit 3549623

Please sign in to comment.