diff --git a/CMakeLists.txt b/CMakeLists.txt index 02dc5e9fd5..c88db8b0be 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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 ) diff --git a/examples/cpp/HostNodes/README.md b/examples/cpp/HostNodes/README.md index dda9d817c5..7f22b1c2d7 100644 --- a/examples/cpp/HostNodes/README.md +++ b/examples/cpp/HostNodes/README.md @@ -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`) diff --git a/examples/python/HostNodes/README.md b/examples/python/HostNodes/README.md index 986a2772d6..91508616cb 100644 --- a/examples/python/HostNodes/README.md +++ b/examples/python/HostNodes/README.md @@ -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`) diff --git a/examples/python/MultiDevice/multi_device_detections_panorama.py b/examples/python/MultiDevice/multi_device_detections_panorama.py index 0cf93b6b86..38a796ac14 100644 --- a/examples/python/MultiDevice/multi_device_detections_panorama.py +++ b/examples/python/MultiDevice/multi_device_detections_panorama.py @@ -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, diff --git a/include/depthai/pipeline/node/Stitching.hpp b/include/depthai/pipeline/node/Stitching.hpp index 075133b1c9..72483c4437 100644 --- a/include/depthai/pipeline/node/Stitching.hpp +++ b/include/depthai/pipeline/node/Stitching.hpp @@ -107,7 +107,7 @@ class Stitching : public DeviceNodeCRTP +#include +#include + +#include "StitchingCompositing.hpp" +#include "utility/ErrorMacros.hpp" + +namespace dai { +namespace utilities { + +namespace { + +constexpr float MIN_WEIGHT = 1.0f / 256.0f; +constexpr int STRIP_ROWS = 32; +constexpr int MIN_PIECE_GAP = 32; + +std::vector pieceColumns(const cv::Mat& used) { + cv::Mat columns; + cv::reduce(used, columns, 0, cv::REDUCE_MAX); + std::vector ranges; + int begin = -1; + int lastUsed = -1; + for(int x = 0; x < columns.cols; ++x) { + if(columns.at(0, x) == 0) continue; + if(begin < 0) { + begin = x; + } else if(x - lastUsed > MIN_PIECE_GAP) { + ranges.emplace_back(begin, lastUsed + 1); + begin = x; + } + lastUsed = x; + } + if(begin >= 0) ranges.emplace_back(begin, lastUsed + 1); + return ranges; +} + +constexpr int OVERLAP_SAMPLES = 4096; +constexpr int MIN_OVERLAP_SAMPLES = 16; +constexpr int SATURATED = 250; +constexpr double GAIN_UPDATE_RATE = 0.1; + +struct Overlap { + size_t i; + size_t j; + double pixels; + cv::Scalar meanI; + cv::Scalar meanJ; +}; + +std::vector solveChannelGains(const std::vector& overlaps, int count) { + constexpr double PRIOR = 1e-3; + const int rows = static_cast(overlaps.size()); + double total = 1.0; + for(const auto& overlap : overlaps) total += std::sqrt(overlap.pixels); + std::vector gains(count, cv::Scalar(1.0, 1.0, 1.0, 1.0)); + for(int channel = 0; channel < 3; ++channel) { + cv::Mat A = cv::Mat::zeros(rows + count + 1, count, CV_64F); + cv::Mat b = cv::Mat::zeros(A.rows, 1, CV_64F); + for(int r = 0; r < rows; ++r) { + const auto& overlap = overlaps[r]; + const double weight = std::sqrt(overlap.pixels) / std::max(1.0, 0.5 * (overlap.meanI[channel] + overlap.meanJ[channel])); + A.at(r, static_cast(overlap.i)) = weight * overlap.meanI[channel]; + A.at(r, static_cast(overlap.j)) = -weight * overlap.meanJ[channel]; + } + for(int i = 0; i < count; ++i) { + A.at(rows + i, i) = PRIOR * total; + b.at(rows + i) = PRIOR * total; + } + A.row(A.rows - 1).setTo(total); + b.at(A.rows - 1) = total * count; + cv::Mat solution; + cv::solve(A, b, solution, cv::DECOMP_SVD); + for(int i = 0; i < count; ++i) gains[i][channel] = std::clamp(solution.at(i), 0.5, 2.0); + } + return gains; +} + +cv::Point sampledFrom(const FixedBlender::Source& source, const cv::Point& warped) { + if(source.map1.type() == CV_16SC2) { + const auto& value = source.map1.at(warped); + return {value[0], value[1]}; + } + if(source.map1.type() == CV_32FC2) { + const auto& value = source.map1.at(warped); + return {cvRound(value[0]), cvRound(value[1])}; + } + return {cvRound(source.map1.at(warped)), cvRound(source.map2.at(warped))}; +} + +std::vector findSeamMasks(const cv::Size& canvas, + const std::vector& corners, + const std::vector& images, + const std::vector& masks, + cv::detail::SeamFinder& finder, + double megapixels) { + const double scale = megapixels > 0.0 ? std::min(1.0, std::sqrt(megapixels * 1e6 / static_cast(canvas.area()))) : 1.0; + std::vector seamCorners; + std::vector seamImages; + std::vector seamMasks; + for(size_t i = 0; i < images.size(); ++i) { + const cv::Size size(std::max(1, static_cast(std::lround(images[i].cols * scale))), + std::max(1, static_cast(std::lround(images[i].rows * scale)))); + cv::Mat image; + cv::Mat mask; + cv::resize(images[i], image, size, 0, 0, cv::INTER_LINEAR_EXACT); + cv::resize(masks[i], mask, size, 0, 0, cv::INTER_NEAREST); + image.convertTo(image, CV_32F); + seamCorners.emplace_back(static_cast(std::lround(corners[i].x * scale)), static_cast(std::lround(corners[i].y * scale))); + seamImages.push_back(image.getUMat(cv::ACCESS_READ)); + seamMasks.push_back(mask.getUMat(cv::ACCESS_RW)); + } + finder.find(seamImages, seamCorners, seamMasks); + + std::vector result; + result.reserve(images.size()); + for(size_t i = 0; i < images.size(); ++i) { + cv::Mat seamMask; + cv::dilate(seamMasks[i].getMat(cv::ACCESS_READ), seamMask, cv::Mat()); + cv::resize(seamMask, seamMask, masks[i].size(), 0, 0, cv::INTER_LINEAR); + result.push_back(seamMask & masks[i]); + } + return result; +} + +} // namespace + +void FixedBlender::updateGains(const std::vector& images, double rate) { + if(overlapSamples.empty()) return; + std::vector overlaps; + overlaps.reserve(overlapSamples.size()); + for(const auto& samples : overlapSamples) { + const cv::Mat& first = images[samples.first]; + const cv::Mat& second = images[samples.second]; + cv::Vec3d sumFirst(0.0, 0.0, 0.0); + cv::Vec3d sumSecond(0.0, 0.0, 0.0); + int used = 0; + for(size_t k = 0; k < samples.inFirst.size(); ++k) { + const auto& a = first.at(std::clamp(samples.inFirst[k].y, 0, first.rows - 1), std::clamp(samples.inFirst[k].x, 0, first.cols - 1)); + const auto& b = second.at(std::clamp(samples.inSecond[k].y, 0, second.rows - 1), std::clamp(samples.inSecond[k].x, 0, second.cols - 1)); + if(std::max({a[0], a[1], a[2], b[0], b[1], b[2]}) >= SATURATED) continue; // Clipped: no exposure ratio + sumFirst += cv::Vec3d(a[0], a[1], a[2]); + sumSecond += cv::Vec3d(b[0], b[1], b[2]); + ++used; + } + if(used < MIN_OVERLAP_SAMPLES) continue; + overlaps.push_back({samples.first, samples.second, samples.pixels, cv::Scalar(sumFirst / used), cv::Scalar(sumSecond / used)}); + } + if(overlaps.empty()) return; // e.g. every overlap clipped: keep the gains + const auto target = solveChannelGains(overlaps, static_cast(sourceCount)); + for(size_t i = 0; i < gains.size(); ++i) { + for(int channel = 0; channel < 3; ++channel) gains[i][channel] += rate * (target[i][channel] - gains[i][channel]); + } +} + +std::vector FixedBlender::prepareBlended(const cv::Rect& canvasRect, + std::vector sources, + const std::vector& images, + cv::detail::SeamFinder& finder, + double seamResolution, + int border) { + DAI_CHECK_V(images.size() == sources.size(), "Expected {} images to prepare the blender, got {}", sources.size(), images.size()); + std::vector corners; + std::vector masks; + std::vector warped(sources.size()); + for(size_t i = 0; i < sources.size(); ++i) { + DAI_CHECK_V(images[i].type() == CV_8UC3, "Blender input {} must be CV_8UC3, got type {}", i, images[i].type()); + corners.push_back(sources[i].tl); + masks.push_back(sources[i].mask); + cv::remap(images[i], warped[i], sources[i].map1, sources[i].map2, cv::INTER_LINEAR, border); + } + auto seamMasks = findSeamMasks(canvasRect.size(), corners, warped, masks, finder, seamResolution); + for(size_t i = 0; i < sources.size(); ++i) sources[i].seamMask = seamMasks[i]; + prepare(canvasRect, sources, static_cast(std::lround(stitching::blendWidth(canvasRect.size()))), border); + + for(size_t i = 0; i < sources.size(); ++i) { // Overlap samples in source coordinates, so the gains follow auto exposure + for(size_t j = i + 1; j < sources.size(); ++j) { + const cv::Rect overlap = cv::Rect(corners[i], masks[i].size()) & cv::Rect(corners[j], masks[j].size()); + if(overlap.area() == 0) continue; + const cv::Rect inI = overlap - corners[i]; + const cv::Rect inJ = overlap - corners[j]; + const cv::Mat both = masks[i](inI) & masks[j](inJ); + const int pixels = cv::countNonZero(both); + if(pixels == 0) continue; + OverlapSamples samples{i, j, static_cast(pixels), {}, {}}; + const int step = std::max(1, static_cast(std::sqrt(static_cast(pixels) / OVERLAP_SAMPLES))); + for(int y = 0; y < both.rows; y += step) { + for(int x = 0; x < both.cols; x += step) { + if(both.at(y, x) == 0) continue; + samples.inFirst.push_back(sampledFrom(sources[i], inI.tl() + cv::Point(x, y))); + samples.inSecond.push_back(sampledFrom(sources[j], inJ.tl() + cv::Point(x, y))); + } + } + overlapSamples.push_back(std::move(samples)); + } + } + updateGains(images, 1.0); + return seamMasks; +} + +void FixedBlender::prepare(const cv::Rect& canvasRect, const std::vector& input, int bandWidth, int border) { + DAI_CHECK_V(!input.empty(), "The fixed blender needs at least one source"); + DAI_CHECK_V(canvasRect.area() > 0, "The fixed blender needs a non-empty canvas"); + canvas = canvasRect; + sourceCount = input.size(); + borderMode = border; + pieces.clear(); + strips.clear(); + overlapSamples.clear(); + gains.clear(); + for(const auto& source : input) gains.push_back(source.gain); + const cv::Rect bounds(cv::Point(0, 0), canvas.size()); + const int kernel = std::max(1, bandWidth) | 1; + const int margin = kernel / 2 + 1; + + std::vector regions(input.size()); + std::vector weights(input.size()); + cv::Mat sum = cv::Mat::zeros(canvas.size(), CV_32F); + for(size_t i = 0; i < input.size(); ++i) { + const auto& source = input[i]; + DAI_CHECK_V(source.mask.size() == source.seamMask.size() && source.map1.size() == source.mask.size(), + "Fixed blender source {} needs a seam mask and maps sized like its mask", + i); + const cv::Rect placed = cv::Rect(source.tl - canvas.tl(), source.mask.size()) & bounds; + cv::Rect region = placed; + if(region.area() > 0) { + const cv::Rect seam = cv::boundingRect(source.seamMask(placed - (source.tl - canvas.tl()))); + region = cv::Rect(seam.x + placed.x - margin, seam.y + placed.y - margin, seam.width + 2 * margin, seam.height + 2 * margin) & placed; + } + regions[i] = region; + if(region.area() == 0) continue; + + const cv::Rect local = region - (source.tl - canvas.tl()); + cv::Mat weight; + source.seamMask(local).convertTo(weight, CV_32F, 1.0 / 255.0); + cv::blur(weight, weight, cv::Size(kernel, kernel), cv::Point(-1, -1), cv::BORDER_REPLICATE); + cv::Mat padded; // The border of the warped image counts as uncovered for the fade + cv::copyMakeBorder(source.mask, padded, 1, 1, 1, 1, cv::BORDER_CONSTANT, cv::Scalar(0)); + cv::Mat distance; + cv::distanceTransform(padded, distance, cv::DIST_L2, cv::DIST_MASK_PRECISE); + cv::Mat fade = cv::min(distance(local + cv::Point(1, 1)) / std::max(1, kernel / 2), 1.0); + weight = weight.mul(fade); + weight.setTo(0.0f, source.mask(local) == 0); + weights[i] = weight; + sum(region) += weight; + } + + cv::Mat kept = cv::Mat::zeros(canvas.size(), CV_32F); + for(size_t i = 0; i < input.size(); ++i) { + if(weights[i].empty()) continue; + cv::Mat share; + cv::divide(weights[i], sum(regions[i]), share); + weights[i].setTo(0.0f, share < MIN_WEIGHT); + kept(regions[i]) += weights[i]; + } + + cv::Mat blended = cv::Mat::zeros(canvas.size(), CV_8U); + std::vector pieceWeights; + for(size_t i = 0; i < input.size(); ++i) { + if(weights[i].empty()) continue; + cv::divide(weights[i], kept(regions[i]), weights[i]); + cv::patchNaNs(weights[i], 0.0); // 0/0 where no source has weight; float division by zero is not defined by OpenCV + const cv::Mat used = weights[i] > 0; + for(const auto& columns : pieceColumns(used)) { + const cv::Rect band(columns.start, 0, columns.size(), used.rows); + const cv::Rect rect = cv::boundingRect(used(band)) + band.tl(); + Piece piece; + piece.source = i; + piece.used = rect + regions[i].tl(); + const cv::Rect inSource = piece.used - (input[i].tl - canvas.tl()); + piece.map1 = input[i].map1(inSource).clone(); + if(!input[i].map2.empty()) piece.map2 = input[i].map2(inSource).clone(); + pieceWeights.push_back(weights[i](rect).clone()); + piece.own = pieceWeights.back() >= 1.0f - MIN_WEIGHT; + blended(piece.used) |= (pieceWeights.back() > 0) & ~piece.own; + pieces.push_back(std::move(piece)); + } + } + + cv::Mat labels; + cv::Mat stats; + cv::Mat centroids; + for(int top = 0; top < canvas.height; top += STRIP_ROWS) { + const cv::Rect band(0, top, canvas.width, std::min(STRIP_ROWS, canvas.height - top)); + const int count = cv::connectedComponentsWithStats(blended(band), labels, stats, centroids, 8, CV_32S); + for(int label = 1; label < count; ++label) { + const cv::Rect inBand(stats.at(label, cv::CC_STAT_LEFT), + stats.at(label, cv::CC_STAT_TOP), + stats.at(label, cv::CC_STAT_WIDTH), + stats.at(label, cv::CC_STAT_HEIGHT)); + Strip strip; + strip.rect = inBand + band.tl(); + strip.mask = labels(inBand) == label; + for(size_t p = 0; p < pieces.size(); ++p) { + const cv::Rect part = strip.rect & pieces[p].used; + if(part.area() == 0) continue; + cv::Mat weight; + pieceWeights[p](part - pieces[p].used.tl()).convertTo(weight, CV_8U, 255.0); + if(cv::countNonZero(weight & strip.mask(part - strip.rect.tl())) == 0) continue; + cv::Mat weight3; + cv::merge(std::vector{weight, weight, weight}, weight3); + strip.parts.push_back({p, part - strip.rect.tl(), weight3}); + } + strips.push_back(std::move(strip)); + } + } +} + +cv::Mat FixedBlender::blend(const std::vector& images) { + DAI_CHECK_V(images.size() == sourceCount, "Expected {} images to blend, got {}", sourceCount, images.size()); + for(size_t i = 0; i < images.size(); ++i) { + DAI_CHECK_V(images[i].type() == CV_8UC3, "Blender input {} must be CV_8UC3, got type {}", i, images[i].type()); + } + updateGains(images, GAIN_UPDATE_RATE); + cv::Mat result = cv::Mat::zeros(canvas.size(), CV_8UC3); + std::vector exposed(pieces.size()); + for(size_t i = 0; i < pieces.size(); ++i) { + const auto& piece = pieces[i]; + cv::remap(images[piece.source], exposed[i], piece.map1, piece.map2, cv::INTER_LINEAR, borderMode); + const auto& gain = gains[piece.source]; + if(gain != cv::Scalar::all(1.0)) cv::multiply(exposed[i], gain, exposed[i]); + exposed[i].copyTo(result(piece.used), piece.own); + } + + for(const auto& strip : strips) { + cv::Mat sum = cv::Mat::zeros(strip.rect.size(), CV_32FC3); + for(const auto& part : strip.parts) { + const cv::Rect inPiece = part.rect + strip.rect.tl() - pieces[part.piece].used.tl(); + cv::Mat region = sum(part.rect); + cv::accumulateProduct(exposed[part.piece](inPiece), part.weight, region); + } + cv::Mat blended; + sum.convertTo(blended, CV_8U, 1.0 / 255.0); + blended.copyTo(result(strip.rect), strip.mask); + } + return result; +} + +} // namespace utilities +} // namespace dai diff --git a/src/pipeline/utilities/Stitching/FixedBlender.hpp b/src/pipeline/utilities/Stitching/FixedBlender.hpp new file mode 100644 index 0000000000..db959b5054 --- /dev/null +++ b/src/pipeline/utilities/Stitching/FixedBlender.hpp @@ -0,0 +1,70 @@ +#pragma once + +#include +#include +#include + +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& sources, int bandWidth, int borderMode); + + std::vector prepareBlended(const cv::Rect& canvas, + std::vector sources, + const std::vector& images, + cv::detail::SeamFinder& finder, + double seamResolution, + int borderMode); + + cv::Mat blend(const std::vector& 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 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 inFirst; + std::vector inSecond; + }; + + void updateGains(const std::vector& images, double rate); + + cv::Rect canvas; + size_t sourceCount = 0; + int borderMode = cv::BORDER_CONSTANT; + std::vector pieces; + std::vector strips; + std::vector gains; + std::vector overlapSamples; +}; + +} // namespace utilities +} // namespace dai diff --git a/src/pipeline/utilities/Stitching/FixedPanoramaCompositor.cpp b/src/pipeline/utilities/Stitching/FixedPanoramaCompositor.cpp index 4c0e4040ad..7cd066de20 100644 --- a/src/pipeline/utilities/Stitching/FixedPanoramaCompositor.cpp +++ b/src/pipeline/utilities/Stitching/FixedPanoramaCompositor.cpp @@ -22,8 +22,7 @@ void FixedPanoramaCompositor::reset() { warperScale = 0.0; canvas = {}; sources.clear(); - compensator.release(); - blender.release(); + blender = FixedBlender{}; } bool FixedPanoramaCompositor::isPrepared() const { @@ -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; } @@ -81,6 +73,7 @@ void FixedPanoramaCompositor::prepare(const std::vector& images, const auto warper = stitching::createWarper(config.cameraModel)->create(static_cast(warperScale)); sources.reserve(images.size()); + std::vector blendSources(images.size()); for(size_t i = 0; i < images.size(); ++i) { DAI_CHECK_V(!images[i].empty(), "Panorama input {} is empty", i); @@ -101,9 +94,11 @@ void FixedPanoramaCompositor::prepare(const std::vector& 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)); @@ -111,17 +106,31 @@ void FixedPanoramaCompositor::prepare(const std::vector& images, const 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 FixedPanoramaCompositor::warp(const std::vector& images) const { +std::vector FixedPanoramaCompositor::composeInputs(const std::vector& images) const { DAI_CHECK_V(images.size() == sources.size(), "Expected {} panorama images, got {}", sources.size(), images.size()); - std::vector warped(sources.size()); + std::vector 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{}", @@ -130,89 +139,18 @@ std::vector FixedPanoramaCompositor::warp(const std::vector& 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& 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(canvas.size().area()))) - : 1.0; - std::vector seamCorners; - std::vector seamImages; - std::vector 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(std::lround(sources[i].roi.x * scale)), static_cast(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& 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(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 diff --git a/src/pipeline/utilities/Stitching/FixedPanoramaCompositor.hpp b/src/pipeline/utilities/Stitching/FixedPanoramaCompositor.hpp index 171d7e3ec6..feb6570344 100644 --- a/src/pipeline/utilities/Stitching/FixedPanoramaCompositor.hpp +++ b/src/pipeline/utilities/Stitching/FixedPanoramaCompositor.hpp @@ -1,11 +1,10 @@ #pragma once #include -#include -#include #include #include +#include "FixedBlender.hpp" #include "depthai/pipeline/node/Stitching.hpp" namespace dai { @@ -46,14 +45,10 @@ 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 warp(const std::vector& images) const; - void prepareCompositing(const std::vector& warped); + std::vector composeInputs(const std::vector& images) const; Config config; bool prepared = false; @@ -61,8 +56,7 @@ class FixedPanoramaCompositor { double warperScale = 0.0; cv::Rect canvas; std::vector sources; - cv::Ptr compensator; - cv::Ptr blender; + FixedBlender blender; }; } // namespace utilities diff --git a/src/pipeline/utilities/Stitching/PlanarStitcher.cpp b/src/pipeline/utilities/Stitching/PlanarStitcher.cpp index 1f88ba6fb9..3b0e65dbb5 100644 --- a/src/pipeline/utilities/Stitching/PlanarStitcher.cpp +++ b/src/pipeline/utilities/Stitching/PlanarStitcher.cpp @@ -118,7 +118,7 @@ void PlanarStitcher::reset() { numInputs = 0; preparedTransformations.clear(); sources.clear(); - compensator.release(); + blender = FixedBlender{}; } bool PlanarStitcher::isPrepared() const { @@ -232,7 +232,6 @@ void PlanarStitcher::prepare(const std::vector& transformatio source.index = i; source.roi = roi; source.mask = validity(roi).clone(); - source.seamMask = source.mask; source.imageSize = cv::Size(static_cast(sourceWidth), static_cast(sourceHeight)); cv::convertMaps(map(roi), cv::noArray(), source.map1, source.map2, CV_16SC2); sources.push_back(std::move(source)); @@ -357,103 +356,37 @@ Stitching::VirtualCamera PlanarStitcher::computeView(const std::vector& warped) { - std::vector corners; - std::vector images; - std::vector masks; - corners.reserve(sources.size()); - images.reserve(sources.size()); - masks.reserve(sources.size()); - for(size_t i = 0; i < sources.size(); ++i) { - corners.push_back(sources[i].roi.tl()); - images.push_back(warped[i].getUMat(cv::ACCESS_READ)); - masks.push_back(sources[i].mask.getUMat(cv::ACCESS_READ)); - } - - compensator = cv::detail::ExposureCompensator::createDefault(cv::detail::ExposureCompensator::GAIN_BLOCKS); - compensator->feed(corners, images, masks); - - const double area = static_cast(view.width) * view.height; // Seams on downscaled images (expensive), as OpenCV's stitcher does - const double scale = std::min(1.0, std::sqrt(stitching::SEAM_ESTIMATION_RESOLUTION * 1e6 / area)); - - std::vector seamCorners; - std::vector seamImages; - std::vector 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; - const cv::Size seamSize(std::max(1, static_cast(std::lround(warped[i].cols * scale))), - std::max(1, static_cast(std::lround(warped[i].rows * scale)))); - cv::resize(warped[i], image, seamSize, 0, 0, cv::INTER_LINEAR_EXACT); - cv::resize(sources[i].mask, mask, image.size(), 0, 0, cv::INTER_NEAREST); - image.convertTo(image, CV_32F); - - seamCorners.emplace_back(static_cast(std::lround(sources[i].roi.x * scale)), static_cast(std::lround(sources[i].roi.y * scale))); - seamImages.push_back(image.getUMat(cv::ACCESS_READ)); - seamMasks.push_back(mask.getUMat(cv::ACCESS_RW)); - } - - 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; - } - - compositingPrepared = true; -} - cv::Mat PlanarStitcher::compose(const std::vector& images) { DAI_CHECK_V(prepared, "The planar projection was not prepared yet"); DAI_CHECK_V(images.size() == numInputs, "Expected {} images, got {}", numInputs, images.size()); - std::vector warped(sources.size()); - for(size_t i = 0; i < sources.size(); ++i) { - const cv::Mat& image = images[sources[i].index]; - DAI_CHECK_V(image.size() == sources[i].imageSize, + std::vector sourceImages; + sourceImages.reserve(sources.size()); + for(const auto& source : sources) { + const cv::Mat& image = images[source.index]; + DAI_CHECK_V(image.size() == source.imageSize, "Input {} changed its size from {}x{} to {}x{}", - sources[i].index, - sources[i].imageSize.width, - sources[i].imageSize.height, + source.index, + source.imageSize.width, + source.imageSize.height, image.cols, image.rows); - cv::remap(image, warped[i], sources[i].map1, sources[i].map2, cv::INTER_LINEAR, cv::BORDER_CONSTANT); + sourceImages.push_back(image); } - if(!compositingPrepared) { - prepareCompositing(warped); - } - - const cv::Size viewSize(static_cast(view.width), static_cast(view.height)); - auto blender = stitching::createBlender(viewSize); - blender->prepare(cv::Rect(0, 0, viewSize.width, viewSize.height)); - - for(size_t i = 0; i < sources.size(); ++i) { - compensator->apply(static_cast(i), sources[i].roi.tl(), warped[i], sources[i].mask); - - cv::Mat converted; - warped[i].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); - - if(result.size() != viewSize) { // The blender only covers the fed regions; the canvas is the view - cv::Mat canvas = cv::Mat::zeros(viewSize, result.type()); - const cv::Rect overlap = cv::Rect(0, 0, result.cols, result.rows) & cv::Rect(0, 0, viewSize.width, viewSize.height); - result(overlap).copyTo(canvas(overlap)); - result = canvas; + std::vector blendSources; + for(auto& source : sources) { + blendSources.push_back({source.roi.tl(), source.mask, {}, cv::Scalar::all(1.0), std::move(source.map1), std::move(source.map2)}); + } + blender.prepareBlended(cv::Rect(0, 0, static_cast(view.width), static_cast(view.height)), + std::move(blendSources), + sourceImages, + *stitching::createSeamFinder(config.seamFinder), + stitching::SEAM_ESTIMATION_RESOLUTION, + cv::BORDER_CONSTANT); + compositingPrepared = true; } - - return result; + return blender.blend(sourceImages); } } // namespace utilities diff --git a/src/pipeline/utilities/Stitching/PlanarStitcher.hpp b/src/pipeline/utilities/Stitching/PlanarStitcher.hpp index 8c1b382b58..f0f385a559 100644 --- a/src/pipeline/utilities/Stitching/PlanarStitcher.hpp +++ b/src/pipeline/utilities/Stitching/PlanarStitcher.hpp @@ -2,10 +2,10 @@ #include #include -#include #include #include +#include "FixedBlender.hpp" #include "depthai/common/ImgTransformations.hpp" #include "depthai/pipeline/node/Stitching.hpp" @@ -49,7 +49,6 @@ class PlanarStitcher { // Inputs must share one origin socket; geometry is buil cv::Mat map1; // Fixed-point maps of roi from cv::convertMaps cv::Mat map2; cv::Mat mask; - cv::Mat seamMask; cv::Rect roi; cv::Size imageSize; }; @@ -61,8 +60,6 @@ class PlanarStitcher { // Inputs must share one origin socket; geometry is buil Stitching::VirtualCamera computeView(const std::vector& transformations, const std::vector& poses) const; - void prepareCompositing(const std::vector& warped); - Config config; bool prepared = false; @@ -74,7 +71,7 @@ class PlanarStitcher { // Inputs must share one origin socket; geometry is buil cv::Vec3d planePoint; // Reference frame, centimeters; the normal is a unit vector cv::Vec3d planeNormal; std::vector sources; - cv::Ptr compensator; + FixedBlender blender; }; } // namespace utilities diff --git a/src/pipeline/utilities/Stitching/Stitching.cpp b/src/pipeline/utilities/Stitching/Stitching.cpp index 3962933314..d802328387 100644 --- a/src/pipeline/utilities/Stitching/Stitching.cpp +++ b/src/pipeline/utilities/Stitching/Stitching.cpp @@ -489,8 +489,9 @@ void Stitching::run() { DAI_CHECK_V(frame != nullptr, "Stitching input {} did not receive an ImgFrame", name); if(first == nullptr) first = frame; - const auto image = (currentProperties.mode == Mode::PLANAR_PROJECTION || currentProperties.useInputCalibration) ? utility::getCvFrameView(*frame) - : frame->getCvFrame(); + auto image = (currentProperties.mode == Mode::PLANAR_PROJECTION || currentProperties.useInputCalibration) ? utility::getCvFrameView(*frame) + : frame->getCvFrame(); + if(image.depth() != CV_8U) image.convertTo(image, CV_8U); // Saturates like the BGR888i output always did if(image.channels() == 1) { cv::Mat bgr; cv::cvtColor(image, bgr, cv::COLOR_GRAY2BGR); @@ -711,7 +712,7 @@ void Stitching::run() { impl->transformFixed = true; if(logger) { const auto size = impl->fixedPanorama.getCanvasSize(); - logger->info("Panorama composition fixed at {}x{}; reusing warp maps, seams and exposure parameters", size.width, size.height); + logger->info("Panorama composition fixed at {}x{}; reusing warp maps and seams", size.width, size.height); } } } diff --git a/src/pipeline/utilities/Stitching/StitchingCompositing.hpp b/src/pipeline/utilities/Stitching/StitchingCompositing.hpp index 42a422df99..042fa0a0ec 100644 --- a/src/pipeline/utilities/Stitching/StitchingCompositing.hpp +++ b/src/pipeline/utilities/Stitching/StitchingCompositing.hpp @@ -78,8 +78,12 @@ inline cv::Ptr createSeamFinder(Stitching::SeamFinder fi return cv::makePtr(cv::detail::GraphCutSeamFinderBase::COST_COLOR); } -inline cv::Ptr createBlender(const cv::Size& panoSizeHint) { // Blend width as in OpenCV stitching_detailed sample - const float blendWidth = std::sqrt(static_cast(panoSizeHint.area())) * BLEND_STRENGTH / 100.0f; +inline float blendWidth(const cv::Size& panoSize) { // As in OpenCV stitching_detailed sample + return std::sqrt(static_cast(panoSize.area())) * BLEND_STRENGTH / 100.0f; +} + +inline cv::Ptr createBlender(const cv::Size& panoSizeHint) { + const float blendWidth = stitching::blendWidth(panoSizeHint); if(blendWidth < 1.0f) { return cv::detail::Blender::createDefault(cv::detail::Blender::NO, false); } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index d2e8d48d86..ee6cada193 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -764,6 +764,8 @@ endif() if(DEPTHAI_HAVE_OPENCV_STITCHING) dai_add_test(planar_stitching_node_test src/onhost_tests/pipeline/node/planar_stitching_node_test.cpp) dai_set_test_labels(planar_stitching_node_test onhost ci) + dai_add_test(fixed_blender_test src/onhost_tests/pipeline/utilities/fixed_blender_test.cpp) + dai_set_test_labels(fixed_blender_test onhost ci) endif() # Remote connection tests diff --git a/tests/src/onhost_tests/pipeline/node/stitching_node_test.cpp b/tests/src/onhost_tests/pipeline/node/stitching_node_test.cpp index 40f51ac30b..45ae9a8691 100644 --- a/tests/src/onhost_tests/pipeline/node/stitching_node_test.cpp +++ b/tests/src/onhost_tests/pipeline/node/stitching_node_test.cpp @@ -80,7 +80,8 @@ std::shared_ptr toCalibratedFrame(const cv::Mat& image, double ya std::shared_ptr composeCalibratedPanorama(const std::vector& images, const std::vector& yaws, const std::vector& pitches, - dai::CameraModel cameraModel) { + dai::CameraModel cameraModel, + dai::node::Stitching::SeamFinder seamFinder = dai::node::Stitching::SeamFinder::NONE) { REQUIRE(images.size() == yaws.size()); REQUIRE(images.size() == pitches.size()); @@ -88,7 +89,7 @@ std::shared_ptr composeCalibratedPanorama(const std::vector()->build(images.size()); stitching->setUseInputCalibration(true); stitching->setCameraModel(cameraModel); - stitching->setSeamFinder(dai::node::Stitching::SeamFinder::NONE); + stitching->setSeamFinder(seamFinder); stitching->setSyncThreshold(std::chrono::seconds(1)); std::vector> inputs; @@ -357,6 +358,36 @@ TEST_CASE("Calibrated panorama directly copies overlapping inputs", "[Stitching] REQUIRE(result.at(result.rows / 2, result.cols / 2) == secondColor); } +TEST_CASE("Calibrated panorama composes 16-bit inputs", "[Stitching]") { + const cv::Mat image(VIEW_HEIGHT, VIEW_WIDTH, CV_16UC3, cv::Scalar::all(100)); + for(const auto seamFinder : {dai::node::Stitching::SeamFinder::NONE, dai::node::Stitching::SeamFinder::VORONOI}) { + dai::Pipeline pipeline(false); + auto stitching = pipeline.create()->build(2); + stitching->setUseInputCalibration(true); + stitching->setCameraModel(dai::CameraModel::Cylindrical); + stitching->setSeamFinder(seamFinder); + stitching->setSyncThreshold(std::chrono::seconds(1)); + auto firstInput = stitching->inputs["input0"].createInputQueue(); + auto secondInput = stitching->inputs["input1"].createInputQueue(); + auto output = stitching->out.createOutputQueue(); + + pipeline.start(); + for(const auto& [input, yaw] : {std::make_pair(firstInput, -20.0), std::make_pair(secondInput, 20.0)}) { + auto frame = toCalibratedFrame(cv::Mat(VIEW_HEIGHT, VIEW_WIDTH, CV_8UC3), yaw, 1); + frame->setCvFrame(image, dai::ImgFrame::Type::RGB161616); + input->send(frame); + } + bool timedOut = false; + auto panorama = output->get(std::chrono::seconds(2), timedOut); + pipeline.stop(); + + REQUIRE_FALSE(timedOut); + REQUIRE(panorama != nullptr); + const auto result = panorama->getCvFrame(); + REQUIRE(result.at(result.rows / 2, result.cols / 2) == cv::Vec3b(100, 100, 100)); + } +} + TEST_CASE("Calibrated panorama blends overlapping inputs when seam finding is enabled", "[Stitching]") { const cv::Vec3b firstColor(20, 40, 60); const cv::Vec3b secondColor(180, 200, 220); @@ -390,6 +421,38 @@ TEST_CASE("Calibrated panorama blends overlapping inputs when seam finding is en REQUIRE(center != secondColor); } +TEST_CASE("Calibrated panorama matches the exposure of overlapping inputs", "[Stitching]") { + const cv::Mat scene = cv::imread(KITCHEN_IMAGE_PATH); + REQUIRE(!scene.empty()); + const std::vector yaws = {-10.0, 10.0}; + const std::vector pitches = {0.0, 0.0}; + const std::vector views = {renderView(scene, yaws[0]), renderView(scene, yaws[1])}; + cv::Mat darker; + cv::multiply(views[1], cv::Scalar(0.6, 0.7, 0.8), darker); + + const auto edgeRatio = [](const cv::Mat& panorama) { + const int edge = panorama.cols * 15 / 100; + const auto mean = [&](int x) { + const cv::Mat part = panorama(cv::Rect(x, 0, edge, panorama.rows)); + cv::Mat gray; + cv::cvtColor(part, gray, cv::COLOR_BGR2GRAY); + return cv::mean(part, gray > 0); + }; + const cv::Scalar left = mean(0); + const cv::Scalar right = mean(panorama.cols - edge); + return cv::Vec3d(right[0] / left[0], right[1] / left[1], right[2] / left[2]); + }; + const auto compose = [&](const std::vector& images) { + return composeCalibratedPanorama(images, yaws, pitches, dai::CameraModel::Cylindrical, dai::node::Stitching::SeamFinder::GRAPHCUT_COLOR)->getCvFrame(); + }; + + const cv::Vec3d reference = edgeRatio(compose(views)); + const cv::Vec3d compensated = edgeRatio(compose({views[0], darker})); + for(int channel = 0; channel < 3; ++channel) { + REQUIRE_THAT(compensated[channel], WithinRel(reference[channel], 0.05)); + } +} + TEST_CASE("Calibrated cylindrical panorama masks inputs crossing the wrap boundary", "[Stitching]") { const cv::Vec3b referenceColor(20, 80, 140); const cv::Vec3b wrappedColor(180, 100, 40); diff --git a/tests/src/onhost_tests/pipeline/utilities/fixed_blender_test.cpp b/tests/src/onhost_tests/pipeline/utilities/fixed_blender_test.cpp new file mode 100644 index 0000000000..1a85250b41 --- /dev/null +++ b/tests/src/onhost_tests/pipeline/utilities/fixed_blender_test.cpp @@ -0,0 +1,88 @@ +#include +#include +#include +#include + +#include "pipeline/utilities/Stitching/FixedBlender.hpp" + +namespace { + +dai::utilities::FixedBlender::Source flatSource(cv::Point tl, const cv::Mat& seamMask) { + cv::Mat map(seamMask.size(), CV_32FC2); + map.forEach([](cv::Vec2f& value, const int* position) { value = cv::Vec2f(static_cast(position[1]), static_cast(position[0])); }); + return {tl, cv::Mat(seamMask.size(), CV_8U, cv::Scalar(255)), seamMask, cv::Scalar::all(1.0), map, cv::Mat()}; +} + +} // namespace + +TEST_CASE("Fixed blender ramps across an overlap narrower than its band", "[Stitching]") { + const cv::Size size(120, 16); + cv::Mat leftSeam = cv::Mat::zeros(size, CV_8U); + leftSeam.colRange(0, 110).setTo(255); + cv::Mat rightSeam = cv::Mat::zeros(size, CV_8U); + rightSeam.colRange(10, 120).setTo(255); + + dai::utilities::FixedBlender blender; + blender.prepare(cv::Rect(0, 0, 220, 16), {flatSource({0, 0}, leftSeam), flatSource({100, 0}, rightSeam)}, 61, cv::BORDER_REFLECT); + const cv::Mat result = blender.blend({cv::Mat(size, CV_8UC3, cv::Scalar::all(50)), cv::Mat(size, CV_8UC3, cv::Scalar::all(150))}); + + REQUIRE(result.at(8, 0) == cv::Vec3b(50, 50, 50)); + REQUIRE(result.at(8, 219) == cv::Vec3b(150, 150, 150)); + int largestStep = 0; + for(int x = 1; x < result.cols; ++x) { + largestStep = std::max(largestStep, std::abs(result.at(8, x)[0] - result.at(8, x - 1)[0])); + } + REQUIRE(largestStep <= 15); +} + +TEST_CASE("Fixed blender samples a source that contributes at both ends of the canvas", "[Stitching]") { + const cv::Size size(300, 8); + cv::Mat endsSeam = cv::Mat::zeros(size, CV_8U); + endsSeam.colRange(0, 50).setTo(255); + endsSeam.colRange(250, 300).setTo(255); + const cv::Mat middleSeam = 255 - endsSeam; + + cv::Mat ramp(size, CV_8UC3); + for(int x = 0; x < size.width; ++x) ramp.col(x).setTo(cv::Scalar::all(x * 255 / (size.width - 1))); + + dai::utilities::FixedBlender blender; + blender.prepare(cv::Rect(0, 0, 300, 8), {flatSource({0, 0}, endsSeam), flatSource({0, 0}, middleSeam)}, 5, cv::BORDER_REFLECT); + const cv::Mat result = blender.blend({ramp, cv::Mat(size, CV_8UC3, cv::Scalar::all(77))}); + for(const int x : {0, 20, 280, 299}) REQUIRE(result.at(4, x) == ramp.at(4, x)); + REQUIRE(result.at(4, 150) == cv::Vec3b(77, 77, 77)); +} + +TEST_CASE("Fixed blender limits the exposure gain of a far darker overlap", "[Stitching]") { + const cv::Size size(100, 8); + const cv::Mat full(size, CV_8U, cv::Scalar(255)); + cv::detail::NoSeamFinder noSeams; + + dai::utilities::FixedBlender blender; + const std::vector images = {cv::Mat(size, CV_8UC3, cv::Scalar::all(2)), cv::Mat(size, CV_8UC3, cv::Scalar::all(120))}; + blender.prepareBlended(cv::Rect(0, 0, 150, 8), {flatSource({0, 0}, full), flatSource({50, 0}, full)}, images, noSeams, -1.0, cv::BORDER_REFLECT); + const cv::Mat result = blender.blend(images); + + REQUIRE(result.at(4, 0)[0] <= 4); + REQUIRE(result.at(4, 149)[0] >= 60); +} + +TEST_CASE("Fixed blender follows the exposure after a first group captured before it settled", "[Stitching]") { + const cv::Size size(100, 8); + const cv::Mat full(size, CV_8U, cv::Scalar(255)); + cv::detail::NoSeamFinder noSeams; + const auto flat = [&](int value) { return cv::Mat(size, CV_8UC3, cv::Scalar::all(value)); }; + + // The second camera starts at half the brightness it has once its auto exposure has settled + dai::utilities::FixedBlender blender; + const std::vector unsettled = {flat(120), flat(60)}; + blender.prepareBlended(cv::Rect(0, 0, 150, 8), {flatSource({0, 0}, full), flatSource({50, 0}, full)}, unsettled, noSeams, -1.0, cv::BORDER_REFLECT); + const cv::Mat first = blender.blend(unsettled); + REQUIRE(std::abs(first.at(4, 0)[0] - first.at(4, 149)[0]) <= 2); + REQUIRE(blender.blend(unsettled).at(4, 0) == first.at(4, 0)); + + const std::vector settled = {flat(120), flat(120)}; + cv::Mat result; + for(int frame = 0; frame < 60; ++frame) result = blender.blend(settled); + REQUIRE(std::abs(result.at(4, 0)[0] - 120) <= 2); + REQUIRE(std::abs(result.at(4, 149)[0] - 120) <= 2); +}