The post has been translated automatically. Original language: Russian
For a foreign customer, we have developed a script that collects a single image of a microscopic sample from a video stream.
System:
- determines the position of the frames,
- tracks the trajectory of movement,
- reduces the visibility of seams,
- evens out the color
- and saves the result in GeoTIFF and DICOM formats.
The project shows a typical situation for applied computer vision: the input data is imperfect, the camera movement is unstable, the image is large, and the result should be suitable for further work, not just for demonstration.
Task
The customer needed to restore the functionality of the application, which previously allowed scanning a microscopic slide and obtaining an image of the entire area under study. The app was removed from the App Store, so the customer decided to implement a similar algorithm again.
The target scenario looked like this:
- the user connects the microscope camera or uses a mobile device,
- moves the sample under the camera, sees which areas have already been scanned,
- and when finished, it saves the image of the entire slide in the desired format.
The main task is to obtain a single image of the sample from the video stream so that the customer can use it for further analysis and research work.
Why was it different from the usual image gluing?
At first glance, the task resembles assembling a panorama: there are several frames, you need to find common areas and glue them into one image. But in microscopy, the conditions are noticeably more complicated.
The camera sees only a small portion of the sample. During movement, the frames may blur, the lighting changes, the image fragments look similar to each other, and individual areas contain almost no pronounced details. In addition, the resulting image is very large, so it is important to consider memory, storage format, and processing stability.
In this project, it was necessary to work not with perfect photos, but with a real video stream, where the frame quality, speed of movement and lighting can change right during shooting.

What have we done
We have developed a pipeline that turns a stream of frames from a microscope into a single map of the scanned area.
System:
- analyzes frames from a video stream;
- evaluates the offset between them;
- plots the trajectory of the camera relative to the sample;
- places frames on a common plane;
- reduces the visibility of seams between fragments;
- corrects differences in brightness and color rendering;
- saves the result to GeoTIFF and DICOM.
This approach allows you not only to glue several images together, but to restore the overall structure of the scanned area, even with uneven camera movement.
Why didn't the standard approach work?
In many computer vision tasks, images are combined through key points. The algorithm searches for characteristic details in neighboring frames, compares them, and calculates the offset.
This approach proved to be insufficiently reliable for microscopic images. There may be few stable landmarks in the frame, and different parts of the sample may look too similar. If the algorithm makes a mistake in matching, the frames begin to shift incorrectly, and the final image is distorted.
Therefore, we did not limit ourselves to the standard comparison of key points and tested alternative approaches to assessing movement between neighboring frames.
- The optical flow is better suited for more complex motion, but it was sensitive to blurring on our data. It allowed you to work at about 40 FPS and potentially take into account more complex movement, including sample rotation.
- Phase correlation estimated the frame shift faster and could work up to 200 FPS. However, it was applicable only for translational movements of the frame. This turned out to be an acceptable limitation for the chosen scenario. The strength of the correlation response made it possible to filter out highly blurred fragments and reduce the risk of errors in trajectory construction.
At this stage, this limitation was acceptable because the priority was a quick and steady assessment of the bias. Additionally, the magnitude of the correlation response helped to identify highly blurred frames and not use them to plot a trajectory.

How the problem of seams was solved
After placing the frames on a common plane, the following problem appears: neighboring fragments should look like a single image. If you simply superimpose them on top of each other, the borders, brightness differences and areas with different sharpness will be noticeable.
Standard image blending smoothed out the borders, but in this project it had an undesirable effect: the image became more blurred. This is critical for microscopy, because useful parts can be lost along with the seams.
We chose a different approach: to take pixels mainly from the central areas of the frames.
The central part of the frame usually suffers less from optical distortion, darkening at the edges, and loss of sharpness. This helped to reduce the visibility of the seams without unnecessarily blurring the final image.
The project also took into account the accumulation of errors and the alignment of personnel positions. If each subsequent frame is placed only relative to the previous one, small errors gradually accumulate and become noticeable on a large map.
Therefore, the pipeline used global optimization of the frame position. We experimented with defocus processing and blur removal separately, but these solutions were not included in the final release.
How the color was aligned
The brightness and color rendering may have changed during shooting. Because of this, the neighboring areas of the final image looked different: somewhere the area is lighter, somewhere darker, and somewhere the hue changes.

