Compare commits
No commits in common. "97463c6b35edc9632ced33609eef672015b382da" and "b6a8209eb4d938669394d2549ebbcfd2d37ad1e3" have entirely different histories.
97463c6b35
...
b6a8209eb4
2
.gitignore
vendored
2
.gitignore
vendored
@ -252,4 +252,4 @@ cython_debug/
|
|||||||
#.idea/
|
#.idea/
|
||||||
|
|
||||||
# End of https://www.toptal.com/developers/gitignore/api/python,pycharm+all
|
# End of https://www.toptal.com/developers/gitignore/api/python,pycharm+all
|
||||||
yolov8s.pt
|
yolov5s.pt
|
17
main.py
17
main.py
@ -2,7 +2,9 @@ import os
|
|||||||
import sys
|
import sys
|
||||||
|
|
||||||
import cv2 as cv
|
import cv2 as cv
|
||||||
|
import numpy as np
|
||||||
import requests
|
import requests
|
||||||
|
import torch
|
||||||
|
|
||||||
import imageWorking
|
import imageWorking
|
||||||
import neuralNetwork
|
import neuralNetwork
|
||||||
@ -23,19 +25,18 @@ def analyze_file(uid: str, image_path: str) -> None:
|
|||||||
raise Exception(f'Онтология с uid {uid} не существует')
|
raise Exception(f'Онтология с uid {uid} не существует')
|
||||||
if not os.path.isfile(image_path):
|
if not os.path.isfile(image_path):
|
||||||
raise Exception(f'Изображение {image_path} не существует')
|
raise Exception(f'Изображение {image_path} не существует')
|
||||||
model = neuralNetwork.load_model()
|
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
|
||||||
|
model.names = neuralNetwork.rename_entity(model.names)
|
||||||
|
|
||||||
# Распознавание изображения.
|
# Распознавание изображения.
|
||||||
results = model.predict(source=imageWorking.get_image_as_array(image_path))
|
results = model(imageWorking.get_image_as_array(image_path))
|
||||||
|
|
||||||
# Создание аксиом онтологии на основе результатов распознавания.
|
# Создание аксиом онтологии на основе результатов распознавания.
|
||||||
object_properties = list()
|
object_properties = list()
|
||||||
data_properties = list()
|
data_properties = list()
|
||||||
for res in results:
|
for i, res in enumerate(results.pred):
|
||||||
classes = res.boxes.cls.int()
|
results_ndarray = np.array(res)
|
||||||
conf = res.boxes.conf
|
request = ontologyWorking.get_request_data(model.names, results_ndarray)
|
||||||
boxes = res.boxes.xywh
|
|
||||||
request = ontologyWorking.get_request_data(model.names, classes, conf, boxes)
|
|
||||||
object_properties += request[0]
|
object_properties += request[0]
|
||||||
data_properties += request[1]
|
data_properties += request[1]
|
||||||
|
|
||||||
@ -75,7 +76,7 @@ def analyze_file(uid: str, image_path: str) -> None:
|
|||||||
print('Неизвестное состояние')
|
print('Неизвестное состояние')
|
||||||
|
|
||||||
# Вывод изображения.
|
# Вывод изображения.
|
||||||
cv.imshow('result', results[0].plot())
|
cv.imshow('result', results.render()[0][:, :, ::-1])
|
||||||
cv.waitKey(0)
|
cv.waitKey(0)
|
||||||
cv.destroyAllWindows()
|
cv.destroyAllWindows()
|
||||||
|
|
||||||
|
@ -1,9 +1,10 @@
|
|||||||
from ultralytics import YOLO
|
def rename_entity(list_names: dict) -> dict:
|
||||||
|
|
||||||
def load_model(name: str = 'yolov8s.pt') -> YOLO:
|
|
||||||
'''
|
'''
|
||||||
Загрузка предварительно натренированной модели.
|
Нормализация названий объектов.
|
||||||
@param name: Название модели.
|
@param list_names: Список названий объектов.
|
||||||
'''
|
'''
|
||||||
model = YOLO(name);
|
temp_list = list()
|
||||||
return model
|
for entity in list_names.values():
|
||||||
|
entity: str
|
||||||
|
temp_list.append(entity.title().replace(' ', ''))
|
||||||
|
return temp_list
|
||||||
|
@ -15,49 +15,41 @@ def is_ontology_exists(uid: str, url: str) -> bool:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def rename_entity(list_names: dict) -> dict:
|
def get_entity_square(results_ndarray_i: np.ndarray) -> float:
|
||||||
'''
|
|
||||||
Нормализация названий объектов.
|
|
||||||
@param list_names: Список названий объектов.
|
|
||||||
'''
|
|
||||||
temp_list = list()
|
|
||||||
for entity in list_names.values():
|
|
||||||
entity: str
|
|
||||||
temp_list.append(entity.title().replace(' ', ''))
|
|
||||||
return temp_list
|
|
||||||
|
|
||||||
|
|
||||||
def get_entity_square(width: float, height: float) -> float:
|
|
||||||
'''
|
'''
|
||||||
Получение площади занимаемой области.
|
Получение площади занимаемой области.
|
||||||
@param width: Ширина области в px.
|
@param results_ndarray_i: Описание местоположения объекта.
|
||||||
@param height: Высота области в px.
|
|
||||||
'''
|
'''
|
||||||
return abs(width * height)
|
square = float((results_ndarray_i[2] - results_ndarray_i[0]) *
|
||||||
|
(results_ndarray_i[3] - results_ndarray_i[1]))
|
||||||
|
return abs(square)
|
||||||
|
|
||||||
|
|
||||||
def get_request_data(entities: dict, objects: np.ndarray, confs: np.ndarray, boxes: np.ndarray) -> tuple[list, list]:
|
def get_request_data(entities: dict, results_ndarray: np.ndarray) -> tuple[list, list]:
|
||||||
'''
|
'''
|
||||||
Формирование данных для сервиса онтологий.
|
Формирование данных для сервиса онтологий.
|
||||||
@param entities: Список имён объектов.
|
@param entities: Список имён объектов.
|
||||||
@param results_ndarray: Результат распознавания объектов.
|
@param results_ndarray: Результат распознавания объектов.
|
||||||
'''
|
'''
|
||||||
classroom = 'classroom'
|
classroom = 'classroom'
|
||||||
entities = rename_entity(entities)
|
|
||||||
object_properties = list()
|
object_properties = list()
|
||||||
data_properties = list()
|
data_properties = list()
|
||||||
|
for i, entity in enumerate(entities): # запись в лист имен объектов и присутствие
|
||||||
for entity_idx, entity in enumerate(entities):
|
if (results_ndarray[:, -1] == i).sum() > 0: # если объект найден
|
||||||
if (entity_idx in objects):
|
object_properties.append({'domain': entity,
|
||||||
object_properties.append({'domain': entity, 'property': 'locatedIn', 'range': classroom})
|
'property': 'locatedIn',
|
||||||
|
'range': classroom})
|
||||||
else:
|
else:
|
||||||
object_properties.append({'domain': entity, 'property': 'notLocatedIn', 'range': classroom})
|
object_properties.append({'domain': entity,
|
||||||
|
'property': 'notLocatedIn',
|
||||||
|
'range': classroom})
|
||||||
|
|
||||||
for object_idx, object in enumerate(objects):
|
for i in range(results_ndarray.shape[0]):
|
||||||
conf = confs[object_idx]
|
data_properties.append({'domain': entities[int(results_ndarray[i, 5])],
|
||||||
box = boxes[object_idx]
|
'property': 'hasArea',
|
||||||
entity = entities[object.item()]
|
'value': get_entity_square(results_ndarray[i])})
|
||||||
data_properties.append({'domain': entity, 'property': 'hasArea', 'value': get_entity_square(float(box[2]), float(box[3]))})
|
data_properties.append({'domain': entities[int(results_ndarray[i, 5])],
|
||||||
data_properties.append({'domain': entity, 'property': 'hasConfidence', 'value': float(conf)})
|
'property': 'hasConfidence',
|
||||||
|
'value': float(results_ndarray[i, 4])})
|
||||||
|
|
||||||
return object_properties, data_properties
|
return object_properties, data_properties
|
||||||
|
Loading…
x
Reference in New Issue
Block a user