# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

import matplotlib.pyplot as plt
from skimage.measure import find_contours, regionprops, label
from skimage import io
import cv2
import numpy as np
import skimage
from skimage import measure
print(skimage.__version__)
from PIL import Image


# +
 def imshow(*args,**kwargs):
     """ Handy function to show multiple plots in on row, possibly with different cmaps and titles
     Usage:
     imshow(img1, title="myPlot")
     imshow(img1,img2, title=['title1','title2'])
     imshow(img1,img2, cmap='hot')
     imshow(img1,img2,cmap=['gray','Blues']) """
     cmap = kwargs.get('cmap', 'gray')
     title= kwargs.get('title','')
     axis_off = kwargs.get('axis_off','')
     if len(args)==0:
         raise ValueError("No images given to imshow")
     elif len(args)==1:
         plt.title(title)
         plt.imshow(args[0], interpolation='none')
     else:
         n=len(args)
         if type(cmap)==str:
             cmap = [cmap]*n
         if type(title)==str:
             title= [title]*n
         plt.figure(figsize=(n*5,10))
         for i in range(n):
             plt.subplot(1,n,i+1)
             plt.title(title[i])
             plt.imshow(args[i], cmap[i])
             if axis_off:
               plt.axis('off')
     plt.show()

def TissueMaskGenerationPatch(patchRGB):
    '''
    Returns mask of tissue that obeys the threshold set by paip
    '''
    r = patchRGB[:,:,0] < 235
    g = patchRGB[:,:,1] < 210
    b = patchRGB[:,:,2] < 235
    tissue_mask = np.logical_or(r,np.logical_or(g,b))
    return tissue_mask 


# -

img_paths = ['../../results/saved_imgs/val_7/ref_142.png']
for img_path in img_paths:
    img = io.imread(img_path)
    _,w,_ = img.shape
    w = w//4
    viable_mask = np.average(img[:,w*3:w*4,:],axis=2)
    slide_img = io.imread('../../results/saved_imgs/ref_imgs_pid/01_01_0083.png')[:,:2847,:]
    whole_tum = np.average(io.imread('../../results/saved_imgs/ref_imgs_pid/01_01_0083.png')[:,5694:,:],axis=2)
    kernel = np.ones((20, 20), dtype=np.uint8)
    img = cv2.morphologyEx(img_raw, cv2.MORPH_OPEN, kernel)
    kernel = np.ones((70, 70), dtype=np.uint8)
    img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
    img = np.uint8(img)
    print(img.shape)
    print(np.unique(img))
    imshow(img_raw,img,slide_img,whole_tum)



b = label(img)
print(np.unique(b))
plt.imshow(b)

r = regionprops(img)
xtl,ytl,xbr,ybr = r[0].bbox

wt = np.zeros_like(img_raw)
wt[xtl:xbr,ytl:ybr] = 255
wt = wt*TissueMaskGenerationPatch(slide_img)
imshow(wt,whole_tum,img_raw)

np.unique(img_raw)

actual_whole_tum = np.sum(whole_tum)/255 
pred_whole_tum = np.sum(wt)/255
viable_tum = np.sum(img_raw)/255
print(actual_whole_tum,pred_whole_tum,viable_tum)
print(viable_tum/actual_whole_tum,viable_tum/pred_whole_tum)

for prop in r:
    for a in prop:
        print(a,prop[a])

# +
# Find contours at a constant value of 0.8
contours = measure.find_contours(img, 0.8)

# Display the image and plot all contours found
fig, ax = plt.subplots()
ax.imshow(img, interpolation='nearest', cmap=plt.cm.gray)

for n, contour in enumerate(contours):
    ax.plot(contour[:, 1], contour[:, 0], linewidth=1)

ax.axis('image')
ax.set_xticks([])
ax.set_yticks([])
plt.show()
# -

aa,contours,_ = cv2.findContours(img.astype('uint8'), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
out = np.zeros_like(img)
cv2.drawContours(out,contours,-1,255,3)
imshow(out,img,aa)

print(np.unique(out))
Image.fromarray(out.astype('uint8'))



StarcoderdataJupyterScriptsDedupFiltered