We've added color correction to make the final map visually smoother. The algorithm analyzed the differences between neighboring areas and corrected the color shifts.
This helped to reduce the differences at the borders and get a more complete image. This is important for a research scenario: the final file should be convenient not only for storage, but also for further viewing and analysis.
Result
As a result, the customer received a script for assembling a single image of a microscopic sample from a video stream. The solution allows you to:
- work with frames from the microscope camera;
- Track movement and interruptions;
- localize frames on a common plane;
- save the trajectory of movement;
- assemble a large image from individual fragments;
- reduce the visibility of seams;
- align the color between the sections;
- save the result in GeoTIFF and DICOM.
For the customer, this has become a tool that helps to obtain images of samples and use them in further research work.
Conclusions
This case shows well how application development works in computer vision.
In a real problem, it's not enough to take a ready-made algorithm and apply it to the data. It is necessary to take into account the quality of the input video stream, camera movement features, similarity of fragments, low contrast, optical distortion, memory limitations and requirements for the result format.
For us, it was a project at the intersection of computer vision, image processing, and research tools.
Such tasks are important not only for microscopy: similar approaches are applicable where it is necessary to assemble a large image or map from individual frames — in medicine, industrial inspection, laboratory research, robotics and other scenarios of working with a video stream.
The main value of the project is not in one specific algorithm, but in a stable pipeline that is adapted to the real data and workflow of the customer.

Для зарубежного заказчика мы разработали скрипт, который собирает единое изображение микроскопического образца из видеопотока.
Система:
- определяет положение кадров,
- отслеживает траекторию движения,
- уменьшает видимость швов,
- выравнивает цвет
- и сохраняет результат в форматах GeoTIFF и DICOM.
Проект показывает типичную для прикладного компьютерного зрения ситуацию: входные данные неидеальны, движение камеры нестабильно, изображение большое, и результат должен быть пригоден для дальнейшей работы, а не только для демонстрации.
Задача
Заказчику нужно было восстановить функциональность приложения, которое раньше позволяло сканировать микроскопический слайд и получать изображение всей исследуемой области. Приложение было удалено из App Store, поэтому заказчик решил реализовать похожий алгоритм заново.
Целевой сценарий выглядел так:
- пользователь подключает камеру микроскопа или использует мобильное устройство,
- перемещает образец под камерой, видит, какие участки уже отсканированы,
- а после завершения сохраняет изображение всего слайда в нужном формате.
Главная задача — получить единое изображение образца из видеопотока, чтобы заказчик мог использовать его для дальнейшего анализа и исследовательской работы.
Почему это было не похоже на обычную склейку изображений
На первый взгляд задача напоминает сборку панорамы: есть несколько кадров, нужно найти общие области и склеить их в одно изображение. Но в микроскопии условия заметно сложнее.
Камера видит только небольшой участок образца. Во время движения кадры могут смазываться, освещение меняется, фрагменты изображения похожи друг на друга, а отдельные области почти не содержат выраженных деталей. Кроме того, итоговое изображение получается очень большим, поэтому важно учитывать память, формат хранения и стабильность обработки.
В этом проекте нужно было работать не с идеальными фотографиями, а с реальным видеопотоком, где качество кадров, скорость движения и освещение могут меняться прямо во время съёмки.

