Руководство по GUI анализа изображений и CV pipeline CV GUI and Pipeline Guide

Это руководство описывает работу с панелью CV/AI в Screph и особенно подробно объясняет расширенный pipeline. Документ ориентирован на пользователя интерфейса: без внутренней реализации, но с практическими сценариями, понятной терминологией и пошаговой навигацией по GUI. This guide explains the Screph CV/AI panel and, in particular, the advanced pipeline editor. It is written for GUI users: practical, task-oriented, and focused on how to work with the interface rather than on internal implementation details.

Основная CV-панель и её общий каталог методов доступны как часть полного продукта, а выбранный режим программы добавляет свою предметную семантику и workspace. «Общий» предназначен для нейтрального анализа изображений, «Автоматизация GUI» добавляет типы экранных элементов, markup refs, review и подтверждённое применение разметки, а «Промышленное зрение» и «Автономные беспилотники» — экспериментальные предметные задачи, кандидаты и evidence. Выберите режим в шапке Selector или в Общие настройки → Платформа разработки; границы режимов описаны в отдельной справке. The main CV panel and its shared method catalog are part of the complete product, while the selected program mode adds domain semantics and a dedicated workspace. General targets neutral image analysis; GUI Automation adds screen-element types, markup refs, review and confirmed markup application; Industrial Vision and Autonomous Unmanned Vehicles add experimental domain tasks, candidates and evidence. Select the mode in the Selector header or under General Settings → Development Platform; see the dedicated guide for mode boundaries.

1. Что делает CV GUI 1. What the CV GUI Does

CV GUI помогает находить области на изображении, выделять маски и контуры, распознавать текст, объединять несколько шагов обработки и превращать результат в каноническую разметку проекта. Конкретные типы задач и кандидатов определяет выбранный режим программы. The CV GUI helps you detect regions in an image, build masks and contours, read text, combine multiple processing steps, and turn the result into canonical project markup. The selected program mode determines the available task and candidate types.

  • Простой режим: выбрать один метод и настроить несколько параметров. Simple mode: choose one method and tune a small set of parameters.
  • Линейный pipeline: собрать цепочку шагов один за другим. Linear pipeline: build a straight sequence of steps.
  • Расширенный pipeline: собрать граф из методов, ветвлений, merge и runtime-inspector. Advanced pipeline: build a graph with methods, branching, merges, and runtime inspection.

2. Базовый сценарий работы 2. Basic Workflow

  1. Откройте изображение или выберите элемент/ROI на холсте. Open an image or select an element/ROI on the canvas.
  2. Откройте панель CV/AI и выберите режим обработки. Open the CV/AI panel and choose a processing mode.
  3. Включите live preview для быстрых итераций или оставьте ручной Apply для тяжёлых методов. Enable live preview for quick iteration or keep manual Apply for heavier methods.
  4. Проверьте preview и overlay на холсте. Check the preview and the overlay on the canvas.
  5. Выберите нужную границу: сохранить технический run, прикрепить mask/result к image series элемента или явно создать canonical elements. Choose the required boundary: archive the technical run, attach a mask/result to an element's image series, or explicitly create canonical elements.

Практический совет:Practical tip: если вы не уверены, с чего начать, сначала ограничьте область интереса (ROI), а уже потом запускайте цветовую или сегментационную обработку. Это быстрее и обычно даёт меньше шума. if you are unsure where to start, first reduce the area of interest (ROI), then run color or segmentation processing. It is faster and usually produces less noise.

Несколько представлений одного проектаMultiple presentations of one project

