diff --git a/mobilenetv2.py b/mobilenetv2.py deleted file mode 100644 index 116b631..0000000 --- a/mobilenetv2.py +++ /dev/null @@ -1,144 +0,0 @@ - -import torch.nn as nn -import math - -__all__ = ['mobilenetv2'] - - -def _make_divisible(v, divisor, min_value=None): - """ - This function is taken from the original tf repo. - It ensures that all layers have a channel number that is divisible by 8 - It can be seen here: - https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py - :param v: - :param divisor: - :param min_value: - :return: - """ - if min_value is None: - min_value = divisor - new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) - # Make sure that round down does not go down by more than 10%. - if new_v < 0.9 * v: - new_v += divisor - return new_v - - -def conv_3x3_bn(inp, oup, stride): - return nn.Sequential( - nn.Conv2d(inp, oup, 3, stride, 1, bias=False), - nn.BatchNorm2d(oup), - nn.ReLU(inplace=True) - ) - - -def conv_1x1_bn(inp, oup): - return nn.Sequential( - nn.Conv2d(inp, oup, 1, 1, 0, bias=False), - nn.BatchNorm2d(oup), - nn.ReLU(inplace=True) - ) - - -class InvertedResidual(nn.Module): - def __init__(self, inp, oup, stride, expand_ratio): - super(InvertedResidual, self).__init__() - assert stride in [1, 2] - - hidden_dim = round(inp * expand_ratio) - self.identity = stride == 1 and inp == oup - - if expand_ratio == 1: - self.conv = nn.Sequential( - # dw - nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False), - nn.BatchNorm2d(hidden_dim), - nn.ReLU(inplace=True), - # pw-linear - nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), - nn.BatchNorm2d(oup), - ) - else: - self.conv = nn.Sequential( - # pw - nn.Conv2d(inp, hidden_dim, 1, 1, 0, bias=False), - nn.BatchNorm2d(hidden_dim), - nn.ReLU(inplace=True), - # dw - nn.Conv2d(hidden_dim, hidden_dim, 3, stride, 1, groups=hidden_dim, bias=False), - nn.BatchNorm2d(hidden_dim), - nn.ReLU(inplace=True), - # pw-linear - nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), - nn.BatchNorm2d(oup), - ) - - def forward(self, x): - if self.identity: - return x + self.conv(x) - else: - return self.conv(x) - - -class MobileNetV2(nn.Module): - def __init__(self, num_classes=33, width_mult=1.): - super(MobileNetV2, self).__init__() - # setting of inverted residual blocks - self.cfgs = [ - # t, c, n, s - [1, 16, 1, 1], - [6, 24, 2, 2], - [6, 32, 3, 2], - [6, 64, 4, 2], - [6, 96, 3, 1], - [6, 160, 3, 2], - [6, 320, 1, 1], - ] - - # building first layer - input_channel = _make_divisible(32 * width_mult, 4 if width_mult == 0.1 else 8) - layers = [conv_3x3_bn(1, input_channel, 2)] - # building inverted residual blocks - block = InvertedResidual - for t, c, n, s in self.cfgs: - output_channel = _make_divisible(c * width_mult, 4 if width_mult == 0.1 else 8) - for i in range(n): - layers.append(block(input_channel, output_channel, s if i == 0 else 1, t)) - input_channel = output_channel - self.features = nn.Sequential(*layers) - # building last several layers - output_channel = _make_divisible(1280 * width_mult, 4 if width_mult == 0.1 else 8) if width_mult > 1.0 else 1280 - self.conv = conv_1x1_bn(input_channel, output_channel) - self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) - self.classifier = nn.Linear(output_channel, num_classes) - - self._initialize_weights() - - def forward(self, x): - x = self.features(x) - x = self.conv(x) - x = self.avgpool(x) - x = x.view(x.size(0), -1) - x = self.classifier(x) - return x - - def _initialize_weights(self): - for m in self.modules(): - if isinstance(m, nn.Conv2d): - n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels - m.weight.data.normal_(0, math.sqrt(2. / n)) - if m.bias is not None: - m.bias.data.zero_() - elif isinstance(m, nn.BatchNorm2d): - m.weight.data.fill_(1) - m.bias.data.zero_() - elif isinstance(m, nn.Linear): - m.weight.data.normal_(0, 0.01) - m.bias.data.zero_() - -def mobilenetv2(**kwargs): - """ - Constructs a MobileNet V2 model - """ - return MobileNetV2(**kwargs) \ No newline at end of file diff --git a/modelv2.pt b/modelv2.onnx similarity index 53% rename from modelv2.pt rename to modelv2.onnx index 3e01a24..c21b799 100644 Binary files a/modelv2.pt and b/modelv2.onnx differ diff --git a/model_loader_no_Crop.py b/onnxinference.py similarity index 69% rename from model_loader_no_Crop.py rename to onnxinference.py index 7123bd2..ba7ff0e 100644 --- a/model_loader_no_Crop.py +++ b/onnxinference.py @@ -1,37 +1,20 @@ -import mobilenetv2 -import cv2 +import onnx import torch -import matplotlib.pyplot as plt +import onnxruntime as ort +import numpy as np +import cv2 import time from pythonosc import udp_client - OSCip="127.0.0.1" OSCport= 9000 #VR Chat OSC port client = udp_client.SimpleUDPClient(OSCip, OSCport) - - -def vc(): - vc.height = 1 - vc.width = 1 - vc.roicheck = 1 -vc() -#check if cuda is available -if torch.cuda.is_available(): - device = torch.device("cuda") - print("CUDA is available") -else: - device = torch.device("cpu") - print("CUDA is not available") -#cheekPuff,cheekSquint_L,cheekSquint_R,noseSneer_L,noseSneer_R,jawOpen,jawForward,jawLeft,jawRight,mouthFunnel,mouthPucker,mouthLeft,mouthRight,mouthRollUpper,mouthRollLower,mouthShrugUpper,mouthShrugLower,mouthClose,mouthSmile_L,mouthSmile_R,mouthFrown_L,mouthFrown_R,mouthDimple_L,mouthDimple_R,mouthUpperUp_L,mouthUpperUp_R,mouthLowerDown_L,mouthLowerDown_R,mouthPress_L,mouthPress_R,mouthStretch_L,mouthStretch_R,tongueOut classes = ["cheekPuff", "cheekSquint_L", "cheekSquint_R", "noseSneer_L", "noseSneer_R", "jawOpen", "jawForward", "jawLeft", "jawRight", "mouthFunnel", "mouthPucker", "mouthLeft", "mouthRight", "mouthRollUpper", "mouthRollLower", "mouthShrugUpper", "mouthShrugLower", "mouthClose", "mouthSmile_L", "mouthSmile_R", "mouthFrown_L", "mouthFrown_R", "mouthDimple_L", "mouthDimple_R", "mouthUpperUp_L", "mouthUpperUp_R", "mouthLowerDown_L", "mouthLowerDown_R", "mouthPress_L", "mouthPress_R", "mouthStretch_L", "mouthStretch_R", "tongueOut"] -device = torch.device("cpu") -model = mobilenetv2.mobilenetv2().to(device) -model.load_state_dict(torch.load('modelv2.pt')) -model.eval() cap = cv2.VideoCapture(0) +sessionOptions = ort.SessionOptions() +ort_sess = ort.InferenceSession("modelv2.onnx", providers = ['CPUExecutionProvider']) while True: #read the frame ret, frame = cap.read() @@ -42,19 +25,15 @@ while True: img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) img = cv2.resize(img, (100,100)) gray = cv2.GaussianBlur(img, (3, 3), 0) - image = gray.reshape(1,1, 100, 100) - image = torch.from_numpy(image).to(device) - image = image.float() - start = time.time() - output = model(image) + image = gray.reshape(1,1, 100, 100) + image = torch.from_numpy(image).float() + #make numpy array + image = image.numpy() + outputs = ort_sess.run(None, {'input': image}) end = time.time() - #print fps - print(1/(end-start)) - output = output.detach().cpu().numpy() - #get the avatar/parameter/jawOpen' - output = output[0] - output = output.tolist() - #multiply by 100 + output = outputs[0][0] + output = output.tolist() + print(output[0]) output = [x * 100 for x in output] client.send_message("/cheekPuff", output[0]) client.send_message("/cheekSquintLeft", output[1]) @@ -89,8 +68,8 @@ while True: client.send_message("/mouthStretchLeft", output[30]) client.send_message("/mouthStretchRight", output[31]) client.send_message("/tongueOut", output[32]) - #show the image - cv2.imshow("image", gray) + #show image + cv2.imshow("frame", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..346255c --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +numpy==1.23.1 +onnx==1.12.0 +onnxruntime==1.12.1 +opencv_python==4.6.0.66 +python_osc==1.8.0 +torch==1.12.1+cu116