Spaces:
Runtime error
Runtime error
initial2
Browse files- Interface_Dependencies/plaus_functs.py +124 -0
- Interface_Dependencies/plot_functs.py +97 -0
- Interface_Dependencies/run_methods.py +156 -0
- Interface_Dependencies/smooth_grad.py +56 -0
- ffmpeg.7z +3 -0
- individual_work/asien/asien_interface.py +29 -0
- individual_work/braedon/braedon_settings.py +69 -0
- individual_work/ike/olddetect.py +248 -0
- outputs/runs/detect/exp/layers/layer0.jpg +0 -0
- references/error_fixes/online_help.md +3 -0
- references/gradio_exs/exstream.py +13 -0
Interface_Dependencies/plaus_functs.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Current Implementation of Smooth_grad (Allows more choices)
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import numpy as np
|
| 5 |
+
from plot_functs import *
|
| 6 |
+
|
| 7 |
+
def generate_vanilla_grad(model, input_tensor, loss_func = None,
|
| 8 |
+
targets=None, metric=None, out_num = 1,
|
| 9 |
+
norm=False, device='cpu'):
|
| 10 |
+
"""
|
| 11 |
+
Computes the vanilla gradient of the input tensor with respect to the output of the given model.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
model (torch.nn.Module): The model to compute the gradient with respect to.
|
| 15 |
+
input_tensor (torch.Tensor): The input tensor to compute the gradient for.
|
| 16 |
+
loss_func (callable, optional): The loss function to use. If None, the gradient is computed with respect to the output tensor.
|
| 17 |
+
targets (torch.Tensor, optional): The target tensor to use with the loss function. Defaults to None.
|
| 18 |
+
metric (callable, optional): The metric function to use with the loss function. Defaults to None.
|
| 19 |
+
out_num (int, optional): The index of the output tensor to compute the gradient with respect to. Defaults to 1.
|
| 20 |
+
norm (bool, optional): Whether to normalize the attribution map. Defaults to False.
|
| 21 |
+
device (str, optional): The device to use for computation. Defaults to 'cpu'.
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
torch.Tensor: The attribution map computed as the gradient of the input tensor with respect to the output tensor.
|
| 25 |
+
"""
|
| 26 |
+
# maybe add model.train() at the beginning and model.eval() at the end of this function
|
| 27 |
+
|
| 28 |
+
# Set requires_grad attribute of tensor. Important for computing gradients
|
| 29 |
+
input_tensor.requires_grad = True
|
| 30 |
+
|
| 31 |
+
# Zero gradients
|
| 32 |
+
model.zero_grad()
|
| 33 |
+
|
| 34 |
+
# Forward pass
|
| 35 |
+
train_out = model(input_tensor) # training outputs (no inference outputs in train mode)
|
| 36 |
+
|
| 37 |
+
# train_out[1] = torch.Size([4, 3, 80, 80, 7]) HxWx(#anchorxC) cls (class probabilities)
|
| 38 |
+
# train_out[0] = torch.Size([4, 3, 160, 160, 7]) HxWx(#anchorx4) reg (location and scaling)
|
| 39 |
+
# train_out[2] = torch.Size([4, 3, 40, 40, 7]) HxWx(#anchorx1) obj (objectness score or confidence)
|
| 40 |
+
|
| 41 |
+
out_num = out_num - 1
|
| 42 |
+
|
| 43 |
+
if loss_func is None:
|
| 44 |
+
grad_wrt = train_out[out_num]
|
| 45 |
+
grad_wrt_outputs = torch.ones_like(grad_wrt)
|
| 46 |
+
else:
|
| 47 |
+
loss, loss_items = loss_func(train_out, targets.to(device), input_tensor, metric=metric) # loss scaled by batch_size
|
| 48 |
+
grad_wrt = loss
|
| 49 |
+
grad_wrt_outputs = None
|
| 50 |
+
# loss.backward(retain_graph=True, create_graph=True)
|
| 51 |
+
# gradients = input_tensor.grad
|
| 52 |
+
|
| 53 |
+
gradients = torch.autograd.grad(grad_wrt, input_tensor,
|
| 54 |
+
grad_outputs=grad_wrt_outputs,
|
| 55 |
+
retain_graph=True, create_graph=True)
|
| 56 |
+
|
| 57 |
+
# Convert gradients to numpy array
|
| 58 |
+
gradients = gradients[0].detach().cpu().numpy()
|
| 59 |
+
|
| 60 |
+
if norm:
|
| 61 |
+
# Take absolute values of gradients
|
| 62 |
+
gradients = np.absolute(gradients)
|
| 63 |
+
|
| 64 |
+
# Sum across color channels
|
| 65 |
+
attribution_map = np.sum(gradients, axis=0)
|
| 66 |
+
|
| 67 |
+
# Normalize attribution map
|
| 68 |
+
attribution_map /= np.max(attribution_map)
|
| 69 |
+
else:
|
| 70 |
+
# Sum across color channels
|
| 71 |
+
attribution_map = gradients
|
| 72 |
+
|
| 73 |
+
# Set model back to training mode
|
| 74 |
+
# model.train()
|
| 75 |
+
|
| 76 |
+
return torch.tensor(attribution_map, dtype=torch.float32, device=device)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def eval_plausibility(imgs, targets, attr_tensor, device):
|
| 80 |
+
"""
|
| 81 |
+
Evaluate the plausibility of an object detection prediction by computing the Intersection over Union (IoU) between
|
| 82 |
+
the predicted bounding box and the ground truth bounding box.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
im0 (numpy.ndarray): The input image.
|
| 86 |
+
targets (list): A list of targets, where each target is a list containing the class label and the ground truth
|
| 87 |
+
bounding box coordinates in the format [class_label, x1, y1, x2, y2].
|
| 88 |
+
attr (torch.Tensor): A tensor containing the normalized attribute values for the predicted
|
| 89 |
+
bounding box.
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
float: The total IoU score for all predicted bounding boxes.
|
| 93 |
+
"""
|
| 94 |
+
# if len(targets) == 0:
|
| 95 |
+
# return 0
|
| 96 |
+
# MIGHT NEED TO NORMALIZE OR TAKE ABS VAL OF ATTR
|
| 97 |
+
# ALSO MIGHT NORMALIZE FOR THE SIZE OF THE BBOX
|
| 98 |
+
eval_totals = 0
|
| 99 |
+
eval_individual_data = []
|
| 100 |
+
targets_ = [[targets[i] for i in range(len(targets)) if int(targets[i][0]) == j] for j in range(int(max(targets[:,0])))]
|
| 101 |
+
for i, im0 in enumerate(imgs):
|
| 102 |
+
if len(targets[i]) == 0:
|
| 103 |
+
eval_individual_data.append([torch.tensor(0).to(device),])
|
| 104 |
+
else:
|
| 105 |
+
IoU_list = []
|
| 106 |
+
xyxy_pred = targets[i][2:] # * torch.tensor([im0.shape[2], im0.shape[1], im0.shape[2], im0.shape[1]])
|
| 107 |
+
xyxy_center = corners_coords(xyxy_pred) * torch.tensor([im0.shape[1], im0.shape[2], im0.shape[1], im0.shape[2]])
|
| 108 |
+
c1, c2 = (int(xyxy_center[0]), int(xyxy_center[1])), (int(xyxy_center[2]), int(xyxy_center[3]))
|
| 109 |
+
attr = normalize_tensor(abs(attr_tensor[i].clone().detach()))
|
| 110 |
+
IoU_num = (torch.sum(attr[:,c1[1]:c2[1], c1[0]:c2[0]]))
|
| 111 |
+
IoU_denom = (torch.sum(attr))
|
| 112 |
+
IoU = IoU_num / IoU_denom
|
| 113 |
+
IoU_list.append(IoU)
|
| 114 |
+
eval_totals += torch.mean(torch.tensor(IoU_list))
|
| 115 |
+
eval_individual_data.append(IoU_list)
|
| 116 |
+
|
| 117 |
+
return torch.tensor(eval_totals).requires_grad_(True)
|
| 118 |
+
|
| 119 |
+
def corners_coords(center_xywh):
|
| 120 |
+
center_x, center_y, w, h = center_xywh
|
| 121 |
+
x = center_x - w/2
|
| 122 |
+
y = center_y - h/2
|
| 123 |
+
return torch.tensor([x, y, x+w, y+h])
|
| 124 |
+
|
Interface_Dependencies/plot_functs.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import matplotlib.pyplot as plt
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def VisualizeNumpyImageGrayscale(image_3d):
|
| 8 |
+
r"""Returns a 3D tensor as a grayscale normalized between 0 and 1 2D tensor.
|
| 9 |
+
"""
|
| 10 |
+
vmin = np.min(image_3d)
|
| 11 |
+
image_2d = image_3d - vmin
|
| 12 |
+
vmax = np.max(image_2d)
|
| 13 |
+
return (image_2d / vmax)
|
| 14 |
+
|
| 15 |
+
def normalize_tensor(image_3d):
|
| 16 |
+
r"""Returns a 3D tensor as a grayscale normalized between 0 and 1 2D tensor.
|
| 17 |
+
"""
|
| 18 |
+
vmin = torch.min(image_3d)
|
| 19 |
+
image_2d = image_3d - vmin
|
| 20 |
+
vmax = torch.max(image_2d)
|
| 21 |
+
return (image_2d / vmax)
|
| 22 |
+
|
| 23 |
+
def format_img(img_):
|
| 24 |
+
img_ = img_ # unnormalize
|
| 25 |
+
np_img = img_.numpy()
|
| 26 |
+
tp_img = np.transpose(np_img, (1, 2, 0))
|
| 27 |
+
return tp_img
|
| 28 |
+
|
| 29 |
+
def imshow(img, save_path=None):
|
| 30 |
+
img = img # unnormalize
|
| 31 |
+
try:
|
| 32 |
+
npimg = img.cpu().detach().numpy()
|
| 33 |
+
except:
|
| 34 |
+
npimg = img
|
| 35 |
+
tpimg = np.transpose(npimg, (1, 2, 0))
|
| 36 |
+
plt.imshow(tpimg)
|
| 37 |
+
if save_path != None:
|
| 38 |
+
plt.savefig(str(str(save_path) + ".png"))
|
| 39 |
+
#plt.show()
|
| 40 |
+
|
| 41 |
+
def imshow_img(img, imsave_path):
|
| 42 |
+
# works for tensors and numpy arrays
|
| 43 |
+
try:
|
| 44 |
+
npimg = VisualizeNumpyImageGrayscale(img.numpy())
|
| 45 |
+
except:
|
| 46 |
+
npimg = VisualizeNumpyImageGrayscale(img)
|
| 47 |
+
npimg = np.transpose(npimg, (2, 0, 1))
|
| 48 |
+
imshow(npimg, save_path=imsave_path)
|
| 49 |
+
print("Saving image as ", imsave_path)
|
| 50 |
+
|
| 51 |
+
def returnGrad(img, labels, model, compute_loss, loss_metric, augment=None, device = 'cpu'):
|
| 52 |
+
model.train()
|
| 53 |
+
model.to(device)
|
| 54 |
+
img = img.to(device)
|
| 55 |
+
img.requires_grad_(True)
|
| 56 |
+
labels.to(device).requires_grad_(True)
|
| 57 |
+
model.requires_grad_(True)
|
| 58 |
+
cuda = device.type != 'cpu'
|
| 59 |
+
scaler = amp.GradScaler(enabled=cuda)
|
| 60 |
+
pred = model(img)
|
| 61 |
+
# out, train_out = model(img, augment=augment) # inference and training outputs
|
| 62 |
+
loss, loss_items = compute_loss(pred, labels, metric=loss_metric)#[1][:3] # box, obj, cls
|
| 63 |
+
# loss = criterion(pred, torch.tensor([int(torch.max(pred[0], 0)[1])]).to(device))
|
| 64 |
+
# loss = torch.sum(loss).requires_grad_(True)
|
| 65 |
+
|
| 66 |
+
with torch.autograd.set_detect_anomaly(True):
|
| 67 |
+
scaler.scale(loss).backward(inputs=img)
|
| 68 |
+
# loss.backward()
|
| 69 |
+
|
| 70 |
+
# S_c = torch.max(pred[0].data, 0)[0]
|
| 71 |
+
Sc_dx = img.grad
|
| 72 |
+
model.eval()
|
| 73 |
+
Sc_dx = torch.tensor(Sc_dx, dtype=torch.float32)
|
| 74 |
+
return Sc_dx
|
| 75 |
+
|
| 76 |
+
def calculate_snr(img, attr, dB=True):
|
| 77 |
+
try:
|
| 78 |
+
img_np = img.detach().cpu().numpy()
|
| 79 |
+
attr_np = attr.detach().cpu().numpy()
|
| 80 |
+
except:
|
| 81 |
+
img_np = img
|
| 82 |
+
attr_np = attr
|
| 83 |
+
|
| 84 |
+
# Calculate the signal power
|
| 85 |
+
signal_power = np.mean(img_np**2)
|
| 86 |
+
|
| 87 |
+
# Calculate the noise power
|
| 88 |
+
noise_power = np.mean(attr_np**2)
|
| 89 |
+
|
| 90 |
+
if dB == True:
|
| 91 |
+
# Calculate SNR in dB
|
| 92 |
+
snr = 10 * np.log10(signal_power / noise_power)
|
| 93 |
+
else:
|
| 94 |
+
# Calculate SNR
|
| 95 |
+
snr = signal_power / noise_power
|
| 96 |
+
|
| 97 |
+
return snr
|
Interface_Dependencies/run_methods.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import os
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import argparse
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
sys.path.append('Interface_Dependencies')
|
| 8 |
+
sys.path.append('Engineering-Clinic-Emerging-AI-Design-Interface/Interface_Dependencies')
|
| 9 |
+
sys.path.append('Engineering-Clinic-Emerging-AI-Design-Interface/yolov7-main')
|
| 10 |
+
sys.path.append('./') # to run '$ python *.py' files in subdirectories
|
| 11 |
+
|
| 12 |
+
from ourDetect import detect, generate_feature_maps # used for output generation
|
| 13 |
+
from utils.general import strip_optimizer # used for opt creation
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def correct_video(video):
|
| 17 |
+
"""
|
| 18 |
+
Takes a video file of any type and turns it into a gradio compatible .mp4/264 video
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
video (str): The file path of the input video
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
str: The file path of the output video
|
| 25 |
+
"""
|
| 26 |
+
os.system("ffmpeg -i {file_str} -y -vcodec libx264 -acodec aac {file_str}.mp4".format(file_str = video))
|
| 27 |
+
return video+".mp4"
|
| 28 |
+
|
| 29 |
+
def run_all(source_type, im, vid, src, inf_size=640, obj_conf_thr=0.25, iou_thr=0.45, conv_layer=1, agnostic_nms=False, outputNum=1, is_stream=False, norm=False):
|
| 30 |
+
if is_stream:
|
| 31 |
+
return run_image(image=im,src=src,inf_size=inf_size,obj_conf_thr=obj_conf_thr,iou_thr=iou_thr,conv_layer=conv_layer,agnostic_nms=agnostic_nms,outputNum=outputNum,is_stream=is_stream,norm=norm)
|
| 32 |
+
elif source_type == "Image":
|
| 33 |
+
return run_image(image=im,src=src,inf_size=inf_size,obj_conf_thr=obj_conf_thr,iou_thr=iou_thr,conv_layer=conv_layer,agnostic_nms=agnostic_nms,outputNum=outputNum,is_stream=is_stream,norm=norm)
|
| 34 |
+
elif source_type == "Video":
|
| 35 |
+
return run_video(video=vid,src=src,inf_size=inf_size,obj_conf_thr=obj_conf_thr,iou_thr=iou_thr,agnostic_nms=agnostic_nms,is_stream=is_stream,outputNum=outputNum)
|
| 36 |
+
|
| 37 |
+
def run_image(image, src, inf_size, obj_conf_thr, iou_thr, conv_layer, agnostic_nms, outputNum, is_stream, norm):
|
| 38 |
+
"""
|
| 39 |
+
Takes an image (from upload or webcam), and outputs the yolo7 boxed output and the convolution layers
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
image (str/PIL): The file path or PIL of the the input image.
|
| 43 |
+
src (str): The source of the input image, either upload or webcam
|
| 44 |
+
inf_size (int): The size of the inference
|
| 45 |
+
obj_conf_thr (float): The object confidence threshold
|
| 46 |
+
iou_thr (float): The intersection of union number
|
| 47 |
+
conv_layer (int): The number of the convolutional layer to show
|
| 48 |
+
agnostic_nms (bool): The agnostic nms boolean
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
List[str]: A list of strings, where each string is a file path to an output image.
|
| 52 |
+
"""
|
| 53 |
+
obj_conf_thr = float(obj_conf_thr)
|
| 54 |
+
iou_thr = float(iou_thr)
|
| 55 |
+
agnostic_nms = bool(agnostic_nms)
|
| 56 |
+
if src == "Webcam":
|
| 57 |
+
image.save('Temp.jpg') # Convert PIL image to OpenCV format if needed
|
| 58 |
+
image = 'Temp.jpg'
|
| 59 |
+
if not is_stream:
|
| 60 |
+
random = Image.open(image)
|
| 61 |
+
new_dir = generate_feature_maps(random, conv_layer)
|
| 62 |
+
if agnostic_nms:
|
| 63 |
+
agnostic_nms = 'store_true'
|
| 64 |
+
else:
|
| 65 |
+
agnostic_nms = 'store_false'
|
| 66 |
+
parser = argparse.ArgumentParser()
|
| 67 |
+
parser.add_argument('--weights', nargs='+', type=str, default='yolov7.pt', help='model.pt path(s)')
|
| 68 |
+
parser.add_argument('--source', type=str, default=image, help='source') # file/folder, 0 for webcam
|
| 69 |
+
parser.add_argument('--img-size', type=int, default=inf_size, help='inference size (pixels)')
|
| 70 |
+
parser.add_argument('--conf-thres', type=float, default=obj_conf_thr, help='object confidence threshold')
|
| 71 |
+
parser.add_argument('--iou-thres', type=float, default=iou_thr, help='IOU threshold for NMS')
|
| 72 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
| 73 |
+
parser.add_argument('--view-img', action='store_true', help='display results')
|
| 74 |
+
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
|
| 75 |
+
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
|
| 76 |
+
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
|
| 77 |
+
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
|
| 78 |
+
parser.add_argument('--agnostic-nms', action=agnostic_nms, help='class-agnostic NMS')
|
| 79 |
+
parser.add_argument('--augment', action='store_true', help='augmented inference')
|
| 80 |
+
parser.add_argument('--update', action='store_true', help='update all models')
|
| 81 |
+
parser.add_argument('--project', default='outputs/runs/detect', help='save results to project/name')
|
| 82 |
+
parser.add_argument('--name', default='exp', help='save results to project/name')
|
| 83 |
+
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
|
| 84 |
+
parser.add_argument('--no-trace', action='store_true', help='don`t trace model')
|
| 85 |
+
opt = parser.parse_args()
|
| 86 |
+
opt.no_trace = True
|
| 87 |
+
print(opt)
|
| 88 |
+
#check_requirements(exclude=('pycocotools', 'thop'))
|
| 89 |
+
if opt.update: # update all models (to fix SourceChangeWarning)
|
| 90 |
+
for opt.weights in ['yolov7.pt']:
|
| 91 |
+
save_dir, smooth_dir, labels, formatted_time = detect(opt, outputNum=outputNum, is_stream=is_stream)
|
| 92 |
+
strip_optimizer(opt.weights)
|
| 93 |
+
else:
|
| 94 |
+
save_dir, smooth_dir, labels, formatted_time = detect(opt, outputNum=outputNum, is_stream=is_stream)
|
| 95 |
+
if is_stream:
|
| 96 |
+
return [save_dir, None, None, None, None, None]
|
| 97 |
+
return [save_dir, new_dir, smooth_dir, labels, formatted_time, None] # added info
|
| 98 |
+
|
| 99 |
+
def run_video(video, src, inf_size, obj_conf_thr, iou_thr, agnostic_nms, is_stream, outputNum=1, norm=False):
|
| 100 |
+
"""
|
| 101 |
+
Takes a video (from upload or webcam), and outputs the yolo7 boxed output
|
| 102 |
+
|
| 103 |
+
Args:
|
| 104 |
+
video (str): The file path of the input video
|
| 105 |
+
src (str): The source of the input video, either upload or webcam
|
| 106 |
+
inf_size (int): The size of the inference
|
| 107 |
+
obj_conf_thr (float): The object confidence threshold
|
| 108 |
+
iou_thr (float): The intersection of union number
|
| 109 |
+
agnostic_nms (bool): The agnostic nms boolean
|
| 110 |
+
|
| 111 |
+
Returns:
|
| 112 |
+
str: The file path of the output video
|
| 113 |
+
"""
|
| 114 |
+
obj_conf_thr = float(obj_conf_thr)
|
| 115 |
+
iou_thr = float(iou_thr)
|
| 116 |
+
agnostic_nms = bool(agnostic_nms)
|
| 117 |
+
if src == "Webcam":
|
| 118 |
+
if is_stream:
|
| 119 |
+
video = "0"
|
| 120 |
+
else:
|
| 121 |
+
video = correct_video(video)
|
| 122 |
+
if agnostic_nms:
|
| 123 |
+
agnostic_nms = 'store_true'
|
| 124 |
+
else:
|
| 125 |
+
agnostic_nms = 'store_false'
|
| 126 |
+
parser = argparse.ArgumentParser()
|
| 127 |
+
parser.add_argument('--weights', nargs='+', type=str, default='yolov7.pt', help='model.pt path(s)')
|
| 128 |
+
parser.add_argument('--source', type=str, default=video, help='source') # file/folder, 0 for webcam
|
| 129 |
+
parser.add_argument('--img-size', type=int, default=inf_size, help='inference size (pixels)')
|
| 130 |
+
parser.add_argument('--conf-thres', type=float, default=obj_conf_thr, help='object confidence threshold')
|
| 131 |
+
parser.add_argument('--iou-thres', type=float, default=iou_thr, help='IOU threshold for NMS')
|
| 132 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
| 133 |
+
parser.add_argument('--view-img', action='store_true', help='display results')
|
| 134 |
+
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
|
| 135 |
+
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
|
| 136 |
+
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
|
| 137 |
+
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
|
| 138 |
+
parser.add_argument('--agnostic-nms', action=agnostic_nms, help='class-agnostic NMS')
|
| 139 |
+
parser.add_argument('--augment', action='store_true', help='augmented inference')
|
| 140 |
+
parser.add_argument('--update', action='store_true', help='update all models')
|
| 141 |
+
parser.add_argument('--project', default='outputs/runs/detect', help='save results to project/name')
|
| 142 |
+
parser.add_argument('--name', default='exp', help='save results to project/name')
|
| 143 |
+
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
|
| 144 |
+
parser.add_argument('--no-trace', action='store_true', help='don`t trace model')
|
| 145 |
+
opt = parser.parse_args()
|
| 146 |
+
opt.batch_size = 1
|
| 147 |
+
print(opt)
|
| 148 |
+
#check_requirements(exclude=('pycocotools', 'thop'))
|
| 149 |
+
with torch.no_grad():
|
| 150 |
+
if opt.update: # update all models (to fix SourceChangeWarning)
|
| 151 |
+
for opt.weights in ['yolov7.pt']:
|
| 152 |
+
save_dir = detect(opt, outputNum=outputNum, is_stream=is_stream, norm=norm)
|
| 153 |
+
strip_optimizer(opt.weights)
|
| 154 |
+
else:
|
| 155 |
+
save_dir = detect(opt, outputNum=outputNum, is_stream=is_stream, norm=norm)
|
| 156 |
+
return [None, None, None, None, None, save_dir]
|
Interface_Dependencies/smooth_grad.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Original Implementation of Smooth_grad **NOT USED**
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
def generate_vanilla_grad(model, input_tensor, outputNum, targets=None, norm=False, device='cpu'):
|
| 7 |
+
"""
|
| 8 |
+
Generates an attribution map using vanilla gradient method.
|
| 9 |
+
|
| 10 |
+
Args:
|
| 11 |
+
model (torch.nn.Module): The PyTorch model to generate the attribution map for.
|
| 12 |
+
input_tensor (torch.Tensor): The input tensor to the model.
|
| 13 |
+
norm (bool, optional): Whether to normalize the attribution map. Defaults to False.
|
| 14 |
+
device (str, optional): The device to use for the computation. Defaults to 'cpu'.
|
| 15 |
+
|
| 16 |
+
Returns:
|
| 17 |
+
numpy.ndarray: The attribution map.
|
| 18 |
+
"""
|
| 19 |
+
# Set requires_grad attribute of tensor. Important for computing gradients
|
| 20 |
+
input_tensor.requires_grad = True
|
| 21 |
+
|
| 22 |
+
# Forward pass
|
| 23 |
+
train_out = model(input_tensor) # training outputs (no inference outputs in train mode)
|
| 24 |
+
|
| 25 |
+
num_classes = 2
|
| 26 |
+
|
| 27 |
+
# Zero gradients
|
| 28 |
+
model.zero_grad()
|
| 29 |
+
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
# train_out[1] = torch.Size([4, 3, 80, 80, 7]) #anchorxC) cls (class probabilities)
|
| 33 |
+
# train_out[0] = torch.Size([4, 3, 160, 160, 7]) #anchorx4) reg (location and scaling)
|
| 34 |
+
# train_out[2] = torch.Size([4, 3, 40, 40, 7]) #anchorx1) obj (objectness score or confidence)
|
| 35 |
+
|
| 36 |
+
gradients = torch.autograd.grad(train_out[outputNum-1].requires_grad_(True), input_tensor,
|
| 37 |
+
grad_outputs=torch.ones_like(train_out[outputNum-1]).requires_grad_(True),
|
| 38 |
+
retain_graph=True, create_graph=True)
|
| 39 |
+
|
| 40 |
+
# Convert gradients to numpy array
|
| 41 |
+
gradients = gradients[0].detach().cpu().numpy()
|
| 42 |
+
|
| 43 |
+
if norm:
|
| 44 |
+
# Take absolute values of gradients
|
| 45 |
+
gradients = np.absolute(gradients)
|
| 46 |
+
|
| 47 |
+
# Sum across color channels
|
| 48 |
+
attribution_map = np.sum(gradients, axis=0)
|
| 49 |
+
|
| 50 |
+
# Normalize attribution map
|
| 51 |
+
attribution_map /= np.max(attribution_map)
|
| 52 |
+
else:
|
| 53 |
+
# Sum across color channels
|
| 54 |
+
attribution_map = gradients
|
| 55 |
+
|
| 56 |
+
return torch.tensor(attribution_map, dtype=torch.float32, device=device)
|
ffmpeg.7z
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9b257499590550039b995ad1eb284ca5e5696c298bcd5cfd0aea325317ba62c1
|
| 3 |
+
size 40956361
|
individual_work/asien/asien_interface.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import io
|
| 4 |
+
import subprocess
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# Define a function to handle the image input
|
| 8 |
+
def detect_objects(input_image):
|
| 9 |
+
# Save the uploaded image temporarily inside the "inference" folder
|
| 10 |
+
print(input_image)
|
| 11 |
+
|
| 12 |
+
# Run your YOLOv7 detection script
|
| 13 |
+
subprocess.run(["python", r"yolov7-main\detect.py", "--source", input_image, "--project", "individual_work\\asien\\run_images", "--name", "exp"])
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# Load the output image from your detection
|
| 17 |
+
output_image = Image.open("individual_work\\asien\\run_images\\exp\\image.png")
|
| 18 |
+
return output_image
|
| 19 |
+
|
| 20 |
+
# Define the Gradio interface with a run button
|
| 21 |
+
iface = gr.Interface(
|
| 22 |
+
fn=detect_objects,
|
| 23 |
+
inputs=gr.inputs.Image(type="filepath", source="upload"),
|
| 24 |
+
outputs=gr.outputs.Image(type="pil"),
|
| 25 |
+
live=False # Set live=False to disable real-time updates
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Launch the Gradio interface
|
| 29 |
+
iface.launch(share=True)
|
individual_work/braedon/braedon_settings.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import argparse
|
| 3 |
+
import sys
|
| 4 |
+
sys.path.append('./')
|
| 5 |
+
sys.path.append('yolov7-main')
|
| 6 |
+
|
| 7 |
+
from ourDetect import detect
|
| 8 |
+
import torch
|
| 9 |
+
from utils.general import strip_optimizer
|
| 10 |
+
|
| 11 |
+
# Define a function to run YOLOv7 with the provided settings
|
| 12 |
+
def run(weights, conf_thres, iou_thres, agnostic_nms, source):
|
| 13 |
+
weights = weights.strip() # Remove any leading/trailing spaces
|
| 14 |
+
conf_thres = float(conf_thres)
|
| 15 |
+
iou_thres = float(iou_thres)
|
| 16 |
+
agnostic_nms = bool(agnostic_nms)
|
| 17 |
+
source = source.strip()
|
| 18 |
+
|
| 19 |
+
parser = argparse.ArgumentParser()
|
| 20 |
+
parser.add_argument('--weights', nargs='+', type=str, default=[weights], help='model.pt path(s)')
|
| 21 |
+
parser.add_argument('--source', type=str, default=source, help='source')
|
| 22 |
+
parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
|
| 23 |
+
parser.add_argument('--conf-thres', type=float, default=conf_thres, help='object confidence threshold')
|
| 24 |
+
parser.add_argument('--iou-thres', type=float, default=iou_thres, help='IOU threshold for NMS')
|
| 25 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
| 26 |
+
parser.add_argument('--view-img', action='store_true', help='display results')
|
| 27 |
+
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
|
| 28 |
+
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
|
| 29 |
+
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
|
| 30 |
+
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
|
| 31 |
+
parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
|
| 32 |
+
parser.add_argument('--augment', action='store_true', help='augmented inference')
|
| 33 |
+
parser.add_argument('--update', action='store_true', help='update all models')
|
| 34 |
+
parser.add_argument('--project', default='runs/detect', help='save results to project/name')
|
| 35 |
+
parser.add_argument('--name', default='exp', help='save results to project/name')
|
| 36 |
+
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
|
| 37 |
+
parser.add_argument('--no-trace', action='store_true', help='don`t trace model')
|
| 38 |
+
opt = parser.parse_args()
|
| 39 |
+
print(opt)
|
| 40 |
+
|
| 41 |
+
with torch.no_grad():
|
| 42 |
+
if opt.update:
|
| 43 |
+
for opt.weights in weights:
|
| 44 |
+
save_dir = detect(opt)
|
| 45 |
+
strip_optimizer(opt.weights)
|
| 46 |
+
else:
|
| 47 |
+
save_dir = detect(opt)
|
| 48 |
+
return save_dir + "\zidane.jpg"
|
| 49 |
+
|
| 50 |
+
# Define the Gradio settings block
|
| 51 |
+
settings_block = [
|
| 52 |
+
"text", # "text" component for Weights (Path)
|
| 53 |
+
"number", # "number" component for Confidence Threshold
|
| 54 |
+
"number", # "number" component for IoU Threshold
|
| 55 |
+
"checkbox", # "checkbox" component for Agnostic NMS
|
| 56 |
+
"text" # "text" component for Source (Path)
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
# Create a Gradio interface for YOLOv7 settings
|
| 60 |
+
iface = gr.Interface(
|
| 61 |
+
fn=run,
|
| 62 |
+
inputs=settings_block,
|
| 63 |
+
outputs="text", # Use "text" directly as the output type
|
| 64 |
+
live=True
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
if __name__ == "__main__":
|
| 69 |
+
iface.launch()
|
individual_work/ike/olddetect.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import time
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import cv2
|
| 6 |
+
import torch
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import torch.backends.cudnn as cudnn
|
| 9 |
+
import numpy as np
|
| 10 |
+
from numpy import random
|
| 11 |
+
|
| 12 |
+
import sys
|
| 13 |
+
sys.path.append('./')
|
| 14 |
+
sys.path.append('yolov7-main')
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
from models.experimental import attempt_load
|
| 18 |
+
from utils.datasets import LoadStreams, LoadImages
|
| 19 |
+
from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
|
| 20 |
+
scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
|
| 21 |
+
from utils.plots import plot_one_box
|
| 22 |
+
from utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def detect(input_image=None, input_Webcam=None):
|
| 26 |
+
source_img = None
|
| 27 |
+
save_txt = False
|
| 28 |
+
trace = False
|
| 29 |
+
# source = opt.source
|
| 30 |
+
if input_image:
|
| 31 |
+
source_img = np.array(input_image) # Convert PIL image to OpenCV format if needed
|
| 32 |
+
|
| 33 |
+
if input_Webcam:
|
| 34 |
+
source_img = np.array(input_Webcam) # Convert PIL image to OpenCV format if needed
|
| 35 |
+
|
| 36 |
+
if source_img is not None:
|
| 37 |
+
#source = cv2.cvtColor(cv2.imread(source), cv2.COLOR_RGB2BGR)
|
| 38 |
+
|
| 39 |
+
img = cv2.imdecode(np.fromstring(source_img(), np.uint8), 1)
|
| 40 |
+
|
| 41 |
+
# Convert image to YSBCR color space
|
| 42 |
+
source = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)
|
| 43 |
+
else:
|
| 44 |
+
source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, not opt.no_trace
|
| 45 |
+
|
| 46 |
+
# save_img = not opt.nosave and not source.endswith('.txt') # save inference images
|
| 47 |
+
# webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
|
| 48 |
+
# ('rtsp://', 'rtmp://', 'http://', 'https://'))
|
| 49 |
+
|
| 50 |
+
# Directories
|
| 51 |
+
save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run
|
| 52 |
+
if not opt.nosave:
|
| 53 |
+
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
| 54 |
+
|
| 55 |
+
# Initialize
|
| 56 |
+
set_logging()
|
| 57 |
+
device = select_device(opt.device)
|
| 58 |
+
half = device.type != 'cpu' # half precision only supported on CUDA
|
| 59 |
+
|
| 60 |
+
# Load model
|
| 61 |
+
weights = 'yolov7.pt'
|
| 62 |
+
imgsz = 640
|
| 63 |
+
model = attempt_load(weights, map_location=device) # load FP32 model
|
| 64 |
+
stride = int(model.stride.max()) # model stride
|
| 65 |
+
imgsz = check_img_size(imgsz, s=stride) # check img_size
|
| 66 |
+
|
| 67 |
+
# if trace:
|
| 68 |
+
# model = TracedModel(model, device, opt.img_size)
|
| 69 |
+
|
| 70 |
+
if half:
|
| 71 |
+
model.half() # to FP16
|
| 72 |
+
|
| 73 |
+
# Second-stage classifier
|
| 74 |
+
classify = False
|
| 75 |
+
if classify:
|
| 76 |
+
modelc = load_classifier(name='resnet101', n=2) # initialize
|
| 77 |
+
modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
|
| 78 |
+
|
| 79 |
+
# Set Dataloader
|
| 80 |
+
dataset = LoadImages(source, img_size=imgsz, stride=stride)
|
| 81 |
+
view_img = check_imshow()
|
| 82 |
+
cudnn.benchmark = True
|
| 83 |
+
# if webcam:
|
| 84 |
+
# view_img = check_imshow()
|
| 85 |
+
# cudnn.benchmark = True # set True to speed up constant image size inference
|
| 86 |
+
# dataset = LoadStreams(source, img_size=imgsz, stride=stride)
|
| 87 |
+
# else:
|
| 88 |
+
# dataset = LoadImages(source, img_size=imgsz, stride=stride)
|
| 89 |
+
|
| 90 |
+
# Get names and colors
|
| 91 |
+
names = model.module.names if hasattr(model, 'module') else model.names
|
| 92 |
+
colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
|
| 93 |
+
|
| 94 |
+
# Run inference
|
| 95 |
+
if device.type != 'cpu':
|
| 96 |
+
model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
|
| 97 |
+
old_img_w = old_img_h = imgsz
|
| 98 |
+
old_img_b = 1
|
| 99 |
+
|
| 100 |
+
t0 = time.time()
|
| 101 |
+
for path, img, im0s, vid_cap in dataset:
|
| 102 |
+
img = torch.from_numpy(img).to(device)
|
| 103 |
+
img = img.half() if half else img.float() # uint8 to fp16/32
|
| 104 |
+
img /= 255.0 # 0 - 255 to 0.0 - 1.0
|
| 105 |
+
if img.ndimension() == 3:
|
| 106 |
+
img = img.unsqueeze(0)
|
| 107 |
+
|
| 108 |
+
# Warmup
|
| 109 |
+
if device.type != 'cpu' and (old_img_b != img.shape[0] or old_img_h != img.shape[2] or old_img_w != img.shape[3]):
|
| 110 |
+
old_img_b = img.shape[0]
|
| 111 |
+
old_img_h = img.shape[2]
|
| 112 |
+
old_img_w = img.shape[3]
|
| 113 |
+
for i in range(3):
|
| 114 |
+
model(img, augment=opt.augment)[0]
|
| 115 |
+
|
| 116 |
+
# Inference
|
| 117 |
+
t1 = time_synchronized()
|
| 118 |
+
with torch.no_grad(): # Calculating gradients would cause a GPU memory leak
|
| 119 |
+
pred = model(img, augment=opt.augment)[0]
|
| 120 |
+
t2 = time_synchronized()
|
| 121 |
+
|
| 122 |
+
# Apply NMS
|
| 123 |
+
pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
|
| 124 |
+
t3 = time_synchronized()
|
| 125 |
+
|
| 126 |
+
# Apply Classifier
|
| 127 |
+
if classify:
|
| 128 |
+
pred = apply_classifier(pred, modelc, img, im0s)
|
| 129 |
+
|
| 130 |
+
# Process detections
|
| 131 |
+
for i, det in enumerate(pred): # detections per image
|
| 132 |
+
if input_Webcam: # batch_size >= 1
|
| 133 |
+
p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
|
| 134 |
+
else:
|
| 135 |
+
p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
|
| 136 |
+
|
| 137 |
+
p = Path(p) # to Path
|
| 138 |
+
save_path = str(save_dir / p.name) # img.jpg
|
| 139 |
+
# txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
|
| 140 |
+
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
|
| 141 |
+
if len(det):
|
| 142 |
+
# Rescale boxes from img_size to im0 size
|
| 143 |
+
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
|
| 144 |
+
|
| 145 |
+
# Print results
|
| 146 |
+
for c in det[:, -1].unique():
|
| 147 |
+
n = (det[:, -1] == c).sum() # detections per class
|
| 148 |
+
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
|
| 149 |
+
|
| 150 |
+
# Write results
|
| 151 |
+
for *xyxy, conf, cls in reversed(det):
|
| 152 |
+
# if save_txt: # Write to file
|
| 153 |
+
# xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
|
| 154 |
+
# line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
|
| 155 |
+
# with open(txt_path + '.txt', 'a') as f:
|
| 156 |
+
# f.write(('%g ' * len(line)).rstrip() % line + '\n')
|
| 157 |
+
|
| 158 |
+
if source or view_img: # Add bbox to image
|
| 159 |
+
label = f'{names[int(cls)]} {conf:.2f}'
|
| 160 |
+
plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=1)
|
| 161 |
+
|
| 162 |
+
# Print time (inference + NMS)
|
| 163 |
+
print(f'{s}Done. ({(1E3 * (t2 - t1)):.1f}ms) Inference, ({(1E3 * (t3 - t2)):.1f}ms) NMS')
|
| 164 |
+
|
| 165 |
+
# Stream results
|
| 166 |
+
if view_img:
|
| 167 |
+
cv2.imshow(str(p), im0)
|
| 168 |
+
cv2.waitKey(1) # 1 millisecond
|
| 169 |
+
|
| 170 |
+
# Save results (image with detections)
|
| 171 |
+
if source:
|
| 172 |
+
if dataset.mode == 'image':
|
| 173 |
+
if not opt.nosave:
|
| 174 |
+
cv2.imwrite(save_path, im0)
|
| 175 |
+
print(f" The image with the result is saved in: {save_path}")
|
| 176 |
+
else: # 'video' or 'stream'
|
| 177 |
+
if vid_path != save_path: # new video
|
| 178 |
+
vid_path = save_path
|
| 179 |
+
if isinstance(vid_writer, cv2.VideoWriter):
|
| 180 |
+
vid_writer.release() # release previous video writer
|
| 181 |
+
if vid_cap: # video
|
| 182 |
+
fps = vid_cap.get(cv2.CAP_PROP_FPS)
|
| 183 |
+
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 184 |
+
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 185 |
+
else: # stream
|
| 186 |
+
fps, w, h = 30, im0.shape[1], im0.shape[0]
|
| 187 |
+
save_path += '.mp4'
|
| 188 |
+
vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
|
| 189 |
+
vid_writer.write(im0)
|
| 190 |
+
|
| 191 |
+
# if source:
|
| 192 |
+
# s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
|
| 193 |
+
# #print(f"Results saved to {save_dir}{s}")
|
| 194 |
+
|
| 195 |
+
print(f'Done. ({time.time() - t0:.3f}s)')
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
if __name__ == '__main__':
|
| 199 |
+
parser = argparse.ArgumentParser()
|
| 200 |
+
parser.add_argument('--weights', nargs='+', type=str, default='yolov7.pt', help='model.pt path(s)')
|
| 201 |
+
parser.add_argument('--source', type=str, default='inference/images', help='source') # file/folder, 0 for webcam
|
| 202 |
+
parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
|
| 203 |
+
parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
|
| 204 |
+
parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
|
| 205 |
+
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
| 206 |
+
parser.add_argument('--view-img', action='store_true', help='display results')
|
| 207 |
+
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
|
| 208 |
+
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
|
| 209 |
+
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
|
| 210 |
+
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
|
| 211 |
+
parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
|
| 212 |
+
parser.add_argument('--augment', action='store_true', help='augmented inference')
|
| 213 |
+
parser.add_argument('--update', action='store_true', help='update all models')
|
| 214 |
+
parser.add_argument('--project', default='runs/detect', help='save results to project/name')
|
| 215 |
+
parser.add_argument('--name', default='exp', help='save results to project/name')
|
| 216 |
+
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
|
| 217 |
+
parser.add_argument('--no-trace', action='store_true', help='don`t trace model')
|
| 218 |
+
opt = parser.parse_args()
|
| 219 |
+
print(opt)
|
| 220 |
+
#check_requirements(exclude=('pycocotools', 'thop'))
|
| 221 |
+
|
| 222 |
+
with torch.no_grad():
|
| 223 |
+
if opt.update: # update all models (to fix SourceChangeWarning)
|
| 224 |
+
for opt.weights in ['yolov7.pt']:
|
| 225 |
+
detect()
|
| 226 |
+
strip_optimizer(opt.weights)
|
| 227 |
+
else:
|
| 228 |
+
detect()
|
| 229 |
+
import gradio as gr
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
input_image = gr.inputs.Image(type='pil', label="Original Image", source="upload", optional=True)
|
| 234 |
+
input_Webcam = gr.inputs.Image(type='pil', label="Original Image", source="webcam", optional=True)
|
| 235 |
+
inputs = [input_image, input_Webcam]
|
| 236 |
+
outputs = gr.outputs.Image(type="pil", label="Output Image")
|
| 237 |
+
title = "Object detection with Yolov7"
|
| 238 |
+
|
| 239 |
+
iface = gr.Interface(detect(input_image, input_Webcam),
|
| 240 |
+
inputs = input_image,
|
| 241 |
+
outputs = Image,
|
| 242 |
+
title="Classification using YOLOV7",
|
| 243 |
+
live=True,
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
iface.launch()
|
| 247 |
+
|
| 248 |
+
|
outputs/runs/detect/exp/layers/layer0.jpg
ADDED
|
references/error_fixes/online_help.md
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
https://stackoverflow.com/questions/75103127/getting-notimplementederror-could-not-run-torchvisionnms-with-arguments-fr#:~:text=The%20full%20error%3A,(if%20using%20custom%20build).
|
| 2 |
+
|
| 3 |
+
https://github.com/WongKinYiu/yolov7/issues/1205
|
references/gradio_exs/exstream.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
def flip(im):
|
| 5 |
+
return np.flipud(im)
|
| 6 |
+
|
| 7 |
+
demo = gr.Interface(
|
| 8 |
+
flip,
|
| 9 |
+
gr.Image(source='webcam', streaming=True),
|
| 10 |
+
"image",
|
| 11 |
+
live=True
|
| 12 |
+
)
|
| 13 |
+
demo.launch()
|