From 0b1958e4d8e104ed6ff49977154ef50f37729213 Mon Sep 17 00:00:00 2001 From: "Alexander \"Skade\" Soldatenkov" Date: Wed, 3 Jul 2024 18:17:53 +0300 Subject: [PATCH 1/2] Timacad Framework + Image Processor --- .gitignore | 167 +++++++++++++++++++++++++++++++++++++++++++ image_processor.py | 97 +++++++++++++++++++++++++ test_of_framework.py | 17 +++++ timacad_framework.py | 34 +++++++++ 4 files changed, 315 insertions(+) create mode 100644 .gitignore create mode 100644 image_processor.py create mode 100644 test_of_framework.py create mode 100644 timacad_framework.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..67be2e6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,167 @@ +# Models files +models/ + +.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 0000000..a265b59 --- /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: Union[str, Any]) -> Image.Image: + try: + if isinstance(file, str): # если file - это путь к файлу + image = Image.open(file) + elif hasattr(file, '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.Image) -> Any: + image_np = np.array(image) + results = self.model(image_np) + return results + + def draw_detections(self, image: Image.Image, results: Any) -> Image.Image: + 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: Any) -> 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: Union[str, Any], output_type: str = 'json') -> Union[dict, io.BytesIO]: + 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 0000000..d4f6129 --- /dev/null +++ b/test_of_framework.py @@ -0,0 +1,17 @@ +import os + +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", "1599753807195975144.png") # Убираем запятую + + blood_cells_processor = TimacadFramework.create("local", "blood_cells") + segmentation_processor = TimacadFramework.create("local", "segmentation_of_fields") + + result_json = blood_cells_processor.process(pic_path, output_type='json') + print(result_json) + + 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 0000000..180eade --- /dev/null +++ b/timacad_framework.py @@ -0,0 +1,34 @@ +import os + +from ultralytics import YOLO + +from image_processor import ImageProcessor + + +class TimacadFramework: + def __init__(self, model_path: str): + self.model_path = model_path + self.model = YOLO(model_path) + + @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 -- GitLab From 9f68aa35f69a44bbc147c73f37794ea568d418df Mon Sep 17 00:00:00 2001 From: Lapshin Sergey Date: Thu, 18 Jul 2024 17:58:05 +0300 Subject: [PATCH 2/2] fix --- .gitignore | 2 ++ image_processor.py | 14 +++++++------- test_of_framework.py | 14 ++++++++++++-- timacad_framework.py | 7 +++++-- 4 files changed, 26 insertions(+), 11 deletions(-) diff --git a/.gitignore b/.gitignore index 67be2e6..28dbf63 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ # Models files models/ +# Pictures files +pictures/ .idea/ diff --git a/image_processor.py b/image_processor.py index a265b59..60843f3 100644 --- a/image_processor.py +++ b/image_processor.py @@ -10,11 +10,11 @@ class ImageProcessor: def __init__(self, model: YOLO): self.model = model - def read_image(self, file: Union[str, Any]) -> Image.Image: + def read_image(self, file): try: - if isinstance(file, str): # если file - это путь к файлу + if isinstance(file, str): image = Image.open(file) - elif hasattr(file, 'file'): # если file - это загруженный файл + elif hasattr(file, 'file'): image = Image.open(file.file) else: raise ValueError("Unsupported file type") @@ -25,12 +25,12 @@ class ImageProcessor: except Exception as e: raise RuntimeError(f"Ошибка при чтении изображения: {e}") - def process_image(self, image: Image.Image) -> Any: + def process_image(self, image): image_np = np.array(image) results = self.model(image_np) return results - def draw_detections(self, image: Image.Image, results: Any) -> Image.Image: + def draw_detections(self, image, results): draw = ImageDraw.Draw(image) try: font = ImageFont.load_default() @@ -58,7 +58,7 @@ class ImageProcessor: return image - def results_to_json(self, results: Any) -> list: + 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() @@ -78,7 +78,7 @@ class ImageProcessor: detections.append(detection) return detections - def process(self, file: Union[str, Any], output_type: str = 'json') -> Union[dict, io.BytesIO]: + def process(self, file, output_type: str = 'json'): try: image = self.read_image(file) results = self.process_image(image) diff --git a/test_of_framework.py b/test_of_framework.py index d4f6129..b5078af 100644 --- a/test_of_framework.py +++ b/test_of_framework.py @@ -1,17 +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", "1599753807195975144.png") # Убираем запятую + # Указываем путь к изображениям + 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) + # 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 index 180eade..c93e14a 100644 --- a/timacad_framework.py +++ b/timacad_framework.py @@ -7,8 +7,11 @@ from image_processor import ImageProcessor class TimacadFramework: def __init__(self, model_path: str): - self.model_path = model_path - self.model = YOLO(model_path) + 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': -- GitLab