<jupyter_start><jupyter_text>Test find_contour logic on example grid<jupyter_code>test = [[0,0,0,0,0],[0,0,1,0,0],[0,1,0,1,0],[0,0,1,0,0], [0,0,0,0,0]]

test_loop_coords = []
test_used_coords = {}
for y, rows in enumerate(test):
        for x, v in enumerate(rows):
            #print "START (%s, %s)" % (x,y)
            test_used_coords, test_loop_coords, test_loop_category = find_contour(test, x, y, test_used_coords, test_loop_coords, None)
print "FINAL", test_used_coords, test_loop_coords<jupyter_output><empty_output><jupyter_text>Find contours on nii image Load nii data from disk<jupyter_code>nii_obj=nib.load('./segmentation-010.nii')
nii_data = nii_obj.get_fdata()<jupyter_output><empty_output><jupyter_text>Convert nii matrix into per-dicom grid structure<jupyter_code>img_data = [[[[None] for x in range(322)] for y in range(1086)] for z in range(20)]
for x, rows in enumerate(nii_data):
    for y, depths in enumerate(rows):
        for z, v in enumerate(depths):
            if v != 0.0:
                print z, y, x, v
            img_data[z][y][x] = v
all_loops = []

for img in img_data:
    loop_coords = []
    used_coords = {}
    for y, rows in enumerate(img):
        for x, v in enumerate(rows):
            if v != 0.0:
                if y not in used_coords or x not in used_coords[y]:
                    # loop around for pixels
                    used_coords, single_loop_coords, loop_category = find_loop(img, x, y, used_coords, [], None)
                    loop_coords.append({'category': loop_category, 'coords': single_loop_coords})
    all_loops.append(loop_coords)<jupyter_output><empty_output><jupyter_text>Dump contour data into json file on disk<jupyter_code>d = {'dicoms':[]}
for i, img_loops in enumerate(all_loops):
    d['dicoms'].append({'contours':img_loops})
with open('contour-data.json', 'w') as outfile:
    json.dump(d, outfile)<jupyter_output><empty_output><jupyter_text>Generating image display with augmented contours<jupyter_code>import matplotlib.pyplot as plt
import matplotlib.patches as patches
import pydicom
from pydicom.data import get_testdata_files
import json, math

import numpy as np
import matplotlib
from shapely.geometry.polygon import LinearRing, Polygon
from matplotlib.collections import PatchCollection
with open('./contours-with-categories.json') as json_file:
    contour_data = json.load(json_file)<jupyter_output><empty_output><jupyter_text>Display augmented dicoms in a grid<jupyter_code>images = [
    './images/001-02.0.dcm', './images/002-06.0.dcm', './images/003-07.0.dcm',
    './images/004-08.0.dcm', './images/005-09.0.dcm', './images/006-10.0.dcm',
    './images/007-11.0.dcm', './images/008-12.0.dcm', './images/009-13.0.dcm',
    './images/010-14.0.dcm', './images/011-15.0.dcm', './images/012-16.0.dcm',
    './images/013-17.0.dcm', './images/014-18.0.dcm', './images/015-19.0.dcm',
    './images/016-20.0.dcm', './images/017-21.0.dcm', './images/018-22.0.dcm',
    './images/019-23.0.dcm', './images/020-24.0.dcm']

n_rows = math.ceil(len(images)*1.0/3)
plt.figure(figsize=(16, 16*n_rows))


for i, img in enumerate(images):
    ax = plt.subplot(n_rows, 3, i+1)
    ds = pydicom.dcmread(img)
    ax.imshow(ds.pixel_array, cmap=plt.cm.bone, vmin=0, vmax=255)
    
    contours = contour_data['dicoms'][i]['contours']
    for contour in contours:
        if len(contour['coords']) > 2:
            poly = Polygon(contour['coords'])
            x,y = poly.exterior.xy
            ax.plot(x, y, color='#ff0000', alpha=0.4,
                linewidth=1, solid_capstyle='round', zorder=2)


plt.suptitle('Tumor Segmentations')
plt.show()<jupyter_output><empty_output><jupyter_text>Export augmented dicoms to png files on disk<jupyter_code>images = [
    './images/001-02.0.dcm', './images/002-06.0.dcm', './images/003-07.0.dcm',
    './images/004-08.0.dcm', './images/005-09.0.dcm', './images/006-10.0.dcm',
    './images/007-11.0.dcm', './images/008-12.0.dcm', './images/009-13.0.dcm',
    './images/010-14.0.dcm', './images/011-15.0.dcm', './images/012-16.0.dcm',
    './images/013-17.0.dcm', './images/014-18.0.dcm', './images/015-19.0.dcm',
    './images/016-20.0.dcm', './images/017-21.0.dcm', './images/018-22.0.dcm',
    './images/019-23.0.dcm', './images/020-24.0.dcm']

plt.figure(figsize=(2, 16))

for i, img in enumerate(images):
    fig,ax = plt.subplots(1)
    fig.set_size_inches(18.5, 10.5)
    ds = pydicom.dcmread(img)
    ax.imshow(ds.pixel_array, cmap=plt.cm.bone, vmin=0, vmax=255)
    ax.axes.get_xaxis().set_visible(False)
    ax.axes.get_yaxis().set_visible(False)
    ax.set_frame_on(False)
    
    contours = contour_data['dicoms'][i]['contours']
    for contour in contours:
        if len(contour['coords']) > 2:
            poly = Polygon(contour['coords'])
            x,y = poly.exterior.xy
            ax.plot(x, y, color='#ff0000', alpha=0.4,
                linewidth=1, solid_capstyle='round', zorder=2)
    plt.axis('off')

    plt.savefig('./frames/%02d.png' % (i), transparent=False, bbox_inches='tight', pad_inches=0)
    plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17806603773584906, 'fraction_numerical': 0.0646619496855346, 'mean_word_length': 3.3532934131736525, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '512252', 'license': 'MIT', 'n_tokens_mistral': 2195, 'n_tokens_neox': 2006, 'n_words': 344, 'path': 'Generate Visualizations.ipynb', 'repo_name': 'DevonBernard/tumor-tensors', 'size': '5088'}