Кнопка раскладки в панели меню может показать одну область A, две области A/B слева–справа или сверху–снизу, три области с A слева и B/C справа либо сетку A/B/C/D 2×2. Это не копии проекта: каноническая разметка, selection и project undo/redo у областей общие, а visual material и pane-local display settings могут быть разными.The layout control in the menu-bar toolbar can show one A pane, A/B side by side or stacked, three panes with A on the left and B/C on the right, or a 2×2 A/B/C/D grid. These are not project copies: canonical markup, selection and project undo/redo are shared, while visual material and pane-local display settings may differ.

  • В настройках каждой области можно изменить название, выбрать Source, рабочий CV-result, mask или diagnostic artifact, способ показа и crop source.Each pane's settings let you change its label and select Source, a working CV result, a mask or diagnostic artifact, its display mode and crop source.
  • Кнопка Активировать задаёт область для Canvas tools и, по умолчанию, источник пикселей ROI. Запрос активации stale, unmapped или read-only presentation отклоняется; если уже активная область стала несовместимой, owner возвращается к A.The Activate control chooses the pane used by Canvas tools and, by default, the ROI pixel source. Activation of a stale, unmapped or read-only presentation is rejected; if the current active pane becomes incompatible, ownership returns to A.
  • Linked panes синхронизируют zoom, центр viewport и canvas-курсор. A всегда является участником связанной группы; B/C/D можно отвязать. Read-only область может быть источником навигации, не становясь владельцем project interaction.Linked panes synchronize zoom, viewport center and the canvas-space cursor. A always belongs to the linked group; B/C/D can be unlinked. A read-only pane may drive navigation without owning project interaction.
  • Поле Источник вырезки явно выбирает текущий instance или исходный Source.The Crop source field explicitly chooses the current instance or the original Source.
  • Mask, diff/composite, display-only transform и stale/unmapped result не являются допустимым ROI input. Операция блокируется вместо скрытого возврата к Source.A mask, diff/composite, display-only transform or stale/unmapped result is not a valid ROI input. The operation is blocked instead of silently falling back to Source.
  • Область A нельзя закрыть. B/C/D закрываются явно без удаления presentation; меньшая раскладка не удаляет их скрыто. Общий Reset назначает Source области A, активирует её, закрывает остальные области и возвращает single layout.Pane A cannot be closed. B/C/D are closed explicitly without deleting a presentation; a smaller layout never removes them silently. Global Reset assigns Source to A, activates it, closes the other panes and returns to the single layout.

Варианты отображения Результат, Градации серого, Инверсия и Псевдоцвет меняют только визуализацию, а не material или recipe. Для сравнения оставьте Source в соседней связанной области.The Result, Grayscale, Invert and Pseudocolor options change display only, not the material or recipe. Keep Source in an adjacent linked pane for comparison.

Предобработка полного изображенияFull-image preprocessing

  1. Откройте Source или существующее рабочее представление в нужной области.Open Source or an existing working presentation in the target pane.
  2. Нажмите Настроить CV; для Source будет создано рабочее processed_raster представление.Press Configure CV; for Source, a working processed_raster presentation is created.
  3. В Анализ изображения → Обработка представления выберите метод или linear pipeline и нажмите Обновить представление.Under Image analysis → Presentation processing, choose a method or linear pipeline and press Update presentation.

У каждого рабочего представления собственные параметры. В его каталоге всегда действует Всё изображение; методы, которым нужны ROI, click, timeline, reference image или побочное изменение проекта, туда не включаются.Each working presentation has its own parameters. Its catalog always operates on the Full image; methods requiring an ROI, click, timeline, reference image or a project-side mutation are excluded.

3. Основные части панели 3. Main Parts of the Panel

  • Режим обработкиProcessing Mode: выбор метода или pipeline. choose a method or a pipeline mode.
  • Параметры методаMethod Parameters: динамическая форма с настройками выбранного метода. dynamic form with settings for the selected method.
  • PreviewPreview: показывает, что именно вернул метод или pipeline. shows what the method or pipeline produced.
  • OverlayOverlay: накладывает маску и контуры на холст, чтобы вы сравнивали результат с исходным изображением. overlays masks and contours on the canvas so you can compare them with the original image.
  • Preset-ыPresets: сохраняют удачные наборы параметров. save useful parameter combinations.
  • Сохранение результатовResult Saving: отдельные действия для runtime archive, image series выбранного элемента и canonical markup. separate actions for the runtime archive, the selected element's image series and canonical markup.
  • Live preview / Auto / AI: Рисовка на лету пересчитывает результат при изменении параметров; 🔮 Авто подбирает параметры по изображению; AI выбор разрешает LLM предложить алгоритм. Для больших кадров и model-backed методов лучше использовать ручное Обновить превью. Live drawing recalculates after parameter changes; 🔮 Auto tunes parameters from the image; AI selection lets the LLM propose an algorithm. For large frames and model-backed methods, prefer manual Refresh preview.
  • Сессия и действияSession and actions: Применить запускает анализ и в основной панели обычно прикрепляет/заменяет cv_result в image series выбранного элемента; Сохранить пишет технический run в именованную CV-сессию; Добавить как элементы создаёт canonical elements, а Добавить маску в результаты добавляет отдельную mask entry. Apply runs analysis and, in the main panel, normally attaches or replaces a cv_result entry in the selected element's image series; Save writes a technical run to the named CV session; Add as elements creates canonical elements, and Add mask to results appends a separate mask entry.
  • Пипетка HSVHSV eyedropper: берёт цвет из preview и заполняет H/S/V с допусками dH/dS/dV. samples a preview color and fills H/S/V ranges with dH/dS/dV tolerances.

