SMACC2
Loading...
Searching...
No Matches
table_survey.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
16
17#include <opencv2/imgproc.hpp>
18
19#include <algorithm>
20#include <cmath>
21#include <limits>
22
23namespace cl_rgb
24{
25
26namespace
27{
28// Median and robust spread (1.4826 * median absolute deviation) of one float channel under a mask.
29void robustStats(const cv::Mat & channel, const cv::Mat & mask, double & median, double & spread)
30{
31 std::vector<float> values;
32 values.reserve(static_cast<size_t>(cv::countNonZero(mask)));
33 for (int r = 0; r < channel.rows; ++r)
34 {
35 const float * c = channel.ptr<float>(r);
36 const uchar * m = mask.ptr<uchar>(r);
37 for (int col = 0; col < channel.cols; ++col)
38 {
39 if (m[col])
40 {
41 values.push_back(c[col]);
42 }
43 }
44 }
45 if (values.empty())
46 {
47 median = 0.0;
48 spread = 1.0;
49 return;
50 }
51 const auto mid = values.begin() + static_cast<long>(values.size() / 2);
52 std::nth_element(values.begin(), mid, values.end());
53 median = *mid;
54 for (auto & v : values)
55 {
56 v = std::abs(v - static_cast<float>(median));
57 }
58 std::nth_element(values.begin(), mid, values.end());
59 spread = 1.4826 * *mid;
60}
61} // namespace
62
64 const PinholeCamera & camera, const cv::Size & size, const TableParams & table)
65{
66 cv::Mat mask(size, CV_8UC1, cv::Scalar(0));
67 const cv::Matx33d H = camera.imageToPlaneHomography(table.height);
68 const double drop = table.height - camera.position[2];
69 for (int v = 0; v < size.height; ++v)
70 {
71 uchar * row = mask.ptr<uchar>(v);
72 for (int u = 0; u < size.width; ++u)
73 {
74 const cv::Vec3d p = H * cv::Vec3d(u, v, 1.0);
75 // p[2] is the vertical component of the ray; the ray must travel towards the plane
76 if (std::abs(p[2]) < 1e-12 || drop / p[2] <= 0.0)
77 {
78 continue;
79 }
80 const double x = p[0] / p[2];
81 const double y = p[1] / p[2];
82 if (x >= table.xMin && x <= table.xMax && y >= table.yMin && y <= table.yMax)
83 {
84 row[u] = 255;
85 }
86 }
87 }
88 return mask;
89}
90
92 const cv::Mat & bgr, const cv::Mat & tableMask, const SegmenterParams & params)
93{
94 cv::Mat floatImage, lab;
95 bgr.convertTo(floatImage, CV_32FC3, 1.0 / 255.0);
96 cv::cvtColor(floatImage, lab, cv::COLOR_BGR2Lab);
97 std::vector<cv::Mat> channels;
98 cv::split(lab, channels);
99
100 cv::Mat distanceSquared(bgr.size(), CV_32FC1, cv::Scalar(0.0f));
101 const double weights[3] = {params.lightnessWeight, 1.0, 1.0};
102 for (int c = 0; c < 3; ++c)
103 {
104 double median = 0.0, spread = 1.0;
105 robustStats(channels[c], tableMask, median, spread);
106 // A floor on the spread: a table of one flat colour must not turn noise into foreground.
107 spread = std::max(spread, 1.0);
108 cv::Mat normalized = (channels[c] - median) * (weights[c] / spread);
109 distanceSquared += normalized.mul(normalized);
110 }
111
112 cv::Mat foreground = (distanceSquared > params.threshold * params.threshold);
113 cv::bitwise_and(foreground, tableMask, foreground);
114 if (params.openPx > 1)
115 {
116 cv::morphologyEx(
117 foreground, foreground, cv::MORPH_OPEN,
118 cv::getStructuringElement(cv::MORPH_RECT, cv::Size(params.openPx, params.openPx)));
119 }
120 if (params.closePx > 1)
121 {
122 cv::morphologyEx(
123 foreground, foreground, cv::MORPH_CLOSE,
124 cv::getStructuringElement(cv::MORPH_RECT, cv::Size(params.closePx, params.closePx)));
125 }
126 return foreground;
127}
128
130 const cv::Mat & bgr, const cv::Mat & referenceBgr, const cv::Mat & tableMask,
131 const SegmenterParams & params)
132{
133 cv::Mat image, reference, imageLab, referenceLab;
134 bgr.convertTo(image, CV_32FC3, 1.0 / 255.0);
135 referenceBgr.convertTo(reference, CV_32FC3, 1.0 / 255.0);
136 cv::cvtColor(image, imageLab, cv::COLOR_BGR2Lab);
137 cv::cvtColor(reference, referenceLab, cv::COLOR_BGR2Lab);
138
139 std::vector<cv::Mat> difference;
140 cv::split(imageLab - referenceLab, difference);
141 difference[0] *= params.referenceLightnessWeight;
142 cv::Mat distanceSquared = difference[0].mul(difference[0]) + difference[1].mul(difference[1]) +
143 difference[2].mul(difference[2]);
144
145 cv::Mat foreground = (distanceSquared > params.referenceThreshold * params.referenceThreshold);
146 cv::bitwise_and(foreground, tableMask, foreground);
147 if (params.shadowDarkest > 0.0)
148 {
149 for (int r = 0; r < foreground.rows; ++r)
150 {
151 for (int c = 0; c < foreground.cols; ++c)
152 {
153 if (!foreground.at<uchar>(r, c))
154 {
155 continue;
156 }
157 const cv::Vec3f seen = image.at<cv::Vec3f>(r, c);
158 const cv::Vec3f empty = reference.at<cv::Vec3f>(r, c);
159 float least = 10.0F, most = 0.0F;
160 for (int k = 0; k < 3; ++k)
161 {
162 const float ratio = (seen[k] + 0.004F) / (empty[k] + 0.004F);
163 least = std::min(least, ratio);
164 most = std::max(most, ratio);
165 }
166 if (most <= 1.03F && least >= params.shadowDarkest && most - least <= params.shadowSpread)
167 {
168 foreground.at<uchar>(r, c) = 0;
169 }
170 }
171 }
172 }
173 if (params.openPx > 1)
174 {
175 cv::morphologyEx(
176 foreground, foreground, cv::MORPH_OPEN,
177 cv::getStructuringElement(cv::MORPH_RECT, cv::Size(params.openPx, params.openPx)));
178 }
179 if (params.closePx > 1)
180 {
181 cv::morphologyEx(
182 foreground, foreground, cv::MORPH_CLOSE,
183 cv::getStructuringElement(cv::MORPH_RECT, cv::Size(params.closePx, params.closePx)));
184 }
185 return foreground;
186}
187
188std::vector<Blob> findBlobs(
189 const cv::Mat & bgr, const cv::Mat & foreground, const PinholeCamera & camera,
190 const TableParams & table, const BlobParams & params)
191{
192 cv::Mat floatImage, lab;
193 bgr.convertTo(floatImage, CV_32FC3, 1.0 / 255.0);
194 cv::cvtColor(floatImage, lab, cv::COLOR_BGR2Lab);
195
196 cv::Mat regions = foreground;
197 if (params.colourEdgeHueDeg > 0.0)
198 {
199 regions = foreground.clone();
200 for (int r = 0; r < lab.rows; ++r)
201 {
202 for (int c = 0; c < lab.cols; ++c)
203 {
204 if (!foreground.at<uchar>(r, c))
205 {
206 continue;
207 }
208 const cv::Vec3f here = lab.at<cv::Vec3f>(r, c);
209 // the pixel two to the right, and the pixel two below
210 for (int k = 0; k < 2; ++k)
211 {
212 const int nr = k == 0 ? r : r + 2;
213 const int nc = k == 0 ? c + 2 : c;
214 if (nr >= lab.rows || nc >= lab.cols || !foreground.at<uchar>(nr, nc))
215 {
216 continue;
217 }
218 const cv::Vec3f there = lab.at<cv::Vec3f>(nr, nc);
219 if (
220 std::hypot(here[1], here[2]) < params.colourEdgeMinChroma ||
221 std::hypot(there[1], there[2]) < params.colourEdgeMinChroma)
222 {
223 continue;
224 }
225 double turn = std::abs(std::atan2(there[2], there[1]) - std::atan2(here[2], here[1]));
226 turn = turn > CV_PI ? 2.0 * CV_PI - turn : turn;
227 if (turn * 180.0 / CV_PI > params.colourEdgeHueDeg)
228 {
229 // the pixel between the two is the seam
230 regions.at<uchar>((r + nr) / 2, (c + nc) / 2) = 0;
231 }
232 }
233 }
234 }
235 }
236
237 cv::Mat labels, stats, centroids;
238 const int count = cv::connectedComponentsWithStats(
239 regions, labels, stats, centroids, params.colourEdgeHueDeg > 0.0 ? 4 : 8);
240 const cv::Matx33d H = camera.imageToPlaneHomography(table.height);
241
242 std::vector<Blob> blobs;
243 for (int i = 1; i < count; ++i)
244 {
245 const int area = stats.at<int>(i, cv::CC_STAT_AREA);
246 if (area < params.minAreaPx)
247 {
248 continue;
249 }
250 Blob blob;
251 blob.areaPx = area;
252 blob.box = cv::Rect(
253 stats.at<int>(i, cv::CC_STAT_LEFT), stats.at<int>(i, cv::CC_STAT_TOP),
254 stats.at<int>(i, cv::CC_STAT_WIDTH), stats.at<int>(i, cv::CC_STAT_HEIGHT));
255 blob.centroidPx = cv::Point2d(centroids.at<double>(i, 0), centroids.at<double>(i, 1));
256 blob.mask = (labels(blob.box) == i);
257 blob.crop = bgr(blob.box).clone();
258 const cv::Scalar meanBgr = cv::mean(bgr(blob.box), blob.mask);
259 const cv::Scalar meanLab = cv::mean(lab(blob.box), blob.mask);
260 blob.meanBgr = cv::Vec3d(meanBgr[0], meanBgr[1], meanBgr[2]);
261 blob.meanLab = cv::Vec3d(meanLab[0], meanLab[1], meanLab[2]);
262
263 if (const auto point = camera.pixelToPlane(blob.centroidPx.x, blob.centroidPx.y, table.height))
264 {
265 blob.tablePoint = *point;
266 }
267
268 // The blob's pixels on the table plane: its footprint as this camera sees it.
269 std::vector<cv::Point2f> footprint;
270 footprint.reserve(static_cast<size_t>(area));
271 double nearest = std::numeric_limits<double>::max();
272 for (int r = 0; r < blob.box.height; ++r)
273 {
274 const uchar * m = blob.mask.ptr<uchar>(r);
275 for (int c = 0; c < blob.box.width; ++c)
276 {
277 if (!m[c])
278 {
279 continue;
280 }
281 const cv::Vec3d p = H * cv::Vec3d(blob.box.x + c, blob.box.y + r, 1.0);
282 if (std::abs(p[2]) < 1e-12)
283 {
284 continue;
285 }
286 const cv::Point2f onTable(static_cast<float>(p[0] / p[2]), static_cast<float>(p[1] / p[2]));
287 footprint.push_back(onTable);
288 const double dx = onTable.x - camera.position[0];
289 const double dy = onTable.y - camera.position[1];
290 const double distance = dx * dx + dy * dy;
291 if (distance < nearest)
292 {
293 nearest = distance;
294 blob.nearPoint = cv::Vec3d(onTable.x, onTable.y, table.height);
295 }
296 }
297 }
298 if (footprint.size() >= 3)
299 {
300 const cv::RotatedRect extent = cv::minAreaRect(footprint);
301 const bool widthIsLong = extent.size.width >= extent.size.height;
302 blob.lengthM = widthIsLong ? extent.size.width : extent.size.height;
303 blob.widthM = widthIsLong ? extent.size.height : extent.size.width;
304 double angle = extent.angle * CV_PI / 180.0 + (widthIsLong ? 0.0 : CV_PI / 2.0);
305 while (angle >= CV_PI / 2.0) angle -= CV_PI;
306 while (angle < -CV_PI / 2.0) angle += CV_PI;
307 blob.axisRad = angle;
308 }
309 blobs.push_back(std::move(blob));
310 }
311
312 std::sort(
313 blobs.begin(), blobs.end(), [](const Blob & a, const Blob & b) { return a.areaPx > b.areaPx; });
314 if (static_cast<int>(blobs.size()) > params.maxBlobs)
315 {
316 blobs.resize(static_cast<size_t>(params.maxBlobs));
317 }
318 for (size_t i = 0; i < blobs.size(); ++i)
319 {
320 blobs[i].id = static_cast<int>(i);
321 }
322 return blobs;
323}
324
325} // namespace cl_rgb
void robustStats(const cv::Mat &channel, const cv::Mat &mask, double &median, double &spread)
cv::Mat segmentAgainstReference(const cv::Mat &bgr, const cv::Mat &referenceBgr, const cv::Mat &tableMask, const SegmenterParams &params)
std::vector< Blob > findBlobs(const cv::Mat &bgr, const cv::Mat &foreground, const PinholeCamera &camera, const TableParams &table, const BlobParams &params)
cv::Mat segmentForeground(const cv::Mat &bgr, const cv::Mat &tableMask, const SegmenterParams &params)
cv::Mat tableRegionMask(const PinholeCamera &camera, const cv::Size &size, const TableParams &table)
cv::Vec3d meanLab
cv::Vec3d nearPoint
cv::Point2d centroidPx
cv::Vec3d tablePoint
cv::Vec3d meanBgr
std::optional< cv::Vec3d > pixelToPlane(double u, double v, double z) const
Definition geometry.cpp:35
cv::Matx33d imageToPlaneHomography(double z) const
Definition geometry.cpp:50