Что мы сделали
Мы разработали пайплайн, который превращает поток кадров с микроскопа в единую карту просканированной области.
Система:
- анализирует кадры из видеопотока;
- оценивает смещение между ними;
- строит траекторию движения камеры относительно образца;
- размещает кадры на общей плоскости;
- уменьшает видимость швов между фрагментами;
- корректирует различия в яркости и цветопередаче;
- сохраняет результат в GeoTIFF и DICOM.
Такой подход позволяет не просто склеить несколько изображений, а восстановить общую структуру просканированной области даже при неравномерном движении камеры.
Почему стандартный подход не подошёл
Во многих задачах компьютерного зрения изображения совмещают через ключевые точки. Алгоритм ищет характерные детали на соседних кадрах, сопоставляет их и вычисляет смещение.
Для микроскопических изображений этот подход оказался недостаточно надёжным. В кадре может быть мало устойчивых ориентиров, а разные участки образца могут выглядеть слишком похожими. Если алгоритм ошибается в сопоставлении, кадры начинают смещаться неправильно, а итоговое изображение собирается с искажениями.
Поэтому мы не стали ограничиваться стандартным сопоставлением ключевых точек и проверили альтернативные подходы к оценке движения между соседними кадрами.
- Оптический поток лучше подходит для более сложного движения, но на наших данных был чувствителен к размытию. Он позволял работать примерно на 40 FPS и потенциально учитывать более сложное движение, включая вращение образца.
- Фазовая корреляция быстрее оценивала сдвиг кадра и могла работать до 200 FPS. При этом она была применима только для поступательных перемещений кадра. Для выбранного сценария это оказалось приемлемым ограничением. Сила корреляционного отклика позволяла отфильтровывать сильно размытые фрагменты и снижать риск ошибок при построении траектории.
На данном этапе это ограничение было приемлемым, потому что приоритетом была быстрая и устойчивая оценка смещения. Дополнительно величина корреляционного отклика помогала выявлять сильно размытые кадры и не использовать их для построения траектории.

Как решали проблему швов
После размещения кадров на общей плоскости появляется следующая проблема: соседние фрагменты должны выглядеть как единое изображение. Если просто наложить их друг на друга, будут заметны границы, перепады яркости и участки с разной резкостью.
Стандартное смешивание изображений сглаживало границы, но в этом проекте давало нежелательный эффект: изображение становилось более смазанным. Для микроскопии это критично, потому что вместе со швами можно потерять полезные детали.
Мы выбрали другой подход: брать пиксели преимущественно из центральных областей кадров.
Центральная часть кадра обычно меньше страдает от оптических искажений, потемнения по краям и падения резкости. Это помогло уменьшить видимость швов без лишнего размытия итогового изображения.
В проекте также учитывались накопление ошибок и согласование положения кадров. Если каждый следующий кадр размещать только относительно предыдущего, небольшие ошибки постепенно накапливаются и становятся заметны на большой карте.
Поэтому в пайплайне использовалась глобальная оптимизация положения кадров. Отдельно экспериментировали с обработкой дефокуса и устранением размытия, но эти решения не вошли в финальный релиз.
Как выравнивали цвет
Во время съёмки яркость и цветопередача могли меняться. Из-за этого соседние участки итогового изображения выглядели неодинаково: где-то область светлее, где-то темнее, где-то меняется оттенок.

Мы добавили цветокоррекцию, чтобы сделать итоговую карту визуально более ровной. Алгоритм анализировал различия между соседними областями и корректировал цветовые сдвиги.
Это помогало уменьшить перепады на границах и получить более цельное изображение. Для исследовательского сценария это важно: итоговый файл должен быть удобен не только для хранения, но и для дальнейшего просмотра и анализа.
Результат
В результате заказчик получил скрипт для сборки цельного изображения микроскопического образца из видеопотока. Решение позволяет:
- работать с кадрами с камеры микроскопа;
- отслеживать движение и прерывания;
- локализовать кадры на общей плоскости;
- сохранять траекторию движения;
- собирать большое изображение из отдельных фрагментов;
- снижать видимость швов;
- выравнивать цвет между участками;
- сохранять результат в GeoTIFF и DICOM.
Для заказчика это стало инструментом, который помогает получать изображения образцов и использовать их в дальнейшей исследовательской работе.
Выводы
Этот кейс хорошо показывает, как устроена прикладная разработка в компьютерном зрении.
В реальной задаче недостаточно взять готовый алгоритм и применить его к данным. Нужно учитывать качество входного видеопотока, особенности движения камеры, схожесть фрагментов, слабую контрастность, оптические искажения, ограничения по памяти и требования к формату результата.
Для нас это был проект на стыке компьютерного зрения, обработки изображений и исследовательских инструментов
Такие задачи важны не только для микроскопии: похожие подходы применимы там, где нужно собирать большое изображение или карту из отдельных кадров — в медицине, промышленной инспекции, лабораторных исследованиях, робототехнике и других сценариях работы с видеопотоком.
Главная ценность проекта — не в одном конкретном алгоритме, а в устойчивом пайплайне, который адаптирован под реальные данные и рабочий процесс заказчика.