Text / OCR использует локальный Tesseract из ocr.runtime. YOLO, три SAM backend и OmniParser требуют отдельно готового ml.runtime и подходящих local model assets. Наличие пункта в списке методов означает доступность интерфейса, а не готовность runtime или уже загруженные веса. См. управление моделями и весами.Text / OCR uses the local Tesseract supplied by ocr.runtime. YOLO, the three SAM backends and OmniParser separately require a ready ml.runtime and suitable local model assets. A method appearing in the list means its UI is available, not that the runtime or weights are already ready. See model and weight management.

Применить не подтверждает CV candidate как geometry/semantic markup. Но explicit Apply в основной панели по умолчанию сохраняет визуальный result в image series выбранного элемента и записывает это изменение в project history; автоматический live-preview recalculation этого не делает. Добавить как элементы создаёт только canonical ScreenElement. Canonical feature или markup group появляются лишь в тех mode-specific review/apply путях, где это явно поддержано.Apply does not accept a CV candidate as geometry or semantic markup. However, explicit Apply in the main panel stores the visual result in the selected element's image series by default and records that project-history mutation; automatic live-preview recalculation does not. Add as elements creates canonical ScreenElement objects only. A canonical feature or markup group appears only in a mode-specific review/apply path that explicitly supports it.

Кнопка настроек LLM открывает профиль роли CV. Model-backed и OCR-методы требуют соответствующих runtime-компонентов.The LLM settings button opens the CV role profile. Model-backed and OCR methods require their matching runtime components. LLM-подключенияLLM connections · ЗависимостиDependencies

4. Жизненный цикл CV-результата 4. CV Result Lifecycle

ДействиеActionЧто создаётсяWhat it createsМеняет проектProject mutation
Live previewРабочий preview/overlay и last-result state.Working preview/overlay and last-result state.Нет автоматического сохранения при пересчёте параметров.No automatic save during parameter-driven recalculation.
Применить / ApplyНовый анализ; в основной панели обычно verified artifact bundle и прикреплённый cv_result.A new analysis; in the main panel, normally a verified artifact bundle and attached cv_result.Image series выбранного элемента может измениться; canonical geometry/semantics — нет.The selected element's image series may change; canonical geometry/semantics do not.
Сохранить / SaveBundle текущего run и legacy/debug projection в именованной CV-сессии.The current run bundle and a legacy/debug projection in the named CV session.Не создаёт markup и само по себе не прикрепляет run к project element.Creates no markup and does not itself attach the run to a project element.
Добавить маску в результатыОтдельная cv_mask entry с artifact metadata.A separate cv_mask entry with artifact metadata.Да, image series элемента и project history.Yes: the element image series and project history.
Добавить как элементыRect/polygon elements из последних contours.Rectangle or polygon elements from the latest contours.Да, explicit canonical markup mutation.Yes: an explicit canonical-markup mutation.
Mode review/applyMode review/applyПринятое решение, apply preview/plan и target, разрешённый конкретным режимом.An accepted decision, apply preview/plan and a target allowed by that mode.Да, только после validation; apply транзакционный и пытается rollback при ошибке.Yes, only after validation; apply is transactional and attempts rollback on failure.

CV candidate, canonical markup и FeatureMatchCV candidates, canonical markup and FeatureMatch

CV method сначала выдаёт result/evidence: preview, detections, contours, mask и metrics. Это ещё не объект Selector. Review связывает candidate с markup_candidate_id и создаёт accepted decision; затем готовятся patch и apply preview. Только явный apply после проверки target, revision и отсутствия дублей меняет canonical project.A CV method first emits a result/evidence: preview, detections, contours, a mask and metrics. This is not yet a Selector object. Review binds the candidate to a markup_candidate_id and creates an accepted decision; a patch and apply preview follow. Only an explicit apply, after target, revision and duplicate checks, mutates the canonical project.

