PDG commited on
Commit
2b37f77
·
1 Parent(s): d599383

Create new file

Browse files
Files changed (1) hide show
  1. app.py +127 -0
app.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import gradio as gr
4
+ import torch
5
+ from torchvision import models, transforms
6
+ from PIL import Image
7
+
8
+
9
+ # -- install detectron2 from source ------------------------------------------------------------------------------
10
+ os.system('pip install git+https://github.com/facebookresearch/detectron2.git')
11
+ os.system('pip install pyyaml==5.1')
12
+
13
+ import detectron2
14
+
15
+ from detectron2.utils.logger import setup_logger
16
+
17
+ from detectron2 import model_zoo
18
+ from detectron2.engine import DefaultPredictor
19
+ from detectron2.config import get_cfg
20
+ from detectron2.utils.visualizer import Visualizer
21
+ from detectron2.data import MetadataCatalog, DatasetCatalog
22
+ import cv2
23
+
24
+
25
+ setup_logger()
26
+
27
+ # -- load rcnn model ---------------------------------------------------------------------------------------------
28
+ cfg = get_cfg()
29
+ # load model config
30
+ cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"))
31
+ cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set threshold for this model
32
+ # set model weights
33
+ cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")
34
+ cfg.MODEL.DEVICE= 'cpu' # move to cpu
35
+ predictor = DefaultPredictor(cfg) # create model
36
+
37
+ # -- load design modernity model for classification --------------------------------------------------------------
38
+ DesignModernityModel = torch.load("DesignModernityModel.pt")
39
+
40
+ DesignModernityModel.eval() # set state of the model to inference
41
+
42
+ # Set class labels
43
+ LABELS = ['2000-2003', '2006-2008', '2009-2011', '2012-2014', '2015-2018']
44
+ n_labels = len(LABELS)
45
+
46
+ # define maéan and std dev for normalization
47
+ MEAN = [0.485, 0.456, 0.406]
48
+ STD = [0.229, 0.224, 0.225]
49
+
50
+ # define image transformation steps
51
+ carTransforms = transforms.Compose([transforms.Resize(224),
52
+ transforms.ToTensor(),
53
+ transforms.Normalize(mean=MEAN, std=STD)])
54
+
55
+
56
+ # -- define a function for extraction of the detected car ---------------------------------------------------------
57
+ def cropImage(outputs, im, boxes, car_class_true):
58
+ # Get the masks
59
+ masks = list(np.array(outputs["instances"].pred_masks[car_class_true]))
60
+ max_idx = torch.tensor([(x[2] - x[0])*(x[3] - x[1]) for x in boxes]).argmax().item()
61
+
62
+ # Pick an item to mask
63
+ item_mask = masks[max_idx]
64
+
65
+ # Get the true bounding box of the mask
66
+ segmentation = np.where(item_mask == True) # return a list of different position in the bow, which are the actual detected object
67
+ x_min = int(np.min(segmentation[1])) # minimum x position
68
+ x_max = int(np.max(segmentation[1]))
69
+ y_min = int(np.min(segmentation[0]))
70
+ y_max = int(np.max(segmentation[0]))
71
+
72
+ # Create cropped image from the just portion of the image we want
73
+ cropped = Image.fromarray(im[y_min:y_max, x_min:x_max, :], mode = 'RGB')
74
+ # Create a PIL Image out of the mask
75
+ mask = Image.fromarray((item_mask * 255).astype('uint8')) ###### change 255
76
+ # Crop the mask to match the cropped image
77
+ cropped_mask = mask.crop((x_min, y_min, x_max, y_max))
78
+
79
+ # Load in a background image and choose a paste position
80
+ height = y_max-y_min
81
+ width = x_max-x_min
82
+ background = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255, 0))
83
+
84
+ # Create a new foreground image as large as the composite and paste the cropped image on top
85
+ new_fg_image = Image.new('RGB', background.size)
86
+ new_fg_image.paste(cropped)
87
+
88
+ # Create a new alpha mask as large as the composite and paste the cropped mask
89
+ new_alpha_mask = Image.new('L', background.size, color=0)
90
+ new_alpha_mask.paste(cropped_mask)
91
+
92
+ #composite the foreground and background using the alpha mask
93
+ composite = Image.composite(new_fg_image, background, new_alpha_mask)
94
+
95
+ return composite
96
+
97
+ # -- define function for image segmentation and classification --------------------------------------------------------
98
+ def classifyCar(im):
99
+ # read image
100
+ #im = cv2.imread(im)
101
+ # perform segmentation
102
+ outputs = predictor(im)
103
+ v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1)
104
+ out = v.draw_instance_predictions(outputs["instances"])
105
+ # check if a car was detected in the image
106
+ car_class_true = outputs["instances"].pred_classes == 2
107
+ boxes = list(outputs["instances"].pred_boxes[car_class_true])
108
+
109
+ # if a car was detected, extract the car and perform modernity score classification
110
+ if len(boxes) != 0:
111
+ im2 = cropImage(outputs, im, boxes, car_class_true)
112
+
113
+
114
+ with torch.no_grad():
115
+ scores = torch.nn.functional.softmax(DesignModernityModel(carTransforms(im2).unsqueeze(0))[0])
116
+ label = {LABELS[i]: float(scores[i]) for i in range(n_labels)}
117
+
118
+ # if no car was detected, show original image and print "No car detected"
119
+ else:
120
+ im2 = Image.fromarray(np.uint8(im)).convert('RGB')
121
+ label = "No car detected"
122
+
123
+ return im2, label
124
+
125
+ # -- create interface for model ----------------------------------------------------------------------------------------
126
+ interface = gr.Interface(classifyCar, inputs='image', outputs=['image','label'], cache_examples=False, title='Modernity car classification')
127
+ interface.launch()