Instrument Neutral Distributed Interface INDI 2.2.5
frametracker.cpp
Go to the documentation of this file.
1/*
2 Copyright (C) 2026 by Jasem Mutlaq <[email protected]>
3
4 Frame Tracker
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
10
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public
17 License along with this library; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
20*/
21
22#include "frametracker.h"
23
24#include <algorithm>
25#include <array>
26#include <cmath>
27#include <vector>
28
29namespace INDI
30{
31
32namespace
33{
34// Long side of the binned working image
35constexpr size_t MAX_WORKING_SIZE = 256;
36// Smallest blob, in binned pixels, accepted as a target
37constexpr size_t MIN_BLOB_PIXELS = 4;
38// Target to sky contrast, in sky noise sigmas, below which quality drops to 0, and above which it is 1
39constexpr double MIN_SNR = 3;
40constexpr double GOOD_SNR = 10;
41// Target to sky brightness, as a fraction of full scale, that gives full quality
42constexpr double GOOD_SIGNAL = 0.02;
43// Quality factor when the blob touches the frame edge (centroid is biased by clipping)
44constexpr double EDGE_FACTOR = 0.5;
45
46double clamp01(double value)
47{
48 return std::min(1.0, std::max(0.0, value));
49}
50
51// Otsu's method over a 256-bin histogram of the working image
52double otsuThreshold(const std::vector<double> &pixels, double minValue, double maxValue)
53{
54 std::array<uint32_t, 256> histogram {};
55 const double range = maxValue - minValue;
56 for (double value : pixels)
57 {
58 int bin = static_cast<int>((value - minValue) / range * 256.0);
59 histogram[std::min(255, std::max(0, bin))]++;
60 }
61
62 const double total = static_cast<double>(pixels.size());
63 double sumAll = 0;
64 for (size_t i = 0; i < histogram.size(); i++)
65 sumAll += i * static_cast<double>(histogram[i]);
66
67 double sumBackground = 0, weightBackground = 0, bestVariance = -1;
68 size_t bestBin = 0;
69 for (size_t i = 0; i < histogram.size(); i++)
70 {
71 weightBackground += histogram[i];
72 if (weightBackground == 0)
73 continue;
74 const double weightForeground = total - weightBackground;
75 if (weightForeground == 0)
76 break;
77
78 sumBackground += i * static_cast<double>(histogram[i]);
79 const double meanBackground = sumBackground / weightBackground;
80 const double meanForeground = (sumAll - sumBackground) / weightForeground;
81 const double variance = weightBackground * weightForeground * (meanBackground - meanForeground) * (meanBackground - meanForeground);
82 if (variance > bestVariance)
83 {
84 bestVariance = variance;
85 bestBin = i;
86 }
87 }
88
89 // Pixels strictly above the upper edge of the best bin are foreground
90 return minValue + (bestBin + 1) * range / 256.0;
91}
92}
93
94FrameTracker::Measurement FrameTracker::measure(const Image &image, double referenceArea)
95{
96 Measurement result;
97
98 if (image.data == nullptr || image.width == 0 || image.height == 0 || image.components == 0
99 || (image.bytesPerComponent != 1 && image.bytesPerComponent != 2))
100 return result;
101
102 // Bin the frame into the working image, summing all color components
103 size_t bin = (std::max(image.width, image.height) + MAX_WORKING_SIZE - 1) / MAX_WORKING_SIZE;
104 if (image.bayer && bin % 2)
105 bin++;
106 bin = std::max<size_t>(bin, 1);
107
108 const size_t workWidth = image.width / bin;
109 const size_t workHeight = image.height / bin;
110 if (workWidth == 0 || workHeight == 0)
111 return result;
112
113 const size_t rowSamples = image.width * image.components;
114 const size_t binSamples = bin * bin * image.components;
115 std::vector<double> pixels(workWidth * workHeight);
116
117 for (size_t wy = 0; wy < workHeight; wy++)
118 {
119 for (size_t wx = 0; wx < workWidth; wx++)
120 {
121 uint64_t sum = 0;
122 for (size_t y = wy * bin; y < (wy + 1) * bin; y++)
123 {
124 const size_t start = y * rowSamples + wx * bin * image.components;
125 const size_t end = start + bin * image.components;
126 if (image.bytesPerComponent == 1)
127 {
128 for (size_t i = start; i < end; i++)
129 sum += image.data[i];
130 }
131 else
132 {
133 const uint16_t *data16 = reinterpret_cast<const uint16_t *>(image.data);
134 for (size_t i = start; i < end; i++)
135 sum += data16[i];
136 }
137 }
138 // Mean sample value, so thresholds are independent of the bin size
139 pixels[wy * workWidth + wx] = static_cast<double>(sum) / binSamples;
140 }
141 }
142
143 const auto minMax = std::minmax_element(pixels.begin(), pixels.end());
144 const double minValue = *minMax.first, maxValue = *minMax.second;
145 if (maxValue - minValue <= 0)
146 return result;
147
148 const double threshold = otsuThreshold(pixels, minValue, maxValue);
149
150 // Keep the largest connected blob above the threshold, so small satellites (Jupiter's moons)
151 // and hot pixels do not pull the centroid.
152 std::vector<int32_t> labels(pixels.size(), 0);
153 std::vector<size_t> stack;
154 int32_t bestLabel = 0, nextLabel = 0;
155 size_t bestCount = 0;
156
157 for (size_t start = 0; start < pixels.size(); start++)
158 {
159 if (labels[start] != 0 || pixels[start] <= threshold)
160 continue;
161
162 const int32_t label = ++nextLabel;
163 size_t count = 0;
164 labels[start] = label;
165 stack.push_back(start);
166 while (!stack.empty())
167 {
168 const size_t index = stack.back();
169 stack.pop_back();
170 count++;
171
172 const size_t x = index % workWidth, y = index / workWidth;
173 const size_t neighbors[4] =
174 {
175 x > 0 ? index - 1 : index,
176 x + 1 < workWidth ? index + 1 : index,
177 y > 0 ? index - workWidth : index,
178 y + 1 < workHeight ? index + workWidth : index
179 };
180 for (size_t neighbor : neighbors)
181 {
182 if (labels[neighbor] == 0 && pixels[neighbor] > threshold)
183 {
184 labels[neighbor] = label;
185 stack.push_back(neighbor);
186 }
187 }
188 }
189
190 if (count > bestCount)
191 {
192 bestCount = count;
193 bestLabel = label;
194 }
195 }
196
197 if (bestCount < MIN_BLOB_PIXELS)
198 return result;
199
200 // Centroid weighted by brightness above threshold, plus statistics for the quality value
201 double sumWeight = 0, sumX = 0, sumY = 0, sumBlob = 0;
202 double sumSky = 0, sumSky2 = 0;
203 size_t skyCount = 0;
204 bool touchesEdge = false;
205
206 for (size_t y = 0; y < workHeight; y++)
207 {
208 for (size_t x = 0; x < workWidth; x++)
209 {
210 const size_t index = y * workWidth + x;
211 const double value = pixels[index];
212 if (labels[index] == bestLabel)
213 {
214 const double weight = value - threshold;
215 sumWeight += weight;
216 sumX += weight * x;
217 sumY += weight * y;
218 sumBlob += value;
219 if (x == 0 || y == 0 || x + 1 == workWidth || y + 1 == workHeight)
220 touchesEdge = true;
221 }
222 else if (labels[index] == 0)
223 {
224 sumSky += value;
225 sumSky2 += value * value;
226 skyCount++;
227 }
228 }
229 }
230
231 if (sumWeight <= 0)
232 return result;
233
234 // Each working pixel covers bin x bin frame pixels; map its center back to frame coordinates
235 result.x = sumX / sumWeight * bin + (bin - 1) / 2.0;
236 result.y = sumY / sumWeight * bin + (bin - 1) / 2.0;
237 result.area = static_cast<double>(bestCount * bin * bin);
238
239 // Quality: target must stand out from the sky noise and be bright enough in absolute terms
240 const double blobMean = sumBlob / bestCount;
241 const double skyMean = skyCount > 0 ? sumSky / skyCount : minValue;
242 const double skyStd = skyCount > 1 ? std::sqrt(std::max(0.0, sumSky2 / skyCount - skyMean * skyMean)) : 0;
243 const double signal = blobMean - skyMean;
244 const double fullScale = image.bytesPerComponent == 1 ? 255.0 : 65535.0;
245
246 double quality = skyStd > 0 ? clamp01((signal / skyStd - MIN_SNR) / (GOOD_SNR - MIN_SNR)) : 1.0;
247 quality *= clamp01(signal / (GOOD_SIGNAL * fullScale));
248 if (touchesEdge)
249 quality *= EDGE_FACTOR;
250 if (referenceArea > 0)
251 quality *= clamp01(1.0 - std::fabs(std::log2(result.area / referenceArea)));
252
253 result.quality = quality;
254 result.valid = quality > 0;
255 return result;
256}
257
259{
260 m_HasLock = false;
261 m_LockX = m_LockY = m_LockArea = 0;
262 resetWindow();
263}
264
265void FrameTracker::setLock(double x, double y)
266{
267 m_HasLock = true;
268 m_LockX = x;
269 m_LockY = y;
270 resetWindow();
271}
272
273void FrameTracker::resetWindow()
274{
275 m_WindowOpen = false;
276 m_WindowStart = 0;
277 m_Samples = m_ValidSamples = 0;
278 m_SumX = m_SumY = m_SumQuality = 0;
279}
280
281bool FrameTracker::addMeasurement(const Measurement &measurement, double time, double window, Report &report)
282{
283 if (!m_HasLock)
284 {
285 if (!measurement.valid)
286 return false;
287
288 m_HasLock = true;
289 m_LockX = measurement.x;
290 m_LockY = measurement.y;
291 m_LockArea = measurement.area;
292 resetWindow();
293 }
294 // An explicit lock has no area yet; take it from the first valid sample
295 else if (m_LockArea <= 0 && measurement.valid)
296 m_LockArea = measurement.area;
297
298 if (!m_WindowOpen)
299 {
300 m_WindowOpen = true;
301 m_WindowStart = time;
302 }
303
304 m_Samples++;
305 if (measurement.valid)
306 {
307 m_ValidSamples++;
308 m_SumX += measurement.x;
309 m_SumY += measurement.y;
310 m_SumQuality += measurement.quality;
311 }
312
313 if (time - m_WindowStart < window)
314 return false;
315
316 report = Report();
317 report.windowStart = m_WindowStart;
318 report.samples = m_Samples;
319 report.valid = m_ValidSamples > 0;
320 if (report.valid)
321 {
322 report.x = m_SumX / m_ValidSamples;
323 report.y = m_SumY / m_ValidSamples;
324 report.offsetX = report.x - m_LockX;
325 report.offsetY = report.y - m_LockY;
326 // Mean quality of valid samples times the valid fraction
327 report.quality = m_SumQuality / m_Samples;
328 }
329
330 resetWindow();
331 return true;
332}
333
334}
void setLock(double x, double y)
Lock to an explicit position. Restarts the averaging window.
static Measurement measure(const Image &image, double referenceArea=0)
measure Find the target in a single frame.
void reset()
Drop the lock point and the current averaging window.
bool addMeasurement(const Measurement &measurement, double time, double window, Report &report)
addMeasurement Add a measurement to the averaging window.
Namespace to encapsulate INDI client, drivers, and mediator classes.
bool bayer
Raw Bayer mosaic: binning is kept even so each bin averages whole CFA cells.
size_t bytesPerComponent
1 for 8-bit, 2 for 16-bit (native endian) samples
size_t components
1 for mono or Bayer, 3 for interleaved RGB
double quality
0 (unusable) to 1 (clean, well separated disk)
double area
Blob area in frame pixels.
double x
Centroid in frame pixels.
double offsetX
Averaged centroid minus lock point.
double quality
Mean quality of the valid samples, scaled by the fraction of samples that were valid.
double windowStart
Time of the first sample in the window.
bool valid
False if no sample in the window was valid (target lost).
uint32_t samples
Number of samples in the window.
double x
Averaged centroid in frame pixels.