ПоверхностьSurfaceЧто реально создаётсяWhat it can createГраница готовностиReadiness boundary
General / GUI AutomationТекущий promotion UI принимает только canonical element; generic contract шире, но этот UI не создаёт feature/group.The current promotion UI accepts canonical element only; the generic contract is broader, but this UI does not create a feature/group.Accepted review → patch → preview → transactional apply.Accepted review → patch → preview → transactional apply.
Industrialelement или region feature (DEFECT, MEASUREMENT_ZONE, TOLERANCE_REGION).element or a region feature (DEFECT, MEASUREMENT_ZONE, TOLERANCE_REGION).Candidate decision и confirmed apply есть, но workflow_ready=False; это не production review/export/control authority.Candidate decisions and confirmed apply exist, but workflow_ready=False; this is not production review/export/control authority.
UAVelement, region feature (AOI/TILE/CHANGE_REGION) или typed TRACK_GROUP.element, region feature (AOI/TILE/CHANGE_REGION) or a typed TRACK_GROUP.Есть transactional apply foundation, но workflow_ready=False; не mission control/GIS/dataset/export workflow.Transactional apply foundation exists, but workflow_ready=False; this is not a mission-control/GIS/dataset/export workflow.
FeatureMatchОтдельная запись occurrence, ссылающаяся на уже существующий feature и хранящая bbox, score, target point и source.A separate occurrence record referencing an existing feature and storing bbox, score, target point and source.Создаётся явным действием из Feature inspector. Ни live preview, ни CV-метод Feature Match не создают domain FeatureMatch автоматически: метод возвращает detections.Created by an explicit Feature-inspector action. Neither live preview nor the Feature Match CV method creates a domain FeatureMatch automatically; the method returns detections.

Проверка candidate и создание FeatureMatch — разные операции: первая продвигает evidence в canonical markup, вторая фиксирует конкретное найденное occurrence уже существующего feature. Это также разные записи project JSON и разные undo/redo mutations.Candidate review/apply and FeatureMatch creation are different operations: the first promotes evidence into canonical markup, while the second records a concrete occurrence of an existing feature. They are separate project-JSON records and separate undo/redo mutations.

Verified bundle хранит source snapshot при его наличии, execution recipe, config snapshot, metrics, standard/extra outputs, SHA-256/size metadata, coordinate contracts и write report. Manifest публикуется только после успешной записи и readback всех обязательных ссылок.A verified bundle stores the source snapshot when available, execution recipe, config snapshot, metrics, standard and extra outputs, SHA-256/size metadata, coordinate contracts and a write report. Its manifest is published only after required references pass write and readback.

Именованная CV-сессия — runtime archive в ScrephData/screen_selector/cv/results, а не второй project format. Список recent sessions содержит не более десяти ID, но это не retention файлов: автоматической очистки старых session directories здесь нет. При сохранении canonical project Selector импортирует только CV entries, прикреплённые к element image series, копирует их artifacts в <name>_artifacts и создаёт project-local result manifest. Неприкреплённый технический archive в package не попадает.A named CV session is a runtime archive under ScrephData/screen_selector/cv/results, not a second project format. The recent-session list keeps at most ten IDs, but this is not file retention: old session directories are not automatically pruned here. When the canonical project is saved, Selector imports only CV entries attached to element image series, copies their artifacts into <name>_artifacts, and writes a project-local result manifest. An unattached technical archive is not included in the package.

Как CV artifacts входят в project package →How CV artifacts enter the project package →

5. Video CV и temporal tracking5. Video CV and Temporal Tracking

Workspace Video CV анализирует последовательность кадров Capture с durable source/timeline identity. Можно обработать выделенный диапазон, текущий clip, весь timeline, окно из 11 кадров вокруг playhead или live stream; направление задаётся отдельно. Pre-roll и post-roll расширяют offline-границы, шаг кадров прореживает вход, а масштаб 100/75/50/25% уменьшает нагрузку с нормализацией результата обратно в координаты источника.The Video CV workspace analyzes a Capture frame sequence with durable source and timeline identity. It can process a selected range, the current clip, the complete timeline, an 11-frame window around the playhead, or a live stream; direction is selected separately. Pre-roll and post-roll expand offline bounds, frame stride subsamples the input, and 100/75/50/25% processing scales reduce load while results are normalized back to source coordinates.

  • Analysis ROI и exclusion areas привязаны к selection context. Если selection изменился, запуск блокируется до обновления контекста — старая ROI не применяется молча.The analysis ROI and exclusion areas are bound to the selection context. If selection changes, execution is blocked until the context is refreshed; a stale ROI is not reused silently.
  • Live reader имеет очередь на четыре кадра и явную политику backpressure: reject, drop oldest или drop newest. Stop/cancel закрывает reader; gaps в offline sequence диагностируются и сбрасывают temporal processor.The live reader has a four-frame queue and an explicit reject, drop-oldest or drop-newest backpressure policy. Stop/cancel closes the reader; offline gaps are diagnosed and reset the temporal processor.
  • Overlay разделён на motion, tracks, accepted markup, detections, optical flow, events и candidates. История запусков позволяет восстановить параметры, повторить run и перейти к проблеме.Overlay layers include motion, tracks, accepted markup, detections, optical flow, events and candidates. Run history can restore parameters, rerun an analysis and navigate to an issue.

