Spaces:
Runtime error
Runtime error
Manav Sarkar
commited on
Commit
·
e6fbb1f
1
Parent(s):
57b53ce
init
Browse files- .gitignore +4 -1
- Dockerfile +1 -1
- app.py +55 -41
- utils.py +451 -0
.gitignore
CHANGED
|
@@ -131,4 +131,7 @@ dmypy.json
|
|
| 131 |
|
| 132 |
.vscode/
|
| 133 |
|
| 134 |
-
data/audio/
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
.vscode/
|
| 133 |
|
| 134 |
+
data/audio/
|
| 135 |
+
|
| 136 |
+
gpr_model_withgender.pkl
|
| 137 |
+
MIN_RESNET101_BMI_Cache_test.pkl
|
Dockerfile
CHANGED
|
@@ -9,7 +9,7 @@ RUN apt-get update && xargs -r -a /app/packages.txt apt-get install -y && rm -rf
|
|
| 9 |
RUN pip3 install --no-cache-dir -r /app/requirements.txt
|
| 10 |
RUN pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
|
| 11 |
RUN wget -O /app/MIN_RESNET101_BMI_Cache_test.pkl "https://github.com/ManavSarkar/Weight-Prediction-using-Machine-Learning/releases/download/dataset/MIN_RESNET101_BMI_Cache_test.pkl"
|
| 12 |
-
RUN wget -O /app/
|
| 13 |
COPY detectron2 /app/detectron2
|
| 14 |
|
| 15 |
RUN pip install -e /app/detectron2
|
|
|
|
| 9 |
RUN pip3 install --no-cache-dir -r /app/requirements.txt
|
| 10 |
RUN pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
|
| 11 |
RUN wget -O /app/MIN_RESNET101_BMI_Cache_test.pkl "https://github.com/ManavSarkar/Weight-Prediction-using-Machine-Learning/releases/download/dataset/MIN_RESNET101_BMI_Cache_test.pkl"
|
| 12 |
+
RUN wget -O /app/gpr_model_withgender.pkl "https://github.com/ManavSarkar/Weight-Prediction-using-Machine-Learning/releases/download/dataset/gpr_model_withgender.pkl"
|
| 13 |
COPY detectron2 /app/detectron2
|
| 14 |
|
| 15 |
RUN pip install -e /app/detectron2
|
app.py
CHANGED
|
@@ -1,42 +1,56 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
-
|
| 3 |
-
import
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
from utils import *
|
| 3 |
+
import torch
|
| 4 |
+
import pickle
|
| 5 |
+
from PIL import Image
|
| 6 |
+
|
| 7 |
+
resnetmodel = custom_resnet()
|
| 8 |
+
resnetmodel.load_state_dict(torch.load('MIN_RESNET101_BMI_Cache_test.pkl', map_location=torch.device('cpu')))
|
| 9 |
+
resnetmodel = resnetmodel.to(device)
|
| 10 |
+
resnetmodel.eval()
|
| 11 |
+
gpr = pickle.load(open('gpr_model_withgender.pkl', 'rb'))
|
| 12 |
+
obj = Data_Processor()
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def get_features(img):
|
| 16 |
+
values = []
|
| 17 |
+
image = Image.open(img)
|
| 18 |
+
values.append(1)
|
| 19 |
+
body_feature = obj.test(image)
|
| 20 |
+
values.append(body_feature.WSR)
|
| 21 |
+
values.append(body_feature.WTR)
|
| 22 |
+
values.append(body_feature.WHpR)
|
| 23 |
+
values.append(body_feature.WHdR)
|
| 24 |
+
values.append(body_feature.HpHdR)
|
| 25 |
+
values.append(body_feature.Area)
|
| 26 |
+
values.append(body_feature.H2W)
|
| 27 |
+
image = Image.open(img)
|
| 28 |
+
image = ScaleAndPadTransform(224).transform(image)
|
| 29 |
+
data = data.unsqueeze(0)
|
| 30 |
+
data = image.to("cpu")
|
| 31 |
+
conv_out = LayerActivations(resnetmodel.fc1, 1)
|
| 32 |
+
out = resnetmodel(data)
|
| 33 |
+
conv_out.remove()
|
| 34 |
+
xs = torch.squeeze(conv_out.features.cpu().detach()).numpy()
|
| 35 |
+
|
| 36 |
+
for x in xs:
|
| 37 |
+
values.append(float(x))
|
| 38 |
+
|
| 39 |
+
return values
|
| 40 |
+
def main():
|
| 41 |
+
st.title("BMI Prediction App")
|
| 42 |
+
|
| 43 |
+
image = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png"])
|
| 44 |
+
if image is not None:
|
| 45 |
+
st.image(image, caption="Uploaded Image", use_column_width=True)
|
| 46 |
+
|
| 47 |
+
# Convert image to features
|
| 48 |
+
values = get_features(image)
|
| 49 |
+
|
| 50 |
+
# Predict BMI using Gaussian Process Regression
|
| 51 |
+
bmi_pred = gpr.predict([values])
|
| 52 |
+
|
| 53 |
+
st.write("Predicted BMI:", bmi_pred[0])
|
| 54 |
+
|
| 55 |
+
if __name__ == "__main__":
|
| 56 |
+
main()
|
utils.py
ADDED
|
@@ -0,0 +1,451 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image, ImageOps
|
| 2 |
+
from torchvision import transforms
|
| 3 |
+
|
| 4 |
+
class ScaleAndPadTransform:
|
| 5 |
+
def __init__(self, target_size):
|
| 6 |
+
self.target_size = target_size
|
| 7 |
+
|
| 8 |
+
def transform(self, img):
|
| 9 |
+
width, height = img.size
|
| 10 |
+
if width > height:
|
| 11 |
+
scale = self.target_size / width
|
| 12 |
+
new_height = int(height * scale)
|
| 13 |
+
img = img.resize((self.target_size, new_height))
|
| 14 |
+
padding = (self.target_size - new_height) // 2
|
| 15 |
+
img = ImageOps.expand(img, (0, padding, 0, self.target_size - new_height - padding))
|
| 16 |
+
else:
|
| 17 |
+
scale = self.target_size / height
|
| 18 |
+
new_width = int(width * scale)
|
| 19 |
+
img = img.resize((new_width, self.target_size))
|
| 20 |
+
padding = (self.target_size - new_width) // 2
|
| 21 |
+
img = ImageOps.expand(img, (padding, 0, self.target_size - new_width - padding, 0))
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
IMG_MEAN = [0.485, 0.456, 0.406]
|
| 25 |
+
IMG_STD = [0.229, 0.224, 0.225]
|
| 26 |
+
|
| 27 |
+
transform = transforms.Compose([
|
| 28 |
+
transforms.CenterCrop(self.target_size),
|
| 29 |
+
transforms.ToTensor(),
|
| 30 |
+
transforms.Normalize(IMG_MEAN, IMG_STD)
|
| 31 |
+
])
|
| 32 |
+
img = transform(img)
|
| 33 |
+
|
| 34 |
+
return img
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class Body_Figure(object):
|
| 38 |
+
def __str__(self):
|
| 39 |
+
return f"Body Figure Information:\n"\
|
| 40 |
+
f" - Waist-to-Shoulder Ratio (WSR): {self.WSR}\n"\
|
| 41 |
+
f" - Waist-to-Thigh Ratio (WTR): {self.WTR}\n"\
|
| 42 |
+
f" - Waist-to-Hip Ratio (WHpR): {self.WHpR}\n"\
|
| 43 |
+
f" - Waist-to-Head Ratio (WHdR): {self.WHdR}\n"\
|
| 44 |
+
f" - Hip-to-Head Ratio (HpHdR): {self.HpHdR}\n"\
|
| 45 |
+
f" - Area: {self.Area}\n"\
|
| 46 |
+
f" - Height-to-Waist Ratio (H2W): {self.H2W}\n"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def __init__(self, waist_width, thigh_width, hip_width, head_width, Area, height, shoulder_width):
|
| 50 |
+
self._waist_width = waist_width
|
| 51 |
+
self._thigh_width = thigh_width
|
| 52 |
+
self._hip_width = hip_width
|
| 53 |
+
self._head_width = head_width
|
| 54 |
+
self._Area = Area
|
| 55 |
+
self._height = height
|
| 56 |
+
self._shoulder_width = shoulder_width
|
| 57 |
+
if self._head_width == 0:
|
| 58 |
+
self._head_width = self._hip_width/3
|
| 59 |
+
|
| 60 |
+
@property
|
| 61 |
+
def WSR(self):
|
| 62 |
+
return (self._waist_width) / (self._shoulder_width)
|
| 63 |
+
|
| 64 |
+
@property
|
| 65 |
+
def WTR(self):
|
| 66 |
+
return (self._waist_width / self._thigh_width) # **2
|
| 67 |
+
|
| 68 |
+
@property
|
| 69 |
+
def WHpR(self):
|
| 70 |
+
return (self._waist_width / self._hip_width) # **2
|
| 71 |
+
|
| 72 |
+
@property
|
| 73 |
+
def WHdR(self):
|
| 74 |
+
return (self._waist_width / self._head_width) # **2
|
| 75 |
+
|
| 76 |
+
@property
|
| 77 |
+
def HpHdR(self):
|
| 78 |
+
return (self._hip_width / self._head_width) # **2
|
| 79 |
+
|
| 80 |
+
@property
|
| 81 |
+
def Area(self):
|
| 82 |
+
return self._Area
|
| 83 |
+
|
| 84 |
+
@property
|
| 85 |
+
def H2W(self):
|
| 86 |
+
return self._height / self._waist_width
|
| 87 |
+
|
| 88 |
+
import torch
|
| 89 |
+
import torch.nn as nn
|
| 90 |
+
import torch.optim as optim
|
| 91 |
+
|
| 92 |
+
def custom_resnet():
|
| 93 |
+
# resnet101
|
| 94 |
+
resnet_model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet101', pretrained=True)
|
| 95 |
+
|
| 96 |
+
resnet_model._modules.pop('fc') #1000 fc
|
| 97 |
+
|
| 98 |
+
resnet_model.fc1 = nn.Linear(2048, 15)
|
| 99 |
+
# resnet_model.fc1 = nn.Linear(2048, 15)
|
| 100 |
+
resnet_model.fc2 = nn.Sequential(
|
| 101 |
+
nn.ReLU(inplace=True),
|
| 102 |
+
nn.Linear(15, 1)
|
| 103 |
+
)
|
| 104 |
+
def forward(self, x):
|
| 105 |
+
x = self.conv1(x)
|
| 106 |
+
x = self.bn1(x)
|
| 107 |
+
x = self.relu(x)
|
| 108 |
+
x = self.maxpool(x)
|
| 109 |
+
|
| 110 |
+
x = self.layer1(x)
|
| 111 |
+
x = self.layer2(x)
|
| 112 |
+
x = self.layer3(x)
|
| 113 |
+
x = self.layer4(x) # 2048*7*7
|
| 114 |
+
|
| 115 |
+
x = self.avgpool(x)
|
| 116 |
+
x = torch.flatten(x, 1)
|
| 117 |
+
x = self.fc1(x)
|
| 118 |
+
x = self.fc2(x)
|
| 119 |
+
return x
|
| 120 |
+
|
| 121 |
+
# add new_forward function to the resnet instance as a class method
|
| 122 |
+
bound_method = forward.__get__(resnet_model, resnet_model.__class__)
|
| 123 |
+
setattr(resnet_model, 'forward', bound_method)
|
| 124 |
+
|
| 125 |
+
return resnet_model
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def custom_resnet_optimizer(resnet_model):
|
| 129 |
+
optimizer = optim.Adam(resnet_model.parameters(), lr=0.0001, betas=(0.9, 0.999), weight_decay=0.001)
|
| 130 |
+
return optimizer
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# scaling the longer side of image to 224 and pad the shorter size with zeroes to match 224x224
|
| 134 |
+
from PIL import Image, ImageOps
|
| 135 |
+
|
| 136 |
+
def scale_and_pad(img):
|
| 137 |
+
width, height = img.size
|
| 138 |
+
if width > height:
|
| 139 |
+
scale = 224 / width
|
| 140 |
+
new_height = int(height * scale)
|
| 141 |
+
img = img.resize((224, new_height))
|
| 142 |
+
padding = (224 - new_height) // 2
|
| 143 |
+
img = ImageOps.expand(img, (0, padding, 0, 224 - new_height - padding))
|
| 144 |
+
else:
|
| 145 |
+
scale = 224 / height
|
| 146 |
+
new_width = int(width * scale)
|
| 147 |
+
img = img.resize((new_width, 224))
|
| 148 |
+
padding = (224 - new_width) // 2
|
| 149 |
+
img = ImageOps.expand(img, (padding, 0, 224 - new_width - padding, 0))
|
| 150 |
+
return img
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
from torchvision import transforms
|
| 154 |
+
IMG_SIZE = 224
|
| 155 |
+
IMG_MEAN = [0.485, 0.456, 0.406]
|
| 156 |
+
IMG_STD = [0.229, 0.224, 0.225]
|
| 157 |
+
transform = transforms.Compose([
|
| 158 |
+
transforms.CenterCrop(IMG_SIZE),
|
| 159 |
+
transforms.ToTensor(),
|
| 160 |
+
transforms.Normalize(IMG_MEAN, IMG_STD)
|
| 161 |
+
])
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
from torch.utils.data import Dataset, DataLoader
|
| 165 |
+
from PIL import Image
|
| 166 |
+
import re
|
| 167 |
+
class CustomDataset(Dataset):
|
| 168 |
+
def __init__(self, dataset, transform=None):
|
| 169 |
+
self.data = dataset
|
| 170 |
+
self.transform = transform
|
| 171 |
+
|
| 172 |
+
def __len__(self):
|
| 173 |
+
return len(self.data.index)
|
| 174 |
+
|
| 175 |
+
def __getitem__(self, idx):
|
| 176 |
+
img_name = self.data.iloc[idx, 0]
|
| 177 |
+
img_path = 'datasets/Images/' + img_name # adjust the path to your actual image directory
|
| 178 |
+
image = Image.open(img_path)
|
| 179 |
+
image = scale_and_pad(image)
|
| 180 |
+
ret = re.match(r"\d+?_([FMfm])_(\d+?)_(\d+?)_(\d+).+", img_name)
|
| 181 |
+
BMI = (int(ret.group(4)) / 100000) / (int(ret.group(3)) / 100000) ** 2
|
| 182 |
+
|
| 183 |
+
if self.transform:
|
| 184 |
+
image = self.transform(image)
|
| 185 |
+
|
| 186 |
+
return (image,img_name), BMI
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
# train the resnet model on the train_img_tensors and train_labels
|
| 190 |
+
import torch
|
| 191 |
+
import torch.nn as nn
|
| 192 |
+
import torch.optim as optim
|
| 193 |
+
import numpy as np
|
| 194 |
+
|
| 195 |
+
from sklearn.metrics import mean_absolute_error
|
| 196 |
+
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
|
| 197 |
+
print(device)
|
| 198 |
+
|
| 199 |
+
# from detectron2 import detectron2
|
| 200 |
+
import numpy as np
|
| 201 |
+
import cv2
|
| 202 |
+
from detectron2 import model_zoo
|
| 203 |
+
from detectron2.engine import DefaultPredictor
|
| 204 |
+
from detectron2.config import get_cfg
|
| 205 |
+
from detectron2.utils.visualizer import Visualizer
|
| 206 |
+
from detectron2.data import MetadataCatalog, DatasetCatalog
|
| 207 |
+
|
| 208 |
+
# from Human_Parse import HumanParser
|
| 209 |
+
|
| 210 |
+
# "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"
|
| 211 |
+
# "COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x.yaml"
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class Image_Processor(object):
|
| 216 |
+
|
| 217 |
+
def __init__(self, masks_file, key_file, key_thresh=0.7):
|
| 218 |
+
|
| 219 |
+
self._KeypointCfg = self.__init_key(key_file, key_thresh)
|
| 220 |
+
self._KeypointsPredictor = DefaultPredictor(self._KeypointCfg)
|
| 221 |
+
|
| 222 |
+
self._Contourcfg=self.__init_mask(masks_file,key_thresh)
|
| 223 |
+
self._ContourPredictor = DefaultPredictor(self._Contourcfg)
|
| 224 |
+
|
| 225 |
+
# self._HumanParser = HumanParser()
|
| 226 |
+
|
| 227 |
+
def __init_key(self, key_file, key_thresh):
|
| 228 |
+
|
| 229 |
+
cfg = get_cfg()
|
| 230 |
+
cfg.merge_from_file(model_zoo.get_config_file(key_file))
|
| 231 |
+
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = key_thresh # set threshold for this model
|
| 232 |
+
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(key_file)
|
| 233 |
+
|
| 234 |
+
return cfg
|
| 235 |
+
|
| 236 |
+
def __init_mask(self, mask_file, key_thresh):
|
| 237 |
+
|
| 238 |
+
cfg = get_cfg()
|
| 239 |
+
cfg.merge_from_file(model_zoo.get_config_file(mask_file))
|
| 240 |
+
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = key_thresh # set threshold for this model
|
| 241 |
+
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(mask_file)
|
| 242 |
+
return cfg
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def get_keyandcontour_output(self, img):
|
| 246 |
+
|
| 247 |
+
Keypoints=self._Keypoints_detected(img)
|
| 248 |
+
|
| 249 |
+
ContourOutput=self._Contour_detected(img)
|
| 250 |
+
|
| 251 |
+
# """ Detect Arms Mask by Human parser """
|
| 252 |
+
# Arms_mask = self._HumanParser.Arms_detect(img)
|
| 253 |
+
# ContourOutput = ContourOutput ^ Arms_mask
|
| 254 |
+
|
| 255 |
+
return Keypoints, ContourOutput
|
| 256 |
+
|
| 257 |
+
def _Contour_detected(self,img):
|
| 258 |
+
|
| 259 |
+
ContourOutput=self._ContourPredictor(img)
|
| 260 |
+
sorted_idxs = np.argsort(-ContourOutput["instances"].scores.cpu().numpy())
|
| 261 |
+
ContourMasks = None
|
| 262 |
+
for sorted_idx in sorted_idxs:
|
| 263 |
+
if ContourOutput["instances"].pred_classes[sorted_idx] == 0:
|
| 264 |
+
ContourMasks = ContourOutput["instances"].pred_masks[sorted_idx].cpu().numpy()
|
| 265 |
+
|
| 266 |
+
ContourOutput = ContourMasks
|
| 267 |
+
return ContourOutput
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def _Keypoints_detected(self,img):
|
| 271 |
+
|
| 272 |
+
KeypointsOutput = self._KeypointsPredictor(img)
|
| 273 |
+
sorted_idxs = np.argsort(-KeypointsOutput["instances"].scores.cpu().numpy())
|
| 274 |
+
Keypoints = KeypointsOutput["instances"].pred_keypoints[sorted_idxs[0]].cpu().numpy()
|
| 275 |
+
|
| 276 |
+
return Keypoints
|
| 277 |
+
|
| 278 |
+
# def Process(self, img_RGB):
|
| 279 |
+
def get_figure(self, img):
|
| 280 |
+
Keypoints, ContourOutput = self.get_keyandcontour_output(img)
|
| 281 |
+
|
| 282 |
+
nose,left_ear,right_ear,left_shoulder,right_shoulder = Keypoints[0],Keypoints[4],Keypoints[3],Keypoints[6], Keypoints[5]
|
| 283 |
+
|
| 284 |
+
left_hip, right_hip, left_knee, right_knee = Keypoints[12], Keypoints[11], Keypoints[14],Keypoints[13]
|
| 285 |
+
|
| 286 |
+
y_hip = (left_hip[1] + right_hip[1]) / 2
|
| 287 |
+
y_knee = (left_knee[1] + right_knee[1]) / 2
|
| 288 |
+
|
| 289 |
+
center_shoulder = (left_shoulder + right_shoulder) / 2
|
| 290 |
+
|
| 291 |
+
y_waist = y_hip * 2 / 3 + (nose[1] + center_shoulder[1]) / 6
|
| 292 |
+
|
| 293 |
+
left_thigh = (left_knee + left_hip) / 2
|
| 294 |
+
right_thigh = (right_knee + right_hip) / 2
|
| 295 |
+
|
| 296 |
+
# estimate the waist width
|
| 297 |
+
waist_width = self.waist_width_estimate(center_shoulder, y_waist, ContourOutput)
|
| 298 |
+
|
| 299 |
+
# estimate the thigh width
|
| 300 |
+
thigh_width = self.thigh_width_estimate(left_thigh, right_thigh, ContourOutput)
|
| 301 |
+
|
| 302 |
+
# estimate the hip width
|
| 303 |
+
hip_width = self.hip_width_estimate(center_shoulder, y_hip, ContourOutput)
|
| 304 |
+
|
| 305 |
+
# estimate the head_width
|
| 306 |
+
head_width = self.head_width_estimate(left_ear, right_ear)
|
| 307 |
+
|
| 308 |
+
# estimate the Area
|
| 309 |
+
Area = self.Area_estimate(y_waist, y_hip, waist_width, hip_width, ContourOutput)
|
| 310 |
+
|
| 311 |
+
# estimate the height2waist
|
| 312 |
+
height = self.Height_estimate(y_knee, nose[1])
|
| 313 |
+
|
| 314 |
+
# estimate tht shoulder_width
|
| 315 |
+
shoulder_width = self.shoulder_width_estimate(left_shoulder, right_shoulder)
|
| 316 |
+
|
| 317 |
+
figure = Body_Figure(waist_width, thigh_width, hip_width, head_width, Area, height, shoulder_width)
|
| 318 |
+
|
| 319 |
+
# outputs = self._KeypointsPredictor(img)
|
| 320 |
+
# v = Visualizer(img[:,:,::-1], MetadataCatalog.get( self._KeypointCfg.DATASETS.TRAIN[0]), scale=1.2)
|
| 321 |
+
# out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
|
| 322 |
+
# # cv2_imshow(out.get_image()[:, :, ::-1])
|
| 323 |
+
# cv2.imwrite('random.jpg', out.get_image()[:, :, ::-1])
|
| 324 |
+
|
| 325 |
+
# outputs = self._ContourPredictor(img)
|
| 326 |
+
# v = Visualizer(img[:,:,::-1], MetadataCatalog.get( self._Contourcfg.DATASETS.TRAIN[0]), scale=1.2)
|
| 327 |
+
# out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
|
| 328 |
+
# # cv2_imshow(out.get_image()[:, :, ::-1])
|
| 329 |
+
# cv2.imwrite('random1.jpg', out.get_image()[:, :, ::-1])
|
| 330 |
+
|
| 331 |
+
return figure
|
| 332 |
+
|
| 333 |
+
def Height_estimate(self, y_k, y_n):
|
| 334 |
+
Height = np.abs(y_n - y_k)
|
| 335 |
+
return Height
|
| 336 |
+
|
| 337 |
+
def Area_estimate(self, y_w, y_h, W_w, H_w, mask):
|
| 338 |
+
# '''
|
| 339 |
+
# Area is expressed as thenumber of
|
| 340 |
+
# pixels per unit area between waist and hip
|
| 341 |
+
# '''
|
| 342 |
+
try:
|
| 343 |
+
pixels = np.sum(mask[int(y_w):int(y_h)][:])
|
| 344 |
+
except:
|
| 345 |
+
pixels=100
|
| 346 |
+
|
| 347 |
+
area = (y_h - y_w) * 0.5 * (W_w + H_w)
|
| 348 |
+
Area = pixels / area
|
| 349 |
+
return Area
|
| 350 |
+
|
| 351 |
+
def shoulder_width_estimate(self, left_shoulder, right_shoulder):
|
| 352 |
+
shoulder_width = np.sqrt((right_shoulder[0] - left_shoulder[0]) ** 2 + (right_shoulder[1] - left_shoulder[1]) ** 2)
|
| 353 |
+
return shoulder_width
|
| 354 |
+
|
| 355 |
+
def head_width_estimate(self, left_ear, right_eat):
|
| 356 |
+
head_width = np.sqrt((right_eat[0] - left_ear[0]) ** 2 + (right_eat[1] - left_ear[1]) ** 2)
|
| 357 |
+
return head_width
|
| 358 |
+
|
| 359 |
+
def hip_width_estimate(self, center_shoulder, y_hip, ContourOutput):
|
| 360 |
+
x_hip_center = int(center_shoulder[0])
|
| 361 |
+
try:
|
| 362 |
+
x_lhb = np.where(ContourOutput[int(y_hip)][:x_hip_center] == 0)[0]
|
| 363 |
+
x_lhb = x_lhb[-1] if len(x_lhb) else 0
|
| 364 |
+
except:
|
| 365 |
+
x_lhb = 10
|
| 366 |
+
try:
|
| 367 |
+
x_rhb = np.where(ContourOutput[int(y_hip)][x_hip_center:] == 0)[0]
|
| 368 |
+
x_rhb = x_rhb[0] + x_hip_center if len(x_rhb) else len(ContourOutput[0])
|
| 369 |
+
except:
|
| 370 |
+
x_rhb = 5
|
| 371 |
+
hip_width = x_rhb - x_lhb
|
| 372 |
+
return hip_width
|
| 373 |
+
|
| 374 |
+
def thigh_width_estimate(self, left_thigh, right_thigh, mask):
|
| 375 |
+
lx, ly = int(left_thigh[0]), int(left_thigh[1])
|
| 376 |
+
rx, ry = int(right_thigh[0]), int(right_thigh[1])
|
| 377 |
+
try:
|
| 378 |
+
x_ltb = np.where(mask[ly][:lx] == 0)[0]
|
| 379 |
+
x_ltb = x_ltb[-1] if len(x_ltb) else 0
|
| 380 |
+
except:
|
| 381 |
+
x_ltb = 10
|
| 382 |
+
try:
|
| 383 |
+
|
| 384 |
+
x_rtb = np.where(mask[ry][rx:] == 0)[0]
|
| 385 |
+
x_rtb = x_rtb[0] + rx if len(x_rtb) else len(mask[0])
|
| 386 |
+
except:
|
| 387 |
+
x_rtb = 0
|
| 388 |
+
l_width = (lx - x_ltb) * 2
|
| 389 |
+
r_width = (x_rtb - rx) * 2
|
| 390 |
+
|
| 391 |
+
thigh_width = (l_width + r_width) / 2
|
| 392 |
+
return thigh_width
|
| 393 |
+
|
| 394 |
+
def waist_width_estimate(self, center_shoulder, y_waist, ContourOutput):
|
| 395 |
+
x_waist_center = int(center_shoulder[0])
|
| 396 |
+
# plt.imshow(ContourOutput)
|
| 397 |
+
# plt.show()
|
| 398 |
+
try:
|
| 399 |
+
x_lwb = np.where(ContourOutput[int(y_waist)][:x_waist_center] == 0)[0]
|
| 400 |
+
x_lwb = x_lwb[-1] if len(x_lwb) else 0
|
| 401 |
+
except:
|
| 402 |
+
x_lwb = 10
|
| 403 |
+
print("err waist width")
|
| 404 |
+
try:
|
| 405 |
+
x_rwb = np.where(ContourOutput[int(y_waist)][x_waist_center:] == 0)[0]
|
| 406 |
+
x_rwb = x_rwb[0] + x_waist_center if len(x_rwb) else len(ContourOutput[0])
|
| 407 |
+
except:
|
| 408 |
+
x_rwb=0
|
| 409 |
+
print("err waist width")
|
| 410 |
+
# print(x_rwb)
|
| 411 |
+
waist_width = x_rwb - x_lwb
|
| 412 |
+
return waist_width
|
| 413 |
+
|
| 414 |
+
import numpy as np
|
| 415 |
+
import pandas
|
| 416 |
+
import cv2
|
| 417 |
+
from PIL import Image
|
| 418 |
+
import torchvision.models.detection
|
| 419 |
+
from torchvision.models.detection import maskrcnn_resnet50_fpn, MaskRCNN_ResNet50_FPN_Weights
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
class Data_Processor(object):
|
| 424 |
+
|
| 425 |
+
def __init__(self,mask_model="COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml",
|
| 426 |
+
keypoints_model = "COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x.yaml"):
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
self._img_pro = Image_Processor(mask_model,keypoints_model)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def get_image_info(self,df):
|
| 433 |
+
return df
|
| 434 |
+
|
| 435 |
+
def test(self,img):
|
| 436 |
+
# img = cv2.imread(img_path)
|
| 437 |
+
img = np.array(img)
|
| 438 |
+
figure = self._img_pro.get_figure(img)
|
| 439 |
+
return figure
|
| 440 |
+
|
| 441 |
+
class LayerActivations:
|
| 442 |
+
features = None
|
| 443 |
+
|
| 444 |
+
def __init__(self, model, layer_num):
|
| 445 |
+
self.hook = model.register_forward_hook(self.hook_fn)
|
| 446 |
+
|
| 447 |
+
def hook_fn(self, module, input, output):
|
| 448 |
+
self.features = output
|
| 449 |
+
|
| 450 |
+
def remove(self):
|
| 451 |
+
self.hook.remove()
|