Spaces:
Runtime error
Runtime error
Create detection.py
Browse files- detection.py +76 -0
detection.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import cv2
|
| 3 |
+
import torch
|
| 4 |
+
from argparse import ArgumentParser
|
| 5 |
+
import os
|
| 6 |
+
import utils_
|
| 7 |
+
|
| 8 |
+
def resize(image, size=640):
|
| 9 |
+
height, width, channels = image.shape
|
| 10 |
+
|
| 11 |
+
if height > width:
|
| 12 |
+
new_height = size
|
| 13 |
+
new_width = round((width / height) * size)
|
| 14 |
+
else:
|
| 15 |
+
new_width = size
|
| 16 |
+
new_height = round((height / width) * size)
|
| 17 |
+
image = cv2.resize(image, (new_width, new_height))
|
| 18 |
+
return image
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def read_image_with_resize(file, size=640):
|
| 22 |
+
img = cv2.imread(file)
|
| 23 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 24 |
+
img = resize(img, size=size)
|
| 25 |
+
return img
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def add_rect(image, xmin, ymin, xmax, ymax, color=(255, 0, 0), thickness=2):
|
| 29 |
+
cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, thickness)
|
| 30 |
+
return image
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# Model
|
| 34 |
+
model = torch.hub.load(
|
| 35 |
+
"ultralytics/yolov5",
|
| 36 |
+
"custom",
|
| 37 |
+
path="./out/detection.pt",
|
| 38 |
+
force_reload=True,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def round_all(array):
|
| 43 |
+
return [round(elm) for elm in array]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def detect(image: np.ndarray):
|
| 47 |
+
# Inference
|
| 48 |
+
results = model(image)
|
| 49 |
+
results = results.pandas().xyxy
|
| 50 |
+
res = []
|
| 51 |
+
for pos in results[0].iterrows():
|
| 52 |
+
tmp = round_all(pos[1][:4].tolist())
|
| 53 |
+
res.append(tmp)
|
| 54 |
+
|
| 55 |
+
return res
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
if __name__ == "__main__":
|
| 59 |
+
parser = ArgumentParser()
|
| 60 |
+
parser.add_argument(
|
| 61 |
+
"--image",
|
| 62 |
+
default=None,
|
| 63 |
+
type=str,
|
| 64 |
+
help="path to image on which prediction will be made",
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
args = parser.parse_args()
|
| 68 |
+
|
| 69 |
+
assert os.path.exists(args.image), f"given path {args.image} does not exists"
|
| 70 |
+
|
| 71 |
+
im = read_image_with_resize()(args.image)
|
| 72 |
+
results = detect(im)
|
| 73 |
+
|
| 74 |
+
for pos in results:
|
| 75 |
+
im = add_rect(im, *pos)
|
| 76 |
+
cv2.imwrite("result.jpg", im)
|