Temporal providersTemporal providers

Встроенный registry включает UAV Sparse Camera Stabilization, OpenCV MOG2 Motion, MIL/CSRT/KCF trackers, Farneback Optical Flow, Activity Events, Native Scene Difference и conditional PySceneDetect Content. Недоступный provider выключается с причиной и repair action: CSRT/KCF требуют подходящий opencv-contrib, PySceneDetect — свою dependency. SAM 2.1 Prompt Mask Propagation сейчас является недоступным internal target будущего isolated worker, а не обычным рабочим backend.The built-in registry includes UAV Sparse Camera Stabilization, OpenCV MOG2 Motion, MIL/CSRT/KCF trackers, Farneback Optical Flow, Activity Events, Native Scene Difference and conditional PySceneDetect Content. An unavailable provider is disabled with a reason and repair action: CSRT/KCF require a suitable opencv-contrib build, while PySceneDetect needs its dependency. SAM 2.1 Prompt Mask Propagation is currently an unavailable internal target for a future isolated worker, not a normal working backend.

Run, track apply и редактированиеRuns, track apply and editing

  1. Запустите provider и дождитесь completed, partial, cancelled или failed. Snapshot входа, config, provenance, coverage, issues и observations сохраняются в temporal run store.Run a provider and wait for completed, partial, cancelled or failed status. The input snapshot, configuration, provenance, coverage, issues and observations are stored in the temporal run store.
  2. Для tracker-run выберите track и подготовьте apply preview. План показывает observations/keyframes/lost states и ожидаемую revision, сохраняя manual/protected observations существующего track.For a tracker run, select a track and prepare the apply preview. The plan reports observations, keyframes, lost states and the expected revision while preserving manual or protected observations from an existing track.
  3. Подтвердите apply. Проект должен быть заранее сохранён или открыт: операция пишет Selector-owned sidecar <project>.temporal-markup.json с revision guard и project undo/redo.Confirm apply. The project must already be saved or opened because the operation writes the Selector-owned <project>.temporal-markup.json sidecar with a revision guard and project undo/redo.

После применения доступны manual keyframe из текущей ROI, удаление keyframe, trim/terminate, split, состояния occluded/outside, undo/redo, безопасный merge без неоднозначных пересечений, смена track ID и retrack от manual keyframe. Это явная prepare/apply граница temporal markup, а не автоматическое принятие всех observations.After apply, you can add a manual keyframe from the current ROI, remove a keyframe, trim or terminate, split, mark occluded/outside, undo/redo, safely merge without ambiguous overlaps, reassign a track ID and retrack from a manual keyframe. This is an explicit prepare/apply boundary for temporal markup, not automatic acceptance of every observation.

Экспорт активного runExporting the active run

  • Neutral JSON содержит run/provider/status, hashes, coverage, provenance, config, observations и optional codegen IR из сохранённого recipe. Это данные, не исполняемый скрипт.Neutral JSON contains run/provider/status, hashes, coverage, provenance, configuration, observations and optional codegen IR from the persisted recipe. It is data, not an executable script.
  • Annotated preview создаёт MJPG AVI по текущим полям start/end и timeline mapping, рисуя track и motion bounding boxes. Нужны положительный Capture FPS, каждый запрошенный кадр и рабочий OpenCV VideoWriter.Annotated preview creates an MJPG AVI using the current start/end fields and timeline mapping, drawing track and motion bounding boxes. It requires a positive Capture FPS, every requested frame and a working OpenCV VideoWriter.

Оба экспорта являются artifacts выбранного run, а не dataset export и не project save.Both exports are artifacts of the selected run, not a dataset export or project save. Файлы и границы temporal data →Temporal data files and boundaries →

6. Фактический каталог методов 6. Actual Method Catalog

