--- title: Pneumothorax demo keywords: fastai sidebar: home_sidebar nb_path: "06_pneumothorax.ipynb" ---
from fastai.vision.all import *
from fastai.medical.imaging import *
import torchvision
import torchvision.transforms as t
pneumothorax_source = untar_data(URLs.SIIM_SMALL)
items = get_dicom_files(pneumothorax_source/f"train/")
df = pd.read_csv(pneumothorax_source/f"labels.csv")
df.head()
df_pneumo = df[df['label']=='Pneumothorax']
pneumothorax = DataBlock(blocks=(ImageBlock(cls=PILDicom), MaskBlock(codes=['bg','pneumo'])),
get_x=lambda x:pneumothorax_source/f"{x[0]}",
get_y=lambda x:'example/siim/'+Path(x[0]).stem+'.png',
batch_tfms=aug_transforms(do_flip=False,p_affine=0,p_lighting=0,size=224))
dls = pneumothorax.dataloaders(df_pneumo.values, num_workers=0, bs=16)
dls.show_batch(max_n=16, vmin=0)
learn = unet_learner(dls, resnet34)
learn.fine_tune(1)
# this is skipped when testing, instead a single epoch is done (not sufficient for overfitting)
learn = unet_learner(dls, resnet34)
learn.fine_tune(8)
learn.show_results(ds_idx=0,max_n=9,vmin=0)
preds = learn.get_preds(ds_idx=0)
plt.imshow(preds[1][2])
preds[0].argmax(dim=1).sum()
#plt.imshow(preds[0].argmax(dim=1)[0])
learn.fine_tune(8)
learn.recorder.plot_loss()
preds = learn.get_preds(ds_idx=0)
preds[0].argmax(dim=1).sum()
fig, axs = plt.subplots(5,2,figsize=(8,16))
for i in range(5):
axs[i,0].imshow(preds[1][i])
axs[i,1].imshow(preds[0][i][1])
print(preds[0][i][1].max())
learn.fit_one_cycle(8)
preds = learn.get_preds(ds_idx=0)
preds[0].argmax(dim=1).sum()
learn.fit_one_cycle(20)
preds = learn.get_preds(ds_idx=0)
preds[0].argmax(dim=1).sum()
fig, axs = plt.subplots(5,3,figsize=(12,16))
for i in range(5):
axs[i,0].imshow(preds[1][i], interpolation="nearest")
axs[i,1].imshow(preds[0][i][1])
axs[i,2].imshow(preds[0].argmax(dim=1)[i], interpolation="nearest")
learn.save('pneumothorx')
learn.load('pneumothorx')
from misas.core import *
from fastai.vision.all import * #open_mask, Image, ImageSegment
import pydicom
def read_dcm(file):
ds = pydicom.dcmread(file)
img = Tensor(ds.pixel_array.astype(np.int16))
img = img/img.max()
transform = t.ToPILImage()
img = transform (torch.stack([img, img, img]))
return img
learn.predict(learn.dls.train_ds.items[1])[0].show(vmin=0)
fname = df_pneumo.iloc[3]['file']
img = lambda: read_dcm(pneumothorax_source/fname)
trueMask = lambda: Image.open('example/siim/'+Path(fname).stem+'.png') #open_mask('example/siim/'+Path(fname).stem+'.png')
dcm = img()
dcm
#to_image(dcm.data)
pred = learn.predict(PILDicom(dcm))[1]
plt.imshow(pred)
class Fastai2_wrapper:
def __init__(self, model):
self.model = model
self.model.cbs = L([])
def imageToPILDicom(self, image):
return PILDicom(image)
def prepareSize(self, imageOrMask):
return imageOrMask.resize((224,224))
def predict(self, image):
image = self.imageToPILDicom(image)
pred = self.model.predict(image)[0]#(in_image)
return Image.fromarray(np.array(pred).astype(np.uint8))
model = Fastai2_wrapper(learn)
plt.imshow(model.predict(img()))
plot_series(get_rotation_series(img(), model))
result = eval_rotation_series(img(), trueMask(), model, start=-180, end=180, components=['bg','pneumo'])
plt.plot(result['deg'],result['pneumo'])