diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..28dbf635eed5aec4400f718475a41429ff23e6ae --- /dev/null +++ b/.gitignore @@ -0,0 +1,169 @@ +# Models files +models/ +# Pictures files +pictures/ + +.idea/ + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/latest/usage/project/#working-with-version-control +.pdm.toml +.pdm-python +.pdm-build/ + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ diff --git a/image_processor.py b/image_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..60843f3bd080c04c5765cf246d42c6085e9e1f3c --- /dev/null +++ b/image_processor.py @@ -0,0 +1,97 @@ +import io +from typing import Union, Any + +import numpy as np +from PIL import Image, ImageDraw, ImageFont +from ultralytics import YOLO + + +class ImageProcessor: + def __init__(self, model: YOLO): + self.model = model + + def read_image(self, file): + try: + if isinstance(file, str): + image = Image.open(file) + elif hasattr(file, 'file'): + image = Image.open(file.file) + else: + raise ValueError("Unsupported file type") + + if image.mode in ('RGBA', 'L'): + image = image.convert('RGB') + return image + except Exception as e: + raise RuntimeError(f"Ошибка при чтении изображения: {e}") + + def process_image(self, image): + image_np = np.array(image) + results = self.model(image_np) + return results + + def draw_detections(self, image, results): + draw = ImageDraw.Draw(image) + try: + font = ImageFont.load_default() + except IOError: + font = None + + if not font: + try: + font = ImageFont.truetype("arial.ttf", 15) + except IOError: + font = ImageFont.load_default() + + boxes = results[0].boxes.xyxy.cpu().numpy() + confidences = results[0].boxes.conf.cpu().numpy() + classes = results[0].boxes.cls.cpu().numpy() + names = results[0].names + + for i, box in enumerate(boxes): + x1, y1, x2, y2 = box + conf = confidences[i] + cls = classes[i] + draw.rectangle([x1, y1, x2, y2], outline="red", width=2) + label = f"{names[int(cls)]} {conf:.2f}" + draw.text((x1, y1), label, fill="red", font=font) + + return image + + def results_to_json(self, results) -> list: + boxes = results[0].boxes.xyxy.cpu().numpy() + confidences = results[0].boxes.conf.cpu().numpy() + classes = results[0].boxes.cls.cpu().numpy() + names = results[0].names + detections = [] + + for i, box in enumerate(boxes): + x1, y1, x2, y2 = box + conf = confidences[i] + cls = classes[i] + detection = { + "bbox": [int(x1), int(y1), int(x2), int(y2)], + "confidence": float(conf), + "class": int(cls), + "name": names[int(cls)] + } + detections.append(detection) + return detections + + def process(self, file, output_type: str = 'json'): + try: + image = self.read_image(file) + results = self.process_image(image) + + if output_type == 'json': + return self.results_to_json(results) + elif output_type == 'jpg': + image_with_detections = self.draw_detections(image, results) + img_byte_arr = io.BytesIO() + image_with_detections.save(img_byte_arr, format='JPEG') + img_byte_arr.seek(0) + return img_byte_arr + else: + raise ValueError(f"Unsupported output type: {output_type}") + except Exception as e: + raise RuntimeError(f"Error processing image: {e}") \ No newline at end of file diff --git a/test_of_framework.py b/test_of_framework.py new file mode 100644 index 0000000000000000000000000000000000000000..b5078af79e7e0a033bf8a0da94f11c03bccc126d --- /dev/null +++ b/test_of_framework.py @@ -0,0 +1,27 @@ +import os +import json + +from timacad_framework import TimacadFramework + +if __name__ == "__main__": + # Определяем директорию + base_path = os.path.dirname(os.path.abspath(__file__)) + + # Указываем путь к изображениям + pic_path = TimacadFramework.get_normalized_path(base_path, "pictures", "2.jpg") + + # Создаем объект TimacadFramework + blood_cells_processor = TimacadFramework.create("local", "blood_cells") + segmentation_processor = TimacadFramework.create("local", "segmentation_of_fields") + + # Получение json нотации + result_json = blood_cells_processor.process(pic_path, output_type='json') + # print(result_json) + + with open('output.json', 'w', encoding='utf-8') as f: + json.dump(result_json, f, ensure_ascii=False, indent=4) + + # Сохранение аннотированного изображения + result_jpg = blood_cells_processor.process(pic_path, output_type='jpg') + with open('output.jpg', 'wb') as f: + f.write(result_jpg.getbuffer()) \ No newline at end of file diff --git a/timacad_framework.py b/timacad_framework.py new file mode 100644 index 0000000000000000000000000000000000000000..c93e14a841d2089949e4c30bbaa769a9b4f647a0 --- /dev/null +++ b/timacad_framework.py @@ -0,0 +1,37 @@ +import os + +from ultralytics import YOLO + +from image_processor import ImageProcessor + + +class TimacadFramework: + def __init__(self, model_path: str): + try: + self.model_path = model_path + self.model = YOLO(model_path) + except: + print('Model not found') + + @classmethod + def create(cls, execute: str, model_type: str) -> 'ImageProcessor': + if execute != "local": + raise ValueError("You can use only local version at this point") + + base_path = os.path.dirname(os.path.abspath(__file__)) + model_paths = { + "blood_cells": cls.get_normalized_path(base_path, "models", "BloodCells.pt"), + "segmentation_of_fields": cls.get_normalized_path(base_path, "models", "SegmentationOfFields.pt") + } + + if model_type not in model_paths: + raise ValueError(f"Unsupported model type: {model_type}") + + builder = cls(model_paths[model_type]) + return ImageProcessor(builder.model) + + @staticmethod + def get_normalized_path(base_path: str, *paths: str) -> str: + full_path = os.path.join(base_path, *paths) + normalized_path = full_path.replace("\\", "/") + return normalized_path \ No newline at end of file