В основной панели зарегистрировано 28 пользовательских одиночных методов. Это реальные пункты выбора, а не число уникальных математических алгоритмов: например, MobileSAM, FastSAM и EfficientSAM — три backend одного семейства promptable segmentation.The main panel registers 28 user-facing single methods. These are actual selectable entries, not a count of unique mathematical algorithms: MobileSAM, FastSAM and EfficientSAM, for example, are three backends in one promptable-segmentation family.

  • Фильтры и цвет:Filters and color: Edges (Canny), Color (HSV), Color Mask (K-Means).
  • Сегментация и маски:Segmentation and masks: GrabCut, Watershed, SLIC Superpixels, YOLO segmentation, MobileSAM, FastSAM, EfficientSAM.
  • Текст и структура:Text and structure: Text / OCR, OmniParser, Hough Lines, Hough Circles, MSER, Connected Components, Contours, Adaptive Threshold.
  • GUI, reference и temporal:GUI, reference and temporal: Template Match, Point Region Grow, Shape Analyze, Line/Rect Layout, Feature Match, Before/After Diff, Align To Reference, Target Track (KLT), UI Layout (Local), Visual ReID.

Для linear pipeline и method-flow graph дополнительно зарегистрировано 14 служебных узлов: Grayscale, Brightness/Contrast, Gamma, Gaussian Blur, Median Blur, CLAHE, Resize, Crop/Pad, Rotate, Deskew, Apply Mask to Image, Invert Mask, Morphology и Extract Contours. Они нужны для построения потока данных и поэтому не дублируются в списке одиночных методов.Linear pipelines and method-flow graphs additionally register 14 utility nodes: Grayscale, Brightness/Contrast, Gamma, Gaussian Blur, Median Blur, CLAHE, Resize, Crop/Pad, Rotate, Deskew, Apply Mask to Image, Invert Mask, Morphology and Extract Contours. They exist to build data flows and therefore are not duplicated in the single-method list.

Каталог рабочего представления уже. Full-image presentation включает только методы с безопасным exact-image/exact-mask контрактом. Template Match, Point Region Grow, Feature Match, Before/After Diff, Align To Reference, Target Track (KLT) и Visual ReID требуют reference, click, timeline или другого контекста и поэтому там не показываются.The working-presentation catalog is narrower. A full-image presentation includes only methods with a safe exact-image/exact-mask contract. Template Match, Point Region Grow, Feature Match, Before/After Diff, Align To Reference, Target Track (KLT) and Visual ReID require a reference, click, timeline or other context and are therefore not shown there.

Что меняет режим программыWhat the program mode changes

  • General: 28 общих методов и 14 pipeline-узлов образуют нейтральный image-analysis каталог.the 28 shared methods and 14 pipeline nodes form the neutral image-analysis catalog.
  • GUI Automation: использует общие CV-возможности и добавляет GUI-типы, markup refs, review draft и promotion patch. Это semantic/authoring layer, а не ещё 42 отдельных метода.uses the shared CV capabilities and adds GUI types, markup refs, a review draft and a promotion patch. This is a semantic/authoring layer, not another 42 separate methods.
  • Industrial / UAV: имеют собственные pipeline-операции, но их каталоги смешивают CV, preprocessing, orchestration, decisions и export nodes. Эти workspace экспериментальны, поэтому число зарегистрированных шагов не следует читать как число production-ready алгоритмов.have mode-specific pipeline operations, but their catalogs mix CV, preprocessing, orchestration, decisions and export nodes. These workspaces are experimental, so the registered-step count must not be read as a count of production-ready algorithms.

7. Линейный pipeline 7. Linear Pipeline

Линейный pipeline удобен, когда вам нужен предсказуемый поток без ветвлений: например, сначала выделить границы, потом очистить маску, потом извлечь контуры. Он проще для быстрого старта и легче переносится между проектами. The linear pipeline is the best option when you need a predictable flow without branching: for example, detect edges, clean the mask, then extract contours. It is easier to learn and easier to reuse across projects.

  • Каждый шаг исполняется сверху вниз. Each step runs from top to bottom.
  • Вы редактируете параметры одного шага за раз. You edit one step at a time.
  • Панель preview шагов помогает понять, на каком этапе появился шум или потерялся объект. Step previews help you see where noise appeared or where an object was lost.
  • Если цепочка остаётся линейной, её легко поддерживать и потом переносить в advanced mode. If the chain stays linear, it is easy to maintain and later move into advanced mode.

8. Расширенный pipeline: подробное руководство 8. Advanced Pipeline: Detailed Guide

Расширенный pipeline предназначен для сложных сценариев, где обычной линейной цепочки уже недостаточно. Он позволяет строить полноценный граф обработки: использовать несколько веток, объединять результаты, держать отдельный preview-выход и смотреть runtime-трассу по шагам. The advanced pipeline is designed for scenarios where a simple linear chain is no longer enough. It lets you build a full processing graph: split into branches, merge results, keep a dedicated preview output, and inspect the runtime trace step by step.

