Niklas Kallinger
Update app.py
64087b8 verified
Raw History Blame
9.12 kB
from PIL import Image
import gradio as gr
import numpy as np
import pandas as pd
from PIL import Image, ImageOps
import torch
import torch.nn as nn
from torchvision import models, transforms
import sys, os, distutils.core
# detectron
sys.path.insert(0, os.path.abspath("./detectron2"))
from detectron2 import model_zoo
from detectron2.utils.logger import setup_logger
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
# gradcam
from torchcam.methods import GradCAM
from torchcam.utils import overlay_mask
from torchvision.transforms.functional import to_pil_image
# initialize logger for detectron
setup_logger()
activation = {}
def getActivation(name):
def hook(model_typicality, input, output):
activation[name] = output.detach()
return hook
def save_img(img, path="error.jpg"):
img = img.astype(np.uint8)
data = Image.fromarray(img)
data.save(path)
return None
softmax = nn.Softmax(dim=1)
cos = nn.CosineSimilarity(dim=1)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# initialize detectron configuration for mask r-cnn instance segmentation
dist = distutils.core.run_setup("./detectron2/setup.py")
cfg = get_cfg()
cfg.merge_from_file(
model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")
)
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(
"COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"
)
cfg.MODEL.DEVICE = "cpu"
predictor = DefaultPredictor(cfg)
# initialize design modernity model
modernity_model = models.resnet18(weights="ResNet18_Weights.DEFAULT")
num_features = modernity_model.fc.in_features
modernity_model.fc = nn.Linear(num_features, 5)
modernity_model.load_state_dict(torch.load("best_model.pth", map_location=torch.device("cpu")))
# initialize design typicality model
typicality_model = models.resnet18(weights="ResNet18_Weights.DEFAULT")
num_features = typicality_model.fc.in_features
typicality_model.fc = nn.Linear(num_features, 5)
typicality_model.load_state_dict(torch.load("best_model2.pth", map_location=torch.device("cpu")))
morph_avg = torch.load("morph.pth")
# initialize gradcam for both resnet models
modernity_cam = GradCAM(modernity_model, target_layer="layer4")
typicality_cam = GradCAM(typicality_model, target_layer="layer4")
# define transformations
test_transforms = transforms.Compose(
[
transforms.Resize(size=(224, 224)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
]
)
def pad_and_resize(image):
img_width, img_height = image.size
if img_width != img_height:
max_dimension = max(img_width, img_height)
pad_width = max_dimension - img_width
pad_height = max_dimension - img_height
padding = (
pad_width // 2,
pad_height // 2,
pad_width - (pad_width // 2),
pad_height - (pad_height // 2),
)
padded_image = ImageOps.expand(image, padding, fill="white")
else:
padded_image = image
return padded_image
# dictionaries
bodytype_dict = {"Convertible": 0, "Hatchback": 1, "MPV": 2, "SUV": 3, "Saloon": 4}
years_dict = {
"2000-2003": 0,
"2006-2008": 1,
"2009-2011": 2,
"2012-2014": 3,
"2015-2018": 4,
}
groups_dict = {
"Convertible_2000-2003": 0,
"Convertible_2006-2008": 1,
"Convertible_2009-2011": 2,
"Convertible_2012-2014": 3,
"Convertible_2015-2018": 4,
"Hatchback_2000-2003": 5,
"Hatchback_2006-2008": 6,
"Hatchback_2009-2011": 7,
"Hatchback_2012-2014": 8,
"Hatchback_2015-2018": 9,
"MPV_2000-2003": 10,
"MPV_2006-2008": 11,
"MPV_2009-2011": 12,
"MPV_2012-2014": 13,
"MPV_2015-2018": 14,
"SUV_2000-2003": 15,
"SUV_2006-2008": 16,
"SUV_2009-2011": 17,
"SUV_2012-2014": 18,
"SUV_2015-2018": 19,
"Saloon_2000-2003": 20,
"Saloon_2006-2008": 21,
"Saloon_2009-2011": 22,
"Saloon_2012-2014": 23,
"Saloon_2015-2018": 24,
}
def analyze(image):
target_class = 2
pil_image = Image.fromarray(image.astype("uint8"), "RGB")
image_array = np.array(pil_image)
outputs = predictor(image_array)
masks = outputs["instances"].pred_masks
pred_classes = outputs["instances"].pred_classes.tolist()
mask_areas = torch.sum(torch.flatten(masks, start_dim=1), dim=1).tolist()
total_area = []
car_indices = []
for idx in range(len(pred_classes)):
if pred_classes[idx] == target_class:
total_area.append(mask_areas[idx])
car_indices.append(idx)
if len(car_indices) == 0:
detected_car = Image.open("please_try_again.jpg")
modernity_heatmap, typicality_heatmap = None, None
modernity_score = "Unfortunately, no design modernity score could be obtained as no automobile instances could be detected in the image."
typicality_score = "Unfortunately, no design typicality score could be obtained as no automobile instances could be detected in the image."
return (
modernity_score,
typicality_score,
detected_car,
modernity_heatmap,
typicality_heatmap,
)
local_idx = total_area.index(max(total_area))
global_idx = car_indices[local_idx]
unsq = outputs["instances"].pred_masks[global_idx].unsqueeze(-1).to("cpu")
mult = torch.tensor(image_array) * unsq
unsq = unsq.int()
unsq[unsq == 0] = 255
unsq[unsq == 1] = 0
mult = mult + unsq
detected_car = mult.numpy()
mask = outputs["instances"].pred_masks[global_idx].cpu().numpy()
coords = np.column_stack(np.where(mask))
y1, x1 = coords.min(axis=0)
y2, x2 = (
coords.max(axis=0) + 1
)
cropped_image = detected_car[y1:y2, x1:x2]
save_img(cropped_image, path="cropped_image.jpg")
img_pred0 = Image.open("cropped_image.jpg")
resized_image = pad_and_resize(img_pred0)
img_pred = test_transforms(img_pred0)
modernity_model.eval()
score_t = modernity_model(img_pred.unsqueeze(0))
score_t = softmax(score_t)
model_year = score_t.argmax(1, keepdim=True).item()
modernity_activation_map = modernity_cam(model_year, score_t)
modernity_heatmap = overlay_mask(
resized_image,
to_pil_image(modernity_activation_map[0].squeeze(0), mode="F"),
alpha=0.5,
)
range_tensor = torch.arange(0, score_t.numel()).to(device)
score_t = torch.mul(range_tensor, torch.reshape(score_t, (-1,))).sum().item()
typicality_model.eval()
logits = typicality_model(img_pred.unsqueeze(0))
outputs = softmax(logits)
type = outputs.argmax(1, keepdim=True).item()
typicality_activation_map = typicality_cam(type, logits)
typicality_heatmap = overlay_mask(
resized_image,
to_pil_image(typicality_activation_map[0].squeeze(0), mode="F"),
alpha=0.5,
)
model_avg = pd.DataFrame()
h1 = typicality_model.avgpool.register_forward_hook(getActivation("avgpool"))
out = typicality_model(img_pred.unsqueeze(0))
act_pool_t = activation["avgpool"]
act_pool_t = act_pool_t.squeeze()
h1.remove()
model_year = list(years_dict.keys())[list(years_dict.values()).index(model_year)]
model_type = list(bodytype_dict.keys())[list(bodytype_dict.values()).index(type)]
true_idx = groups_dict[model_type + "_" + model_year]
cos_t = cos(morph_avg[true_idx].unsqueeze(0), act_pool_t.unsqueeze(0)).item()
modernity_score = f"{round(score_t, 2)} (on a scale from 0 to 4)"
typicality_score = f"{round(cos_t, 2)} (on a scale from 0 to 1)"
return (
modernity_score,
typicality_score,
cropped_image,
modernity_heatmap,
typicality_heatmap,
)
example_images = [
["no_carfront.jpg"],
["multiple_carfronts.jpg"],
["one_carfront.jpg"],
]
interface = gr.Interface(
fn=analyze,
inputs=gr.Image(label="Uploaded Image That Should Contain the Front of a Car"),
outputs=[
gr.Textbox(label="Design Modernity Score"),
gr.Textbox(label="Design Typicality Score"),
gr.Image(type="pil", label="Cropped Image of the (Salient) Detected Car"),
gr.Image(
type="pil",
label="Heatmap Highlighting the Regions on Which the Neural Network That Predicts Year Focuses",
),
gr.Image(
type="pil",
label="Heatmap Highlighting the Regions on Which the Neural Network That Predicts Year and Body Type Focuses",
),
],
title="Design Modernity and Typicality of Automobiles",
description="Please upload an image of an automobile to get design modernity and typicality scores for the car. Please note that this tool<br>only works properly if the uploaded image contains the front of a car.<br><br>Instead of uploading an image yourself, you can also select one of the three example images at the bottom left to try out the<br>tool.",
examples=example_images,
)
interface.launch()