File size: 2,830 Bytes
83cbde9 964bcc7 83cbde9 dda1637 83cbde9 6bb142c 041094d 6bb142c 97d80cd 6bb142c 83cbde9 d876962 83cbde9 964bcc7 854b5d0 83cbde9 a3598cf 964bcc7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | import gradio as gr
import cv2
import requests
import os
from PIL import Image
import timm
import torch
from torchvision.transforms import transforms
import numpy as np
from PIL import ImageFile
import matplotlib.pyplot as plt
import warnings
import glob
warnings.filterwarnings("ignore")
ImageFile.LOAD_TRUNCATED_IMAGES = True
def predict(image, model, device, class_name):
prediction_transform = transforms.Compose([transforms.Resize(size=(224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])
try:
image = prediction_transform(image)[:3,:,:].unsqueeze(0)
except:
image = image.convert('RGB')
image = prediction_transform(image)[:3,:,:].unsqueeze(0)
if device == 'cuda':
if torch.cuda.is_available():
image = image.cuda()
else:
print("You don't have cuda")
with torch.no_grad():
model.eval()
pred = model(image)
idx = torch.argmax(pred)
prob = pred[0][idx].item()*100
return prob, class_name[idx]
model = timm.create_model('resnet50', pretrained=True)
model.fc = torch.nn.Sequential(torch.nn.Linear(2048, 256),
torch.nn.Dropout(0.2),
torch.nn.ReLU(),
torch.nn.Linear(256, 64),
torch.nn.Dropout(0.2),
torch.nn.ReLU(),
torch.nn.Linear(64, 32),
torch.nn.Dropout(0.2),
torch.nn.ReLU(),
torch.nn.Linear(32, 4),
torch.nn.Softmax()
)
model.load_state_dict(torch.load('model_ResNet50_acc_max.pt',map_location=torch.device('cpu')))
display_prob = True
show=True
#path = glob.glob('*.png')
def show_preds_image(path):
#for image in path:
img = Image.open(path)
# if show:
# plt.imshow(img)
# plt.show()
#img = cv2.imread(path)
class_name = ['adenocarcinoma',
'large.cell.carcinoma',
'normal',
'squamous.cell.carcinoma']
prob, result = predict(img, model, 'cpu', class_name)
if display_prob:
print('Probability of {} : {:.6f}'.format(result, prob))
return result, prob
inputs_image = [
gr.components.Image(type="filepath", label="Input Image"),
]
interface_image = gr.Interface(
fn=show_preds_image,
inputs=inputs_image,
outputs="text",
title="Cancer Detector App using data from Kaggle",
cache_examples=False,
).launch()
|