Когда переходить в расширенный режим When to Switch to Advanced Mode

  • Нужно сравнить две разные ветки обработки одной и той же картинки. You need to compare two different branches for the same image.
  • Нужно выбрать один из вариантов по условию. You need to choose between variants conditionally.
  • Нужно отдельно управлять результатом и предпросмотром. You want to control the final result and the preview separately.
  • Нужен runtime inspector, чтобы видеть payload каждого узла и каждой связи. You need the runtime inspector to see the payload of each node and connection.

Важно:Important: расширенный режим экспериментальный. Пока у него свой draft-состояние, а линейный pipeline остаётся основным форматом, пока вы явно не примените обратно exportable graph. the advanced mode is still experimental. It keeps its own draft state, while the linear pipeline remains the main format until you explicitly apply an exportable graph back.

Структура экрана advanced pipeline Advanced Pipeline Screen Layout

  • Верхняя панель действийTop Action Bar: быстрые операции вроде Quick Add, Snippets, Auto Layout, Repair Graph, Apply to Linear. quick actions like Quick Add, Snippets, Auto Layout, Repair Graph, Apply to Linear.
  • Холст графаGraph Canvas: основная рабочая область с узлами, связями, комментариями и группами. the main editing area with nodes, connections, comments, and groups.
  • Правая колонка инспекторовRight-side Inspectors: сведения о выбранном объекте, payload, pinned inspector и selection preview. information about the selected item, payload, pinned inspector, and selection preview.
  • Runtime debug областьRuntime Debug Area: история выполнения, scrubber по шагам, diff, pinned runtime step и preview истории. execution history, step scrubber, diff, pinned runtime step, and preview history.
  • Validation / Search / RecommendationsValidation / Search / Recommendations: быстрый переход к проблемам, поиск по графу и рекомендации по исправлению. jump to issues, search the graph, and follow suggested fixes.

Типы узлов Node Types

  • SourceSource: входное изображение, point prompt, константы. input image, point prompt, constants.
  • MethodMethod: реальные CV-методы: edge detection, segmentation, OCR, contour extraction и т.д. actual CV methods: edge detection, segmentation, OCR, contour extraction, and so on.
  • ControlControl: условные узлы и merge для выбора или объединения веток. conditional nodes and merge nodes used to choose or combine branches.
  • UtilityUtility: технические узлы вроде reroute, чтобы сделать граф чище. helper nodes such as reroute nodes to keep the graph readable.
  • SinkSink: финальные точки вывода результата и preview. final output targets for result and preview.

В типичном графе всегда присутствуют как минимум Input Image и Result Output. Они задают начало и явную конечную точку потока. Если в графе несколько веток и нет явного result output, runtime может посчитать конфигурацию неоднозначной. A typical graph always includes at least Input Image and Result Output. They define the start and the explicit end of the flow. If your graph has multiple branches and no explicit result output, the runtime may treat it as ambiguous.

Как собирать граф на практике How to Build a Graph in Practice

  1. Откройте вкладку Advanced рядом с линейным редактором. Open the Advanced tab next to the linear editor.
  2. Добавьте узлы через Quick Add или кнопку Add Node. Add nodes via Quick Add or the Add Node button.
  3. Соединяйте порты перетаскиванием от выхода к совместимому входу. Connect ports by dragging from an output to a compatible input.
  4. Если граф разрастается, используйте reroute и comment/group frames. If the graph becomes large, use reroute nodes and comment/group frames.
  5. Для сложного ветвления вставляйте If и Merge узлы. For branching logic, insert If and Merge nodes.
  6. После изменений проверяйте validation panel и summary справа. After editing, check the validation panel and summary on the right.

Рекомендуемый стартовый паттерн:Recommended starter pattern: `Input Image -> один-два method nodes -> Result Output`. Сначала убедитесь, что этот скелет работает, и только потом добавляйте ветвление, merge и отдельный preview sink. `Input Image -> one or two method nodes -> Result Output`. First make sure this skeleton works, then add branching, merge nodes, and a separate preview sink.

Редактирование и навигация Editing and Navigation

  • Delete удаляет выбранные узлы, связи или группы. Delete removes selected nodes, connections, or groups.
  • F2 переименовывает выбранный узел. F2 renames the selected node.
  • Ctrl+D дублирует выделение. Ctrl+D duplicates the current selection.
  • Tab или Space открывают Quick Add. Tab or Space opens Quick Add.
  • A запускает auto layout. A runs auto layout.
  • Ctrl+0 подгоняет масштаб под граф. Ctrl+0 fits the graph into view.

