Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,7 @@ set(TARGET_OPENCV_SOURCES
if(DEPTHAI_HAVE_OPENCV_STITCHING)
list(APPEND TARGET_OPENCV_SOURCES
src/pipeline/utilities/Stitching/Stitching.cpp
src/pipeline/utilities/Stitching/FixedBlender.cpp
src/pipeline/utilities/Stitching/FixedPanoramaCompositor.cpp
src/pipeline/utilities/Stitching/PlanarStitcher.cpp
)
Expand Down
2 changes: 1 addition & 1 deletion examples/cpp/HostNodes/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ render onto.

Where inputs overlap, `setSeamFinder()` picks how the seam is found. `SeamFinder::NONE` copies the inputs in order and
is the fastest; any other value (`VORONOI`, `DP_COLOR`, `DP_COLOR_GRAD`, `GRAPHCUT_COLOR` (default),
`GRAPHCUT_COLOR_GRAD`) also enables exposure compensation and multiband blending. `setMaxPanoramaSize()` bounds the
`GRAPHCUT_COLOR_GRAD`) also enables exposure compensation and blending. `setMaxPanoramaSize()` bounds the
canvas.

### Planar projection (`stitching_planar_projection.cpp`)
Expand Down
2 changes: 1 addition & 1 deletion examples/python/HostNodes/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ render onto.

Where inputs overlap, `setSeamFinder()` picks how the seam is found. `SeamFinder.NONE` copies the inputs in order and is
the fastest; any other value (`VORONOI`, `DP_COLOR`, `DP_COLOR_GRAD`, `GRAPHCUT_COLOR` (default), `GRAPHCUT_COLOR_GRAD`)
also enables exposure compensation and multiband blending. `setMaxPanoramaSize()` bounds the canvas.
also enables exposure compensation and blending. `setMaxPanoramaSize()` bounds the canvas.

