Compare commits
No commits in common. "b6a8209eb4d938669394d2549ebbcfd2d37ad1e3" and "62f0152a4fa4aab101de35f98320af40a2cc8454" have entirely different histories.
b6a8209eb4
...
62f0152a4f
@ -3,20 +3,13 @@ import numpy as np
|
|||||||
|
|
||||||
from main import img_size as size
|
from main import img_size as size
|
||||||
|
|
||||||
def image_transform(image: np.ndarray) -> np.ndarray:
|
|
||||||
'''
|
def image_transform(image):
|
||||||
Трансформирует изображение нужным образом.
|
|
||||||
@param image: Исходная матрица с представлением изображения.
|
|
||||||
'''
|
|
||||||
image = cv.resize(image, (size[0], size[1]))
|
image = cv.resize(image, (size[0], size[1]))
|
||||||
return image[:, :, ::-1]
|
return image[:, :, ::-1]
|
||||||
|
|
||||||
|
|
||||||
def get_image_as_array(image_name: str) -> np.ndarray:
|
def get_image_as_array(image_name):
|
||||||
'''
|
|
||||||
Получает изображение из файла и нормализует его.
|
|
||||||
@param image_name: Путь до изображения.
|
|
||||||
'''
|
|
||||||
image = cv.imread(image_name)
|
image = cv.imread(image_name)
|
||||||
image: np.ndarray # приведение типов
|
image: np.ndarray # приведение типов
|
||||||
image = image_transform(image)
|
image = image_transform(image)
|
||||||
|
25
main.py
25
main.py
@ -12,26 +12,18 @@ import ontologyWorking
|
|||||||
|
|
||||||
url = 'http://kb.athene.tech/api/1.0/ontology/'
|
url = 'http://kb.athene.tech/api/1.0/ontology/'
|
||||||
img_path = 'data'
|
img_path = 'data'
|
||||||
img_size = (1280, 720) # Размер изображения для нормализации.
|
img_size = (1280, 720)
|
||||||
|
|
||||||
|
|
||||||
def analyze_file(uid: str, image_path: str) -> None:
|
def analyse_file(uid, image_path):
|
||||||
'''
|
if ontologyWorking.is_ontology_exists(uid, url):
|
||||||
Анализирует файл и выводит результат в консоль.
|
|
||||||
@param uid: УИД онтологии.
|
|
||||||
@param url: Базовый URL сервиса.
|
|
||||||
'''
|
|
||||||
if not ontologyWorking.is_ontology_exists(uid, url):
|
|
||||||
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 = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
|
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
|
||||||
model.names = neuralNetwork.rename_entity(model.names)
|
model.names = neuralNetwork.rename_entity(model.names)
|
||||||
|
|
||||||
# Распознавание изображения.
|
|
||||||
results = model(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 i, res in enumerate(results.pred):
|
for i, res in enumerate(results.pred):
|
||||||
@ -40,7 +32,6 @@ def analyze_file(uid: str, image_path: str) -> None:
|
|||||||
object_properties += request[0]
|
object_properties += request[0]
|
||||||
data_properties += request[1]
|
data_properties += request[1]
|
||||||
|
|
||||||
# Формирование данных для запроса к сервису работы с онтологиями.
|
|
||||||
data = {
|
data = {
|
||||||
'data':
|
'data':
|
||||||
{
|
{
|
||||||
@ -48,14 +39,13 @@ def analyze_file(uid: str, image_path: str) -> None:
|
|||||||
'dataPropertyAssertions': data_properties
|
'dataPropertyAssertions': data_properties
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
result = {
|
result = {
|
||||||
'QueryGetNotEmpty': '',
|
'QueryGetNotEmpty': '',
|
||||||
'QueryGetCheck': '',
|
'QueryGetCheck': '',
|
||||||
'QueryGetEmpty': ''
|
'QueryGetEmpty': ''
|
||||||
}
|
}
|
||||||
params = '&'.join([f'names={query}' for query in result.keys()])
|
params = '&'.join([f'names={query}' for query in result.keys()])
|
||||||
|
|
||||||
# Выполнение запроса.
|
|
||||||
response = requests.post(url + f'{uid}/query/multi?{params}', json=data).json()
|
response = requests.post(url + f'{uid}/query/multi?{params}', json=data).json()
|
||||||
if response['error']:
|
if response['error']:
|
||||||
raise Exception(response['error'])
|
raise Exception(response['error'])
|
||||||
@ -63,7 +53,6 @@ def analyze_file(uid: str, image_path: str) -> None:
|
|||||||
result[query] = [resultSQWRL['name']['value'] for resultSQWRL in response['response'][query]['rows']]
|
result[query] = [resultSQWRL['name']['value'] for resultSQWRL in response['response'][query]['rows']]
|
||||||
print(f'Запрос выполнен')
|
print(f'Запрос выполнен')
|
||||||
|
|
||||||
# Вывод результата.
|
|
||||||
print()
|
print()
|
||||||
print('Результат:')
|
print('Результат:')
|
||||||
if result['QueryGetNotEmpty']:
|
if result['QueryGetNotEmpty']:
|
||||||
@ -75,14 +64,14 @@ def analyze_file(uid: str, image_path: str) -> None:
|
|||||||
else:
|
else:
|
||||||
print('Неизвестное состояние')
|
print('Неизвестное состояние')
|
||||||
|
|
||||||
# Вывод изображения.
|
# Вывод изображения
|
||||||
cv.imshow('result', results.render()[0][:, :, ::-1])
|
cv.imshow('result', results.render()[0][:, :, ::-1])
|
||||||
cv.waitKey(0)
|
cv.waitKey(0)
|
||||||
cv.destroyAllWindows()
|
cv.destroyAllWindows()
|
||||||
|
|
||||||
# Точка входа в приложение.
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
if len(sys.argv) != 3:
|
if len(sys.argv) != 3:
|
||||||
print(f'Запуск: {sys.argv[0]} <Ontology UID> <Image path>')
|
print(f'Запуск: {sys.argv[0]} <Ontology UID> <Image path>')
|
||||||
exit(1)
|
exit(1)
|
||||||
analyze_file(sys.argv[1], sys.argv[2])
|
analyse_file(sys.argv[1], sys.argv[2])
|
||||||
|
@ -1,8 +1,4 @@
|
|||||||
def rename_entity(list_names: dict) -> dict:
|
def rename_entity(list_names: dict):
|
||||||
'''
|
|
||||||
Нормализация названий объектов.
|
|
||||||
@param list_names: Список названий объектов.
|
|
||||||
'''
|
|
||||||
temp_list = list()
|
temp_list = list()
|
||||||
for entity in list_names.values():
|
for entity in list_names.values():
|
||||||
entity: str
|
entity: str
|
||||||
|
@ -1,36 +1,21 @@
|
|||||||
import numpy as np
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
|
|
||||||
def is_ontology_exists(uid: str, url: str) -> bool:
|
def is_ontology_exists(uid, url):
|
||||||
'''
|
list_ontologies = requests.get(url).json()['response']
|
||||||
Проверяет, существует ли онтология в сервисе.
|
|
||||||
@param uid: УИД онтологии.
|
|
||||||
@param url: Базовый URL сервиса.
|
|
||||||
'''
|
|
||||||
list_ontologies = requests.get(url).json()['response']['items']
|
|
||||||
for onto in list_ontologies:
|
for onto in list_ontologies:
|
||||||
if onto['uid'] == uid:
|
if onto['uid'] == uid:
|
||||||
return True
|
return False
|
||||||
return False
|
return True
|
||||||
|
|
||||||
|
|
||||||
def get_entity_square(results_ndarray_i: np.ndarray) -> float:
|
def get_entity_square(results_ndarray_i):
|
||||||
'''
|
|
||||||
Получение площади занимаемой области.
|
|
||||||
@param results_ndarray_i: Описание местоположения объекта.
|
|
||||||
'''
|
|
||||||
square = float((results_ndarray_i[2] - results_ndarray_i[0]) *
|
square = float((results_ndarray_i[2] - results_ndarray_i[0]) *
|
||||||
(results_ndarray_i[3] - results_ndarray_i[1]))
|
(results_ndarray_i[3] - results_ndarray_i[1]))
|
||||||
return abs(square)
|
return abs(square)
|
||||||
|
|
||||||
|
|
||||||
def get_request_data(entities: dict, results_ndarray: np.ndarray) -> tuple[list, list]:
|
def get_request_data(entities, results_ndarray):
|
||||||
'''
|
|
||||||
Формирование данных для сервиса онтологий.
|
|
||||||
@param entities: Список имён объектов.
|
|
||||||
@param results_ndarray: Результат распознавания объектов.
|
|
||||||
'''
|
|
||||||
classroom = 'classroom'
|
classroom = 'classroom'
|
||||||
object_properties = list()
|
object_properties = list()
|
||||||
data_properties = list()
|
data_properties = list()
|
||||||
|
Loading…
x
Reference in New Issue
Block a user