Runtime inspector: как читать выполнение графа Runtime Inspector: How to Read Graph Execution

После запуска обработки расширенный pipeline сохраняет runtime-снимок. Он показывает не только итоговую картинку, но и то, что происходило в каждом узле: какие входы были доступны, что узел вернул, какая ветка условия была выбрана, и где появился warning или error. After execution, the advanced pipeline stores a runtime snapshot. It shows not only the final image but also what happened in each node: which inputs were available, what the node returned, which branch was selected, and where warnings or errors appeared.

  • Runtime scrubberRuntime scrubber: переход между полным видом и отдельными runtime-шагами. switch between the full view and individual runtime steps.
  • Current / Pinned stepCurrent / Pinned step: удобно сравнивать два состояния графа или две ветки выполнения. useful for comparing two states or two execution branches.
  • Selection previewSelection preview: показывает preview именно выбранного узла или связи. shows the preview for the selected node or edge.
  • Payload inspectorPayload inspector: помогает понять, какой тип данных идёт по связи: image, mask, contours, detections, text. helps you understand what kind of payload flows through a connection: image, mask, contours, detections, or text.

Горячие клавиши runtime:Runtime shortcuts: `Alt+Home` — к началу трассы, `Alt+Left/Right` — шаг назад/вперёд, `Alt+End` — полный вид. `Alt+Home` jumps to the beginning of the trace, `Alt+Left/Right` moves backward/forward, and `Alt+End` returns to the full view.

Draft, синхронизация и применение к линейному pipeline Drafts, Sync, and Applying Back to Linear

У advanced mode есть собственное состояние редактирования. Пока граф содержит ветвления, utility/control узлы или другие нелинейные конструкции, он может оставаться только advanced draft. Если же конфигурация остаётся linearly exportable, вы можете нажать Apply to Linear и вернуть её в обычный линейный pipeline. Advanced mode has its own editable draft state. As long as the graph contains branching, utility/control nodes, or other non-linear structures, it may remain an advanced-only draft. If the configuration stays linearly exportable, you can press Apply to Linear and convert it back to the regular linear pipeline.

  • Resync from Linear перезагружает граф из текущего линейного pipeline. Resync from Linear rebuilds the graph from the current linear pipeline.
  • Apply to Linear записывает graph обратно в линейный формат, если это возможно. Apply to Linear writes the graph back into the linear format when possible.
  • Repair Graph предлагает безопасные исправления, если структура неполная или сломана. Repair Graph suggests safe fixes when the structure is incomplete or broken.

9. Советы по производительности 9. Performance Tips

  • Для тяжёлых графов выключайте live preview и запускайте Apply вручную. For heavy graphs, turn off live preview and run Apply manually.
  • Ограничивайте ROI перед сложной обработкой, если не нужен весь экран. Limit the ROI before running heavy processing if you do not need the full screen.
  • Используйте reroute и comment frames, чтобы не превращать граф в трудно читаемую “паутину”. Use reroute nodes and comment frames to avoid turning the graph into unreadable spaghetti.
  • После крупных перестроений делайте Auto Layout и проверяйте validation summary. After major changes, run Auto Layout and check the validation summary.

10. Частые проблемы и что делать 10. Common Problems and What to Do

  • Preview пустойPreview is empty: проверьте, что граф заканчивается в Result Output или Preview sink и что у узлов есть совместимые входы. make sure the graph ends in Result Output or a Preview sink and that nodes receive compatible inputs.
  • Граф не применяется к linearGraph cannot be applied back to linear: обычно причина в ветвлении, merge, utility/control nodes или другом нелинейном фрагменте. the usual reason is branching, merge nodes, utility/control nodes, or another non-linear fragment.
  • Слишком много шумаToo much noise: уменьшите ROI, добавьте фильтрацию маски или разбейте задачу на несколько шагов вместо одного универсального метода. reduce the ROI, add mask cleanup, or split the task into several steps instead of using one generic method.
  • Результат нестабилен между кадрамиThe result is unstable across frames: зафиксируйте область, уменьшите количество веток и проверяйте runtime trace по шагам, а не только итоговый preview. lock the area, reduce the number of branches, and inspect the runtime trace step by step instead of looking only at the final preview.

← Вернуться к оглавлению документации ← Back to Documentation Index