SMACC2
Loading...
Searching...
No Matches
box_fit.cpp
Go to the documentation of this file.
1// Copyright 2026 RobosoftAI Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include <cl_rgb/box_fit.hpp>
16
17#include <opencv2/imgproc.hpp>
18
19#include <algorithm>
20#include <cmath>
21#include <vector>
22
23namespace cl_rgb
24{
25namespace
26{
27// The outline of the box in the blob's own image window; empty when a corner is not seen.
28cv::Mat outline(
29 const PinholeCamera & camera, const cv::Rect & box, double x, double y, double yaw, double tableZ,
30 const cv::Vec3d & size, bool topOnly)
31{
32 const double c = std::cos(yaw), s = std::sin(yaw);
33 std::vector<cv::Point> corners;
34 for (int i = topOnly ? 4 : 0; i < 8; ++i)
35 {
36 const double dx = ((i & 1) != 0 ? 0.5 : -0.5) * size[0];
37 const double dy = ((i & 2) != 0 ? 0.5 : -0.5) * size[1];
38 const double dz = (i & 4) != 0 ? size[2] : 0.0;
39 const auto pixel =
40 camera.project(cv::Vec3d(x + c * dx - s * dy, y + s * dx + c * dy, tableZ + dz));
41 if (!pixel)
42 {
43 return cv::Mat();
44 }
45 corners.emplace_back(cvRound(pixel->x) - box.x, cvRound(pixel->y) - box.y);
46 }
47 std::vector<cv::Point> hull;
48 cv::convexHull(corners, hull);
49 cv::Mat drawn = cv::Mat::zeros(box.size(), CV_8UC1);
50 cv::fillConvexPoly(drawn, hull, cv::Scalar(255));
51 return drawn;
52}
53
54double hullArea(
55 const PinholeCamera & camera, double x, double y, double yaw, double tableZ,
56 const cv::Vec3d & size, bool topOnly)
57{
58 const double c = std::cos(yaw), s = std::sin(yaw);
59 std::vector<cv::Point2f> corners;
60 for (int i = topOnly ? 4 : 0; i < 8; ++i)
61 {
62 const double dx = ((i & 1) != 0 ? 0.5 : -0.5) * size[0];
63 const double dy = ((i & 2) != 0 ? 0.5 : -0.5) * size[1];
64 const double dz = (i & 4) != 0 ? size[2] : 0.0;
65 const auto pixel =
66 camera.project(cv::Vec3d(x + c * dx - s * dy, y + s * dx + c * dy, tableZ + dz));
67 if (!pixel)
68 {
69 return 0.0;
70 }
71 corners.emplace_back(static_cast<float>(pixel->x), static_cast<float>(pixel->y));
72 }
73 std::vector<cv::Point2f> hull;
74 cv::convexHull(corners, hull);
75 return cv::contourArea(hull);
76}
77} // namespace
78
79namespace
80{
81// The blob without its weakly coloured pixels; the blob itself when that leaves too little.
82Blob strongColourPart(const Blob & whole, double minChromaFraction)
83{
84 if (minChromaFraction <= 0.0 || whole.crop.empty())
85 {
86 return whole;
87 }
88 cv::Mat floatCrop, lab;
89 whole.crop.convertTo(floatCrop, CV_32FC3, 1.0 / 255.0);
90 cv::cvtColor(floatCrop, lab, cv::COLOR_BGR2Lab);
91 std::vector<float> chromas, lightnesses;
92 cv::Mat chroma(lab.size(), CV_32FC1, cv::Scalar(0));
93 cv::Mat lightness(lab.size(), CV_32FC1, cv::Scalar(0));
94 for (int r = 0; r < lab.rows; ++r)
95 {
96 for (int c = 0; c < lab.cols; ++c)
97 {
98 if (whole.mask.at<uchar>(r, c))
99 {
100 const cv::Vec3f v = lab.at<cv::Vec3f>(r, c);
101 chroma.at<float>(r, c) = std::hypot(v[1], v[2]);
102 chromas.push_back(chroma.at<float>(r, c));
103 lightness.at<float>(r, c) = v[0];
104 lightnesses.push_back(v[0]);
105 }
106 }
107 }
108 if (chromas.empty())
109 {
110 return whole;
111 }
112 std::sort(chromas.begin(), chromas.end());
113 const float strong = chromas[static_cast<size_t>(0.9 * (chromas.size() - 1))];
114 Blob part = whole;
115 std::sort(lightnesses.begin(), lightnesses.end());
116 const float middle = lightnesses[lightnesses.size() / 2];
117 part.mask = whole.mask &
118 ((chroma >= static_cast<float>(minChromaFraction) * strong) | (lightness >= middle));
119 part.areaPx = cv::countNonZero(part.mask);
120 if (part.areaPx < whole.areaPx / 4)
121 {
122 return whole;
123 }
124 const cv::Moments m = cv::moments(part.mask, true);
125 part.centroidPx = cv::Point2d(whole.box.x + m.m10 / m.m00, whole.box.y + m.m01 / m.m00);
126 return part;
127}
128} // namespace
129
130std::optional<BoxFit> fitBoxOnTable(
131 const Blob & seen, const PinholeCamera & camera, double tableZ, const BoxFitParams & params)
132{
133 if (seen.mask.empty() || seen.areaPx <= 0)
134 {
135 return std::nullopt;
136 }
137 const Blob blob = strongColourPart(seen, params.minChromaFraction);
138 // the centroid of the outline lies near the box's centre at half its height
139 const auto guess =
140 camera.pixelToPlane(blob.centroidPx.x, blob.centroidPx.y, tableZ + params.sizeM[2] / 2.0);
141 if (!guess)
142 {
143 return std::nullopt;
144 }
145 const bool square = std::abs(params.sizeM[0] - params.sizeM[1]) < 1e-6;
146 const double yawEnd = square ? CV_PI / 2.0 : CV_PI;
147 const int steps = static_cast<int>(std::round(params.searchM / params.stepM));
148
149 BoxFit best;
150 best.overlap = -1.0;
151 for (const bool topOnly : {false, true})
152 {
153 if (topOnly && best.overlap >= params.tryTopBelow)
154 {
155 break;
156 }
157 // the centroid of the top face lies at the box's centre at its full height
158 const auto centre =
159 topOnly ? camera.pixelToPlane(blob.centroidPx.x, blob.centroidPx.y, tableZ + params.sizeM[2])
160 : guess;
161 if (!centre)
162 {
163 continue;
164 }
165 for (double yaw = 0.0; yaw < yawEnd - 1e-9; yaw += params.yawStepRad)
166 {
167 for (int ix = -steps; ix <= steps; ++ix)
168 {
169 for (int iy = -steps; iy <= steps; ++iy)
170 {
171 const double x = (*centre)[0] + ix * params.stepM;
172 const double y = (*centre)[1] + iy * params.stepM;
173 const cv::Mat drawn = outline(camera, blob.box, x, y, yaw, tableZ, params.sizeM, topOnly);
174 if (drawn.empty())
175 {
176 continue;
177 }
178 const double both = cv::countNonZero(drawn & blob.mask);
179 // the outline's full area, so that a box partly outside the window is not favoured
180 const double whole =
181 std::max(hullArea(camera, x, y, yaw, tableZ, params.sizeM, topOnly), 1.0);
182 const double overlap = both / (whole + blob.areaPx - both);
183 if (overlap > best.overlap)
184 {
185 best = BoxFit{x, y, yaw, overlap, topOnly};
186 }
187 }
188 }
189 }
190 }
191 if (best.overlap < params.minOverlap)
192 {
193 return std::nullopt;
194 }
195 return best;
196}
197
198} // namespace cl_rgb
Blob strongColourPart(const Blob &whole, double minChromaFraction)
Definition box_fit.cpp:82
double hullArea(const PinholeCamera &camera, double x, double y, double yaw, double tableZ, const cv::Vec3d &size, bool topOnly)
Definition box_fit.cpp:54
cv::Mat outline(const PinholeCamera &camera, const cv::Rect &box, double x, double y, double yaw, double tableZ, const cv::Vec3d &size, bool topOnly)
Definition box_fit.cpp:28
std::optional< BoxFit > fitBoxOnTable(const Blob &blob, const PinholeCamera &camera, double tableZ, const BoxFitParams &params)
Definition box_fit.cpp:130
cv::Point2d centroidPx
double overlap
Definition box_fit.hpp:33
std::optional< cv::Vec3d > pixelToPlane(double u, double v, double z) const
Definition geometry.cpp:35
std::optional< cv::Point2d > project(const cv::Vec3d &point) const
Definition geometry.cpp:25