### Planar projection (`stitching_planar_projection.py`)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
parser.add_argument("--projection", choices=["Perspective", "Equirectangular", "Cylindrical"], default="Cylindrical")
parser.add_argument("--average", action="store_true", help="Average duplicate boxes and union their masks instead of NMS")
parser.add_argument("--blend", action=argparse.BooleanOptionalAction, default=True,
help="Enable exposure compensation and multiband blending (default: on; --no-blend is faster)")
help="Enable exposure compensation and blending (default: on; --no-blend is faster)")
parser.add_argument("--panorama-scale", type=int, choices=range(1, 5), default=2,
help="Stitching resolution multiplier for 640x400 camera views (default: 2)")
parser.add_argument("--sync-threshold-ms", type=int, default=1000 // FPS,
Expand Down
7 changes: 4 additions & 3 deletions include/depthai/pipeline/node/Stitching.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ class Stitching : public DeviceNodeCRTP<DeviceNode, Stitching, StitchingProperti
* Nonzero pixels identify each source's seam region, or the pixels retained after direct copying in input order.
* Linked outputs emit once when the composition is prepared, and again after it is reset. Available on the host
* in PANORAMA mode with input calibration. Link to ImgDetectionsFilter.inputSourceMasks using the detection key
* for the corresponding camera. Multiband blending can mix sources near seams beyond these regions.
* for the corresponding camera. Blending can mix sources near seams beyond these regions.
*/
OutputMap outSourceMasks{*this, "outSourceMasks", {DEFAULT_NAME, DEFAULT_GROUP, {{{DatatypeEnum::ImgFrame, false}}}}};

Expand Down Expand Up @@ -216,7 +216,8 @@ class Stitching : public DeviceNodeCRTP<DeviceNode, Stitching, StitchingProperti
* camera Y axis as the cylinder axis. When enabled, panorama composition starts from the first synchronized group
* without feature matching or bundle adjustment. With `SeamFinder::NONE`, warped inputs are copied in order and
* later inputs replace earlier ones in overlapping regions. Other seam finders enable seam estimation, exposure
* compensation, and multiband blending. The prepared composition is reused for subsequent groups. Only undistorted
* compensation, and blending. The prepared composition is reused for subsequent groups, while the exposure gains keep
* following the overlaps of the incoming groups. Only undistorted
* inputs are accepted. Only used in `Mode::PANORAMA`.
*/
void setUseInputCalibration(bool useInputCalibration);
Expand Down Expand Up @@ -266,7 +267,7 @@ class Stitching : public DeviceNodeCRTP<DeviceNode, Stitching, StitchingProperti

/**
* Set the panorama seam finder. In calibrated panorama mode, `NONE` selects direct composition; other values also
* enable exposure compensation and multiband blending.
* enable exposure compensation and blending.
*/
void setSeamFinder(SeamFinder finder);
SeamFinder getSeamFinder() const;
Expand Down
341 changes: 341 additions & 0 deletions src/pipeline/utilities/Stitching/FixedBlender.cpp

Large diffs are not rendered by default.

70 changes: 70 additions & 0 deletions src/pipeline/utilities/Stitching/FixedBlender.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#pragma once

#include <opencv2/core.hpp>
#include <opencv2/stitching/detail/seam_finders.hpp>
#include <vector>

namespace dai {
namespace utilities {

class FixedBlender {
public:
struct Source {
cv::Point tl;
cv::Mat mask;
cv::Mat seamMask;
cv::Scalar gain{1.0, 1.0, 1.0, 1.0};
cv::Mat map1;
cv::Mat map2;
};

void prepare(const cv::Rect& canvas, const std::vector<Source>& sources, int bandWidth, int borderMode);

std::vector<cv::Mat> prepareBlended(const cv::Rect& canvas,
std::vector<Source> sources,
const std::vector<cv::Mat>& images,
cv::detail::SeamFinder& finder,
double seamResolution,
int borderMode);

cv::Mat blend(const std::vector<cv::Mat>& images); // Also moves the exposure gains toward this group's overlaps

private:
struct Part {
size_t piece;
cv::Rect rect;
cv::Mat weight;
};
struct Strip {
cv::Rect rect;
cv::Mat mask;
std::vector<Part> parts;
};
struct Piece {
size_t source;
cv::Rect used;
cv::Mat own;
cv::Mat map1;
cv::Mat map2;
};
struct OverlapSamples {
size_t first;
size_t second;
double pixels;
std::vector<cv::Point> inFirst;
std::vector<cv::Point> inSecond;
};

void updateGains(const std::vector<cv::Mat>& images, double rate);

cv::Rect canvas;
size_t sourceCount = 0;
int borderMode = cv::BORDER_CONSTANT;
std::vector<Piece> pieces;
std::vector<Strip> strips;
std::vector<cv::Scalar> gains;
std::vector<OverlapSamples> overlapSamples;
};

} // namespace utilities
} // namespace dai
122 changes: 30 additions & 92 deletions src/pipeline/utilities/Stitching/FixedPanoramaCompositor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ void FixedPanoramaCompositor::reset() {
warperScale = 0.0;
canvas = {};
sources.clear();
compensator.release();
blender.release();
blender = FixedBlender{};
}

bool FixedPanoramaCompositor::isPrepared() const {
Expand All @@ -48,14 +47,7 @@ cv::Mat FixedPanoramaCompositor::getSourceMask(size_t sourceIndex) const {
DAI_CHECK_V(prepared && sourceIndex < sources.size(), "The fixed panorama source {} is unavailable", sourceIndex);
cv::Mat mask = cv::Mat::zeros(canvas.size(), CV_8U);
const auto& source = sources[sourceIndex];
const auto& region = config.composition == Composition::BLENDED ? source.seamMask : source.mask;
region.copyTo(mask(cv::Rect(source.roi.tl() - canvas.tl(), region.size())));
if(config.composition == Composition::DIRECT) {
for(size_t i = sourceIndex + 1; i < sources.size(); ++i) {
const auto& later = sources[i];
mask(cv::Rect(later.roi.tl() - canvas.tl(), later.mask.size())).setTo(0, later.mask);
}
}
source.seamMask.copyTo(mask(cv::Rect(source.roi.tl() - canvas.tl(), source.seamMask.size())));
return mask;
}

Expand All @@ -81,6 +73,7 @@ void FixedPanoramaCompositor::prepare(const std::vector<cv::Mat>& images, const
auto warper = stitching::createWarper(config.cameraModel)->create(static_cast<float>(warperScale));

sources.reserve(images.size());
std::vector<FixedBlender::Source> blendSources(images.size());
for(size_t i = 0; i < images.size(); ++i) {
DAI_CHECK_V(!images[i].empty(), "Panorama input {} is empty", i);

Expand All @@ -101,27 +94,43 @@ void FixedPanoramaCompositor::prepare(const std::vector<cv::Mat>& images, const
source.roi.width = mapX.cols;
source.roi.height = mapX.rows;

auto& blendSource = blendSources[i];
blendSource.tl = source.roi.tl();
const cv::Mat inputMask(source.composeInputSize, CV_8U, cv::Scalar::all(255));
cv::remap(inputMask, source.mask, mapX, mapY, cv::INTER_NEAREST, cv::BORDER_CONSTANT);
cv::convertMaps(mapX, mapY, source.map1, source.map2, CV_16SC2);
cv::remap(inputMask, blendSource.mask, mapX, mapY, cv::INTER_NEAREST, cv::BORDER_CONSTANT);
cv::convertMaps(mapX, mapY, blendSource.map1, blendSource.map2, CV_16SC2);

canvas = sources.empty() ? source.roi : canvas | source.roi;
sources.push_back(std::move(source));
}
DAI_CHECK_V(canvas.width > 0 && canvas.height > 0, "The registered panorama has an empty canvas");

if(config.composition == Composition::BLENDED) {
const auto warped = warp(images);
prepareCompositing(warped);
blender = stitching::createBlender(canvas.size());
const auto seamMasks = blender.prepareBlended(canvas,
std::move(blendSources),
composeInputs(images),
*stitching::createSeamFinder(config.seamFinder),
config.seamEstimationResolution,
cv::BORDER_REFLECT);
for(size_t i = 0; i < sources.size(); ++i) sources[i].seamMask = seamMasks[i];
} else {
cv::Mat later = cv::Mat::zeros(canvas.size(), CV_8U);
for(size_t i = sources.size(); i-- > 0;) {
auto& blendSource = blendSources[i];
const cv::Rect placed(blendSource.tl - canvas.tl(), blendSource.mask.size());
blendSource.seamMask = blendSource.mask & ~later(placed);
later(placed) |= blendSource.mask;
sources[i].seamMask = blendSource.seamMask;
}
blender.prepare(canvas, blendSources, 0, cv::BORDER_REFLECT);
}
prepared = true;
}

std::vector<cv::Mat> FixedPanoramaCompositor::warp(const std::vector<cv::Mat>& images) const {
std::vector<cv::Mat> FixedPanoramaCompositor::composeInputs(const std::vector<cv::Mat>& images) const {
DAI_CHECK_V(images.size() == sources.size(), "Expected {} panorama images, got {}", sources.size(), images.size());

std::vector<cv::Mat> warped(sources.size());
std::vector<cv::Mat> inputs(sources.size());
for(size_t i = 0; i < sources.size(); ++i) {
DAI_CHECK_V(images[i].size() == sources[i].inputSize,
"Panorama input {} changed its size from {}x{} to {}x{}",
Expand All @@ -130,89 +139,18 @@ std::vector<cv::Mat> FixedPanoramaCompositor::warp(const std::vector<cv::Mat>& i
sources[i].inputSize.height,
images[i].cols,
images[i].rows);
cv::Mat composeInput;
if(images[i].size() == sources[i].composeInputSize) {
composeInput = images[i];
inputs[i] = images[i];
} else {
cv::resize(images[i], composeInput, sources[i].composeInputSize, 0, 0, cv::INTER_LINEAR_EXACT);
cv::resize(images[i], inputs[i], sources[i].composeInputSize, 0, 0, cv::INTER_LINEAR_EXACT);
}
cv::remap(composeInput, warped[i], sources[i].map1, sources[i].map2, cv::INTER_LINEAR, cv::BORDER_REFLECT);
}
return warped;
}

void FixedPanoramaCompositor::prepareCompositing(const std::vector<cv::Mat>& warped) {
compensator = cv::detail::ExposureCompensator::createDefault(cv::detail::ExposureCompensator::GAIN_BLOCKS);

const double scale = config.seamEstimationResolution > 0.0
? std::min(1.0, std::sqrt(config.seamEstimationResolution * 1e6 / static_cast<double>(canvas.size().area())))
: 1.0;
std::vector<cv::Point> seamCorners;
std::vector<cv::UMat> seamImages;
std::vector<cv::UMat> seamMasks;
seamCorners.reserve(sources.size());
seamImages.reserve(sources.size());
seamMasks.reserve(sources.size());
for(size_t i = 0; i < sources.size(); ++i) {
cv::Mat image;
cv::Mat mask;
cv::resize(warped[i], image, cv::Size(), scale, scale, cv::INTER_LINEAR_EXACT);
cv::resize(sources[i].mask, mask, image.size(), 0, 0, cv::INTER_NEAREST);

seamCorners.emplace_back(static_cast<int>(std::lround(sources[i].roi.x * scale)), static_cast<int>(std::lround(sources[i].roi.y * scale)));
seamImages.push_back(image.getUMat(cv::ACCESS_READ));
seamMasks.push_back(mask.getUMat(cv::ACCESS_RW));
}

compensator->feed(seamCorners, seamImages, seamMasks);
for(auto& image : seamImages) {
cv::UMat converted;
image.convertTo(converted, CV_32F);
image = std::move(converted);
}
stitching::createSeamFinder(config.seamFinder)->find(seamImages, seamCorners, seamMasks);
for(size_t i = 0; i < sources.size(); ++i) {
cv::Mat seamMask;
cv::dilate(seamMasks[i].getMat(cv::ACCESS_READ), seamMask, cv::Mat());
cv::resize(seamMask, seamMask, sources[i].mask.size(), 0, 0, cv::INTER_LINEAR);
sources[i].seamMask = seamMask & sources[i].mask;
}
return inputs;
}

cv::Mat FixedPanoramaCompositor::compose(const std::vector<cv::Mat>& images) {
DAI_CHECK_V(prepared, "The fixed panorama compositor was not prepared yet");
const auto warped = warp(images);

if(config.composition == Composition::DIRECT) {
cv::Mat result = cv::Mat::zeros(canvas.size(), warped.front().type());
for(size_t i = 0; i < sources.size(); ++i) {
const cv::Point destination = sources[i].roi.tl() - canvas.tl();
warped[i].copyTo(result(cv::Rect(destination, warped[i].size())), sources[i].mask);
}
return result;
}

blender->prepare(canvas);
for(size_t i = 0; i < sources.size(); ++i) {
cv::Mat compensated = warped[i];
compensator->apply(static_cast<int>(i), sources[i].roi.tl(), compensated, sources[i].mask);

cv::Mat converted;
compensated.convertTo(converted, CV_16S);
blender->feed(converted, sources[i].seamMask, sources[i].roi.tl());
}

cv::Mat result;
cv::Mat resultMask;
blender->blend(result, resultMask);
result.convertTo(result, CV_8U);
DAI_CHECK_V(result.size() == canvas.size(),
"The fixed panorama blender returned {}x{}, expected the cached {}x{} canvas",
result.cols,
result.rows,
canvas.width,
canvas.height);
return result;
return blender.blend(composeInputs(images));
}

} // namespace utilities
Expand Down
12 changes: 3 additions & 9 deletions src/pipeline/utilities/Stitching/FixedPanoramaCompositor.hpp
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
#pragma once

#include <opencv2/core.hpp>
#include <opencv2/stitching/detail/blenders.hpp>
#include <opencv2/stitching/detail/exposure_compensate.hpp>
#include <opencv2/stitching/detail/motion_estimators.hpp>
#include <vector>

#include "FixedBlender.hpp"
#include "depthai/pipeline/node/Stitching.hpp"

namespace dai {
Expand Down Expand Up @@ -46,23 +45,18 @@ class FixedPanoramaCompositor {
cv::Size inputSize;
cv::Size composeInputSize;
cv::Rect roi;
cv::Mat map1;
cv::Mat map2;
cv::Mat mask;
cv::Mat seamMask;
};

std::vector<cv::Mat> warp(const std::vector<cv::Mat>& images) const;
void prepareCompositing(const std::vector<cv::Mat>& warped);
std::vector<cv::Mat> composeInputs(const std::vector<cv::Mat>& images) const;

Config config;
bool prepared = false;
double composeScale = 1.0;
double warperScale = 0.0;
cv::Rect canvas;
std::vector<Source> sources;
cv::Ptr<cv::detail::ExposureCompensator> compensator;
cv::Ptr<cv::detail::Blender> blender;
FixedBlender blender;
};

} // namespace utilities
Expand Down
Loading
Loading