{'fraction_non_alphanumeric': 0.0323060789553804, 'fraction_numerical': 0.011298670545651365, 'mean_word_length': 4.803297997644288, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 1, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Mask-ToF: Learning Microlens Masks for Flying Pixel Correction in Time-of-Flight Imaging

We introduce Mask-ToF, a method to reduce flying pixels (FP) in time-of-flight (ToF) depth captures. FPs are pervasive artifacts which occur around depth edges, where light paths from both an object and its background are integrated over the aperture. This light mixes at a sensor pixel to produce erroneous depth estimates, which can adversely affect downstream 3D vision tasks. Mask-ToF starts at the source of these FPs, learning a microlens-level occlusion mask which effectively creates a custom-shaped sub-aperture for each sensor pixel. This modulates the selection of foreground and background light mixtures on a per-pixel basis and thereby encodes scene geometric information directly into the ToF measurements. We develop a differentiable ToF simulator to jointly train a convolutional neural network to decode this information and produce high-fidelity, low-FP depth reconstructions. We test the effectiveness of Mask-ToF on a simulated light field dataset and validate the method with an experimental prototype. To this end, we manufacture the learned amplitude mask and design an optical relay system to virtually place it on a high-resolution ToF sensor. We find that Mask-ToF generalizes well to real data without retraining, cutting FP counts in half.


Introduction
Large-scale image datasets such as ImageNet [15] and CIFAR [31,32], in tandem with a boom in computational resources, drastically reshaped the field of image processing. In the depth domain, a similar trend [61,8,13] has recently made the mass-acquisition of high-quality depth maps a vital prerequisite for a range of 3D graphics and vision applications. These include human-centered tasks such as pose tracking [59,29], action recognition [26,51], and facial analysis [56], as well as scene-understanding problems including mapping [19], segmentation [14], and object reconstruction [70,10,75]. While methods look to captured depth datasets for ground truth, the devices used to capture them are subject to a slew of error sources which, if not addressed, can hurt task performance and generalizability. One of many approaches to depth acquisition is passive sensing: exploiting parallax cues to infer distances solely from input monocular [66,41,18] or multiview [24,27,73] images. These methods can use standard RGB cameras for data acquisition, but struggle with textureless regions and complex geometries [63,36]. Active sensing approaches tackle this challenge by first sending out a known illumination into the scene and reconstructing depth with the help of the returned light. These include structured light methods such as active stereo, where spatially patterned light is projected into the scene to aid in the stereo feature matching process [1]. While being robust to textureless scenes, their accuracy is fundamentally limited by illumination pattern density and sensor baseline, resulting in a bulky camera form-factor. Some of the most successful active depth sensing methods are time-of-flight (ToF) approaches, where depth is estimated from the travel time of light leaving and returning to the device. Direct ToF systems such as LiDAR send out individual laser pulses and measure their time to return using time-resolved sensors such as avalanche photo diodes [12]. These can provide high-accuracy and longrange depth estimates, but use a scanning approach to collect data, leading to poor depth completeness and/or expensive sensor array systems. In contrast, amplitude-modulated continuous wave (AMCW) ToF cameras, the focus of this paper, flood-illuminate a scene with periodic amplitudemodulated light and estimate the phase shift of returned light to infer depth. These devices do not need to timeresolve captured light like their direct ToF counterparts, and so can rely on an easy-to-manufacture CMOS sensor array to produce complete depth maps at a high framerate. This, when combined with their small sensor-illumination baseline, makes AMCW ToF cameras compact and affordable, and has led to their widespread adoption in the vision community. Devices such as those in the Microsoft Kinect series have subsequently helped create community-made freelyavailable scene understanding benchmarks that lower the barrier of entry for 3D vision research [64,2].
Although they promise to democratize low-cost dense depth imaging, AMCW ToF methods are still subject to fundamental limitations of the sensing process: noise from ambient light, photon shot, phase wrapping, multipath interference (MPI), and flying pixels (FPs) [16]. There has accordingly arisen a large body of work in computational postprocessing methods to address these issues; methods concerning depth denoising [17,74], phase unwrapping [35], and MPI correction [42]. Contrastingly, while confidencebased methods [55] are able to identify flying-pixels, rectifying them -recovering the depth of their corresponding chief ray -has remained a great challenge.
FPs are formed when light from both an object and its background reaches the same sensor pixel, generating a mixed depth measurement. These often appear to be floating in empty space in the resultant point cloud, hence flying pixels. Computationally unmixing these FPs often leads to edge blur or severe artifacts [72]. As they originate in the optical pipeline, artifacts of the light collection process by the main lens, we argue that an effective strategy to mitigate them should also start in the optical pipeline. Unfortunately, a direct masking approach, such as simply reducing aperture size to block stray light paths, is not efficient for overall light throughput, and so significantly lowers SNR.
With Mask-ToF we learn a microlens amplitude mask, allowing us to generate per-pixel aperture configurations with spatially-varying susceptibility to noise and FPs, as shown in Figure 1. We train an encoder-decoder network which learns to aggregate this spatial information and leverages mask structural cues to produce refined depth estimates. We then backpropagate this net's loss to jointly learn high-level mask patterns. We photolithographically manufacture the learned mask, and virtually place it on the sensor with a custom optical relay system to validate Mask-ToF on real-world data. In the future, we expect this mask can be fabricated directly on the camera sensor in a similar manner to a polarization sensor [47], preserving its form factor.
In summary, we make the following contributions: • We develop a differentiable AMCW ToF image formation model, including sub-aperture light transport.
• We incorporate sub-aperture masking and a refinement network into this framework and learn an optimal mask structure through a patch-based gradient descent approach from synthetic data.
• We test the masks in simulation, evaluating on overall error and FP reduction, then manufacture them and construct an experimental setup to validate the proposed method on real data.

Related Work
Depth Imaging. There exists a wide body of work in both passive and active methods for depth imaging. The former operates with only passive depth cues, such as parallax [24,5,46] and defocus [66,66], to infer depth. These methods exhibit diminished accuracy for textureless scenes with few visual cues and complex geometries with ambiguous cues [63]. Active methods overcome this challenge by sending out a known illumination pattern into the scene and using the returned signal to help reconstruct depth. While structured light approaches rely on this illumination to improve local image contrast [58,1], ToF imaging uses the travel time of light itself to measure distance [23,60]. This sensing approach allows for compact illumination-sensor setups and does not hinge on ambiguous visual cues.
ToF Imaging. ToF imaging can be further categorized into direct and indirect methods. Direct ToF devices such as Li-DAR send out pulses of light, scanning over a scene and directly measuring their round-trip time via avalanche photodiodes [12,50] or single-photon detectors [45,22]. While accurate and long-ranged, these systems can produce only a few spatial measurements at a time, resulting in sparse depth maps [40]. Furthermore, their specialized detectors are orders of magnitude more expensive than conventional CMOS sensors. AMCW ToF imaging, a representative indirect ToF method, instead floods the whole scene with periodically modulated light and infers depth from phase differences between captures [20,34]. These captures can be acquired with a standard CMOS sensor, making AMCW ToF cameras an affordable solution for dense depth measurement. Ultimately, all these devices integrate light over an aperture and are thus susceptible to FPs [55,57].
Depth Reconstruction Methods. Depth cameras are all subject to erroneous measurements, which has led to a wide array of work in robust depth reconstruction algorithms. Some approaches attempt to learn a direct mapping between noisy and clean 3D points [44,49], though they are limited in their scope and scalability as they contend with graph operations on unstructured point cloud data [53,54]. Correlation between color and depth has also been used to smooth noisy depth estimates and enforce view consistency [30,38], though these approaches often blur object edges, producing more FPs. Confidence-based methods for ToF [55,17] on the other hand can detect FPs as unreliable measurements, but lack the context needed to determine if they belong to an object, background, or intermediate depth.
Mask-ToF resolves this problem with a two-stage, generalizable approach that joins reconstruction with the optical pipeline; where a spatially varying amplitude mask encodes the information needed to correct these flying pixels.
Masks for Computational Imaging. Masks enable an imaging system to directly modify the point spread function (PSF) of input light, densely encoding information about the scene that can be computationally recovered postcapture. Amplitude masks can only attenuate light, yet have a wide range of applications including light-field [43], lensless [4], x-ray [52], high-speed [39], and spectral imaging [3]. Phase masks can allow for finer manipulation of PSFs [11], and may be of interest in future masked ToF projects, but are prohibitively expensive to manufacture at a micro-scale resolution. In this work we learn an occlusion mask with spatially varying microlens apertures, encoding scene geometric information in AMCW ToF measurements to help correct FPs during reconstruction.
End-to-End Design of Optics and Computation. Conventional imaging systems are designed in a sequential manner: first develop the optical and sensor stack in isolation, driven by compartmentalized metrics, then delineate an image processing pipeline [69]. Recently, a new paradigm of jointly optimizing optics and reconstruction has emerged, where all stages are jointly optimized in the design phase. These hold promise for applications in extended depth-of-field [62], microscopy [48], monocular depth [9], HDR [67], hyperspectral [6], and transient [68] imaging. Inspired by these works, Mask-ToF uses a differentiable ToF simulator to jointly learn an optimal mask pattern and train a depth refinement network to produce high SNR, low FP depth maps.

Image Formation
Before introducing our proposed method, we review the fundamentals of AMCW ToF imaging; for details see [33].
Pinhole Model. Correlation ToF cameras flood-illuminate the scene with an amplitude-modulated light signal Here ω is a modulation frequency, α is amplitude, and β is signal bias. Under a pinhole camera model this modulated light is perfectly reflected by an object and captured by the ToF camera after travel time τ . The measured signal is effectively p(t) with attenuated amplitudeα, shifted bias β, and an introduced τ -dependent phase shift φ. The camera then correlatesp(t−τ ) with an identically modulated reference signal r(t) = cos(ωt + ψ) to produce for integration time T τ . By sampling correlation values C(ψ) at four different phase offsets ψ = [0, π/2, 3π/2, π], we can extract the measured signal's true phase φ from This arctangent, however, introduces a 2πn phase ambiguity for depths z ≥ λ = c/2ω, halved for the round-trip distance and with c being the speed of light. To estimate this factor n we can use a phase unwrapping algorithm [35], which typically solves instances of Equation (4) for multiple modulation frequencies ω and disambiguates φ via Euclidean division [71]. This estimate is ultimately converted to depth as z = φc/4πω.
Lens Model. In a practical camera system, to increase light throughput, we use a lens to focus light incident on an aperture plane U to a sensor pixel x; for simplicity we assume a 2D model. We thus rewrite the image formation model aŝ wherep x is the measurement at pixel x, A(·) is a binary aperture function, u ∈ U is the aperture coordinate, and τ u is an additional time-of-flight term incurred by the residual path length.p x , τ x refer to Equation (2) evaluated for a ray connecting through point u to x. The length of this ray is where f is the focal length of the lens, z is the depth of the scene point, and r is the lens radius. For a typical AMCW ToF camera, with operating range z r and modulation frequency ω = O(10 8 Hz), the phase contribution from the residual distance term δ u,x = d u,x − d 0,x is negligible. We thus discard the corresponding time-of-flight term τ u , and approximate the image formation model aŝ Flying Pixels. While for an unobstructed point z this image formation is adequate, an edge case arises for points at a depth discontinuity. Suppose there is a single pixel on the sensor whose chief ray (u = 0) comes from an x near an object edge, see Figure 2. This would mean that for part of the aperture coordinates, U F , we would receive unfocused light rays from the foreground object, with travel time τ , while the other rays passing through U B = U \ U F would have the intended travel time τ . The received signal would similarly consist of a mix of both foregroundp F whereφ is the measured phase shift of this mixed signal. Solving Equation (4) returns an incorrect depthẑ somewhere between the foreground and background depths.
Aperture-Masked ToF Image Formation. It might seem that a simple solution to the above flying pixel problem is just to reduce the aperture size. In the extreme case where A(u) = 0, ∀u > 0, we retain only the chief ray and so have no mixed measurements. Unfortunately, this also leads to poor light efficiency, which lowers the system's SNR as it becomes more susceptible to photon shot. We provide a detailed discussion of this fundamental SNR/FP tradeoff in the Supplemental Document. To better maintain light throughput, we can selectively block light paths by applying a spatially-varying microlens amplitude mask M x (u) to the image plane. The model from Equation (7) thus becomeŝ One could imagine an ominscient mask M x (u) = 0 for u ∈ U F , else M x (u) = 1. This would remove unfocused foreground light and preserve all other light paths, perfectly correcting FPs with high SNR. Unfortunately, such a mask could only work for a single scene, and we would need to know that scene beforehand to design it. Instead, with the derivations above, we can form a differentiable framework for AMCW ToF image formation and use gradient descent to learn a single generalizable mask pattern. We describe this approach in the following section.

Learning to Mask Flying Pixels
Mask Intuition. Before we outline how to learn a mask, it's important to intuit why a static mask could help correct FPs in the first place. With a global aperture, shown in Figures 1 and 2 (b), all pixels are equally susceptible to FPs; if one sensor pixel returns an FP, likely so will its neighbors. The addition of spatially variable susceptibility via a microlens mask, shown in Figures 1 and 2 (c), means this is no longer the case. A sensor pixel with a wide effective aperture can be trusted with regards to noise statistics but is likely to return FPs when near an object boundary. Contrastingly, a neighboring pixel with a narrow aperture will likely produce noisier measurements, but be less affected by depth discontinuities. By aggregating information in pixel neighborhoods, we can effectively use wide aperture pixels to denoise local measurements, and narrow aperture pixels to de-flying-pixel them. This means a Mask-ToF approach critically needs not only a mask, but also a method to decode the information encoded by the mask.
From Light to Time-of-Flight. Given ground truth depth, we can simulate ToF measurements via Equation (2) without distinguishing between light rays. However, to apply the mask M x (u) as in Equation (9), we also need access to the aperture plane U. We thus discretize the image formation model and use light fields [37] as a natural parametrization Herep u,x is our ToF signal, a sum over sub-aperture views u in the light field L, discretized now in both x and u. As the number of sub-aperture views |L| → ∞ we converge on the form of Equation (9), though in practice |L| governs mask resolution and is limited by manufacturing constraints.
Tensor Image Model. Rather than operate onp u,v,x,y , in 3D space we swap to a tensor view of simulation, as visualized in Figure 3 (c). We start with a depth map D ∈ R H×W , which we convert to phase array Φ, and with the light field tensor L simulate 4×|L| correlation images C 0,0 − C 3,|L| . One for each of four phase shifts ψ and sub-aperture arrays L u ∈ L. These are individually masked by M u , and the views are averaged to produce 4 final correlation images C ψ , subject to simulated noise η ψ . This process is summarized in Equation (11).  The refinement network R, with skip connections in gray, which aggregates mask and coded depth information to produce a reduced FP output. (c) Stages of the differentiable simulation pipeline, from input light-field data to output refined depth.
Here g is sensor gain, T is integration time, H×W is the sensor size, and denotes element-wise multiplication. The noise constants a, b, µ, σ are chosen empirically. At high photon counts, Poisson and Skellam [7] noise can be well approximated by scaled Gaussian noise, thus η generalizes many expected sources of ToF noise [21] while maintaining simulation differentiability.
Depth Reconstruction. Using Equation (4) we generate an estimated depth mapD from the four masked correlation images C ψ . We implement this as a differentiable func-tionD = P (C) with automatic gradient evaluations. This grants us flexibility as we can swap P (C) for other depth estimation methods, such as the discrete Fourier transform, if needed. To process the information embedded in these measurements by the microlens mask, we propose a refinement network R, illustrated in Figure 3 (b). R is a residual encoder-decoder model, inspired by the hourglass architecture from [73], which takes as inputD and M and outputŝ whereD * is the refined depth map andD R is a learned residual depth which when added toD serves to correct the now spatially multiplexed effects of noise and FPs. As Equation (4) does the initial depth calculation, R does not have to learn how to generate depth from phase, and can be made significantly more lightweight than a typical deep reconstruction network. This helps R to quickly learn highlevel depth and mask features, and generalize well to arbitrary scenes where raw phase data might significantly differ from the training set. The sequential depth estimation and refinement approach also allows us to naturally exploit calibration procedures [29] implemented by the sensor manufacturer. We can feed real depth data directly into R without having to retrain and learn calibration offsets.
Smooth L1 loss L S helps enforce local smoothness in the reconstructed depth map, controlling the Gaussian noise η while being less sensitive to depth outliers. To penalize these outliers, we add a Chamfer loss term L C . It considers the projected points proj(p), which we produce by concatenating sensor coordinates x, y to the corresponding depth values z, and penalizes points based on their distance to the nearest ground truth point. FPs, which exist in the empty space between foreground and background depths with no close neighbors, are thus heavily penalized. We balance these losses with weights w L and w C .  Patch-based Training. We can propagate the gradient of this loss through the differentiable framework above all the way to the mask M, however, learning an unconstrained M proves computationally burdensome. We thus restrict M to be an m×n tiling of a mask patch M P and learn M P instead, adopting a patch-based stochastic gradient descent approach. We sample a batch of random patches from the input light field and ground truth depth, and update M P and R based on the patch loss. This effectively exponentially increases the number of available samples for training, allowing us to rely on a relatively small light field dataset. As R is fully convolutional, it is invariant to input shape, and so this patch training generalizes well to the full-sized images.

Synthetic Assessment
Implementation. Our network R is trained on patches of size 80×80×9×9 sampled from 512×512×9×9 synthetic light field data. This data, sourced from [25], contains 9×9 sub-aperture views per image pixel, and a total of 16 light fields. The full-sized evaluation masks are constructed by an 8×8 tiling of the center 64×64 area of the learned mask M P , reducing edge artifacts from training. Noise parameters a, b, µ, σ from Equation (11) are set to 0.75, 1.25, 0, 3; empirically matched to real recorded ToF samples. We set sensor gain to g = 20 and integration time to T = 1 ms.
The ADAM optimizer was used for training [28], with an initial learning rate of 0.004 for the refinement network R and 0.1 for the mask M P . We halve both rates every 80 epochs. M P is not updated for the first 70 epochs of training, as these epochs tend to be extremely noisy, the convolutional layers of R having not yet learned high-level structures [76]. Through empirical study we found weights w L = 100 and w C = 0.08 to effectively balance the differing scales of Chamfer and smooth L1 loss in Equation (13). We leave δ as the default δ = 1. The network contains 19 million learnable parameters, 1 million of which are the amplitude mask, and is trained for 3 hours on a single Nvidia Tesla V100. Inference time for a single 512×512 image is ≈ 8 ms. Code and trained models will be made available.
Ablation Study. We quantify the effects of architecture design choices in a series of ablation experiments, summarized in Table 1. Here, Proposed is our final network R, and Chamfer Only/L1 Only are tests where we train R using only the respective loss function. In the Half modification we remove the first hourglass, H1, while in Big we double intermediate channel counts in R. These help gauge if the network can be simplified or requires increased parametrization. The Global modification adds another global channel, implemented by duplicating H1 with increased stride lengths and concatenating the new signal at the input to H2, to test if the network can be improved by aggregating more non-local information. The No Mask tests the effect of training R on only depth data, without mask input. Lastly, ToFNet is a reimplementation of the ToFNet architecture from [65]. We train it until convergence with weighted L1 and TV loss as suggested in the original work, and fine-tune the learning rate to our data.
We validate the proposed architecture of the network R with the results in Table 1  method wins in all categories compared to the Big and Half, suggesting it is adequately parametrized. The lack of improvement from Global also suggests that the network R is sufficiently utilizing non-local information. Chamfer Only and No Mask both lead to lackluster performance, emphasizing the value of the L1 regularization term and mask comprehension, respectively. Although we see close results for L1 Only, the addition of Chamfer loss does lead to a reduction in outliers, expressed in RMSE and threshold metrics. ToFNet shows overall worse performance than our Baseline refinement architecture, with the network learning to reconstruct a smooth depth map, however not learning to remove flying pixels. This is possibly due to its significantly wider scope; lacking a skip layer to the output, it must learn to reconstruct depth from raw phase measurements.
Analysis of Mask Patterns. Mask-ToF contains a feedback loop: a change in the mask structure of M P necessitates an update to the refinement network R, which itself alters the propagated loss gradient and changes the structure of M P . Thus, to avoid local minima, we test a broad set of both human-selected and randomly generated initial masks including: various diameters of circular aperture, Gaussian and Bernoulli noise, randomly oriented barcode structures, and several multiplexed designs. A full discussion of mask patterns is available in the Supplemental Document. We compare the final optimized mask against the best hand-crafted (naïve) initializations to validate our proposed end-to-end optimization method. For a fair comparison, we fine-tune the refinement network R for each of these handcrafted mask designs and highlight the drop in performance from a lack of joint mask optimization. Results are displayed in Figure 3 and quantified in Table 2. We see that the Diameter 1 mask achieves low error for the 15mm thresh-  old metric and RMSE, which we find to be a good proxy for FP count. Even with the refinement network, however, its low light throughput leads to a large amount of noise, resulting in poor MAE and RMSE values. On the other end of the spectrum, the All-Ones (open-aperture) mask produces smooth low-noise reconstructions, but with copious FPs. The optimized mask design wins in all categories, with the low FP count and high SNR, and provides nearidentical light throughput as the Diameter 5 mask (13 times the throughput of the Diameter 1 pinhole mask).

Experimental Assessment
Mask Fabrication. We fabricate our custom mask patterns via photolithography. 0.5mm fused silica wafers are used as the substrate, receiving a 200nm of chromium film to occlude light. A layer of 0.6 µm thick photoresist AZ1505 is then spin-coated on top. We place the wafer under a master mask on a contact aligner (EVG 6200∞) for UV exposure, and develop in AZ726 to form the mask pattern on the photoresist. With an etchant we then remove the chromium from under open areas in the photoresist. See the Supplemental Document for further information on fabrication.
Prototype. We capture measurements with an AMCW ToF camera (Helios Flex, Lucid Vision) operating on an NVIDIA Jetson TX2. We use a custom-designed 1:1 Keplerian telescope as an optical relay system to virtually place the mask on the sensor (see Figure 5). This eliminates the need to remove the sensor cover glass and allows for rapid prototyping, but in a commercial product can be supplanted by a directly integrated mask to maintain device form factor. The mask sits on the intermediate image plane of the telescope attached to a precision microscope slide, which is optically conjugate with the sensor plane. We adjust the position of the mask with an XYZ translation stage (Thorlabs PT3A). For more details, see the Supplemental Document. Results. Depth maps were captured via the previously described setup and fed directly into the synthetically trained refinement network R, with no network fine-tuning. By counting points as in Figure 7, we see that Mask-ToF cuts flying pixel counts in half when compared to an open aperture. Compared to the near-identical light throughput Diameter 5 mask we reduce FPs by an additional 30.5%. These results are qualitatively confirmed in Figure 6 for objects of varying geometry and reflectance, with additional results in the Supplemental Document and 3D rendering in the accompanying video. Our optimized mask reconstruction visibly and significantly reduces FPs as compared to Diameter 5, while maintaining object shape consistency with the open aperture measurements. Of note is how sharply Mask-ToF reconstructs the tips of the Plant example's petals, as compared to the noisy reconstruction produced by the Diameter 5 mask. Additionally, Mask-ToF is even able to reduce intra-object FPs such as those inside the Plant's pot.

Conclusion
Mask-ToF is an end-to-end approach to tackle the longstanding problem of flying pixel artifacts in time-of-flight imaging. It learns a per-pixel microlens amplitude mask, that, when combined with a jointly trained refinement network, reduces FPs while preserving light throughput. We validate the method both in simulation and experimentally, manufacturing the learned mask and optically placing it on a camera sensor with a custom-designed optical relay system. The proposed mask and reconstruction method outperform existing hand-engineered masks (and no mask) for real-world scenes. In a mass-market implementation of our method, we envision the amplitude mask to be integrated as part of the sensor assembly, maintaining the camera formfactor while improving FP statistics. Future research directions include learned phase mask patterns and dynamic masks, implemented via a spatial light modulator or similar, which adapt their structure to the observed scene.