<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Julien Sahli on Medium]]></title>
        <description><![CDATA[Stories by Julien Sahli on Medium]]></description>
        <link>https://medium.com/@julien.sahli?source=rss-5246763fb747------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Hp_pyUTFLA20jqQxVkaytw.png</url>
            <title>Stories by Julien Sahli on Medium</title>
            <link>https://medium.com/@julien.sahli?source=rss-5246763fb747------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:57:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@julien.sahli/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Simulating lensless camera data from 3D scenes]]></title>
            <link>https://medium.com/@julien.sahli/simulating-lensless-camera-data-from-3d-scenes-a3da3daf50e?source=rss-5246763fb747------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3da3daf50e</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[optics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[cameras]]></category>
            <dc:creator><![CDATA[Julien Sahli]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 16:13:13 GMT</pubDate>
            <atom:updated>2023-03-21T14:17:31.240Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reconstructing 3D scenes from lensless data and simulating the collection of such lensless data from virtual scenes — Part 3/3</h4><p><em>This work is in line with the </em><a href="https://github.com/LCAV/LenslessPiCam"><em>LenslessPiCam</em></a><em> project conducted at the </em><a href="https://www.epfl.ch/labs/lcav/"><em>LCAV</em></a><em> lab from EPFL. Before continuing, if you wish to delve in the subject more in detail, a general introduction to this project as well as links to specific parts of its implementation can be found in </em><a href="https://medium.com/@bezzam/a-complete-lensless-imaging-tutorial-hardware-software-and-algorithms-8873fa81a660"><em>this post</em></a>, <em>and the corresponding code is available at </em><a href="https://github.com/LCAV/LenslessPiCam"><em>this link</em></a><em>. The current work aims at extending it to 3D as well as building a lensless data simulator. (The corresponding code will be available soon).</em></p><p>This work is divided in three parts:</p><ul><li><a href="https://medium.com/@julien.sahli/3d-imaging-with-lensless-camera-822983618455">Part 1: 3D Imaging with lensless camera</a></li><li><a href="https://medium.com/@julien.sahli/simulating-lensless-camera-psfs-with-ray-tracing-a224ca11f758">Part 2: Simulating lensless camera PSFs with ray tracing</a></li><li><strong>Part 3: Simulating lensless camera data from 3D scenes</strong></li></ul><h3>Simulating lensless data</h3><p>Now that we have achieved to simulate the PSFs of diffuser-based and mask-based lensless cameras, the next step is to simulate the lensless data that would be produced by using these cameras to capture arbitrary scenes.</p><p>As we have done above in order to characterise the cameras that we simulated, we will need specify some parameters describing the scenes that we will render:</p><ul><li><strong>Scene minimum depth:</strong> The distance between the mask/diffuser and the closest element of the scene, along the depths axis. (e.g. 0.8 cm)</li><li><strong>Scene maximum depth:</strong> The distance between the mask/diffuser and the furthest element of the scene, along the depths axis.(e.g. 2 cm)</li><li><strong>Scene width/height:</strong> The width and height at the back of the scene (e.g. 20 cm × 20 cm)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*EiW9rksmOzjb1zPAWuD4QQ.png" /><figcaption><strong>Characterisation of the scene</strong></figcaption></figure><p>The shape of the scene that we will render will not be a rectangular cuboid, but the section of a frustum whose vanishing point is the mask/diffuser; in other words, a rectangular pyramid whose tip would be located at the position of the diffuser and whose base would be parallel to the diffuser, but truncated.</p><p>Such geometry has a main property which we will take advantage of later: if we project the whole scene on either of its faces that are perpendicular to the scene-diffuser axis, we can generate a radiance map with the following propriety : the scaling between the points of the radiance map and the light actually collected by mask/diffuser will always be the same for a given scene, regardless of the depth of the light source from which the light comes from.</p><p>Thanks to this property, providing explicitly the exact position of each element from the scene will not be necessary. The only data that we will need to provide is the radiance map associated to the scene as well as a corresponding depth map, which will specify the distance between the diffuser and the objects responsible of emitting the light registered in the radiance map. This input is actually closer to the actual data gathered by a real camera that what a whole 3D scene would be; in particular when some objects are hidden behind other ones.</p><p>The radiance map and the depth map will either be generated by hand or from rendering software (such as <a href="https://www.blender.org/">Blender,</a> which is able to run custom python scripts in order to get the depth map).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nb_jSrRPLerk3tmdDK2qfg.png" /><figcaption><strong>An example of a scene featuring the LCAV logo. The radiance map describes the quantity and the colour of the light reaching the mask/diffuser, and the depth map the distance between the corresponding part of the model and the sensor, with darker pixels corresponding to closer distances</strong></figcaption></figure><p>Of course, as soon as we will use 3D PSFs to generate lensless data from a such scene, the depth range of the scene will need to match the depths that were sampled when generating the PSF; i.e. to render a scene with a minimum depth of <strong>0.8</strong> cm and a maximum depth of <strong>2</strong> cm, we will need a PSF that was generated with a set of depths that range from <strong>0.8</strong> cm to <strong>2</strong> cm (included). The more depth layers the PSF will have, the more precise our simulation will be. But before using PSFs, let’s quickly review a first version of the renderer that uses ray tracing and serves as comparison for the convolution-based renderer that we will present afterwards.</p><h4>Ray tracing renderer</h4><p>Ray tracing is a simple and intuitive way to illustrate how the light coming from the scene should behave through the cameras optic. However, its main disadvantage with respect to the convolution-based renderer is the computation time (more on that later). Even by limiting it to the cameras which have a mask as optic, rather than an actual diffuser, the amount of rays that we would need to trace to fully render the effect of the whole scene on the sensor would be equal to the amount of pixels in the radiance map times the amount of pixels of the collected image. Without the use of appropriate stochastic approximations, having a scene of 1000 px × 1000 px and an output image as big would need to trace as much as 1000 billion rays ! We will therefore limit the use of the ray tracing renderer to very small scenes, that will be used to compare with the result of the convolution-based renderer.</p><p>The functioning of the ray tracing renderer is quite straightforward : we give it a radiance map and a depth map as well as the shape of the mask that serves as the camera optic; then, for each pixel of the radiance map, we trace a ray between it and each point of the sensor and compute how much light goes through, in a very similar way that we generate mask-based PSFs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*MIBfInYtUwSVNXrarv7Obg.png" /><figcaption><strong>A simulation using a camera characterised by the mask (top left) outputs the corresponding lensless data (top right) when exposed to a scene with the following radiance map (bottom left) and the depths map (bottom right)</strong></figcaption></figure><p>Notice how the shape of the mask gets projected on the sensor. Also notice how the green and red projections are dimmer, since the corresponding depth map places them farther away from the camera.</p><p>We could expect the red and green projections to be closer to the centre of the sensor as the corresponding light sources are farther away from the scene but have the same lateral position as the blue and white dots on the radiance map ; but we must remember that the radiance map is already built while accounting for projection of the scene towards the camera, hence it is not the case. It only means that in an orthogonal coordinate system, the red and green light sources would not only be farther away in the Z-axis, but also shifted accordingly along the other axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*3ooHFENtpSdphfHhPqFYow.png" /><figcaption><strong>The blue and green dots (respectively the white and red dots) get projected on the radiance map with the same horizontal position, but do no have the same horizontal position in orthogonal coordinates.</strong></figcaption></figure><p>The functioning of the ray tracing renderer doesn’t rely on the assumption that the PSFs are horizontally and vertically shift-invariant and the produced scenes can therefore be compared to the ones generated through the convolution-based renderer in order to verify that this assumption is indeed sufficiently close to reality in order to be used. As a reminder : the reconstruction algorithms make this assumption in order to define the forward model as a convolution of the scene radiance and the PSFs. It does so despite the fact that PSFs are technically not shift-invariant, but the practical scale of the various parts of the scene and the camera reduce the actual difference to such minimal amounts that it can be neglected while still producing satisfactory results. In the simulation case, we will make the same assumption and allow for much quicker computations by using fast convolutions rather than manually tracing a large amount of rays for each pixels of the radiance map, as we shall now see.</p><h4>Convolution-based renderer</h4><p>The convolution-based renderer, on its side, supports any kind of optics whose PSF is known and is not limited to masks. It basically works by performing the inverse task than the 3D reconstruction: it virtually splits the input scene in different depth layers (one for each depth level of the provided 3D PSF) and performs the convolution of the radiance corresponding to this depth with the corresponding depth level of the PSF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*HlmqkVkYQEyF7dkqgRmuEA.png" /><figcaption><strong>The scene is split in different depth layers in the exact same way as it in the reconstruction algorithm</strong></figcaption></figure><p>It is worth noting that the convolution-based rendered assumes that the PSFs are shift-invariant, which is not the case for the ray tracing renderer. Therefore, certain scenes configurations where this assumption does not holds (such as very large dimensions for the sensor and the scene, relatively to the distance in-between, allowing the projection of the diffuser’s patterns to be stretched out for light sources in the borders of the scene) could be rendered in a non-realistic way; but because the reconstruction algorithm also needs to make this assumption, these are scenes that could not be reconstructed from real data anyway.</p><p>Now, the main difficulty of this approach is to scale correctly the radiance map relatively to the PSF. Indeed, the PSFs we provide are generated by accounting for specific metric parameters, as we have seen. When we specify the radiance map from our scene, we do so with an arbitrary pixel resolution. However, if we simply take the radiance map as is, split it according to the corresponding depths and convolute each part with the appropriate PSF, we will get different results depending on its resolution; that means inconsitstant scaling of the scene.</p><p>Indeed, the images that we have for each depth of the PSFs describe the light received on the surface of the sensor. Each pixel of these PSF represent a surface equal to the width and height of the sensor divided by the width and height of the image in pixels. Moreover, the light in provenance for any point of the diffuser will form a certain angle with each of these surfaces. The value of this angle depends on the size of the surface, but also of the distance between it and the diffuser. These angles need to be equivalent to the ones that are formed while projecting the light coming from the radiance map into the sensor.</p><p>In other terms, for the PSF to be meaningful, the two following ratios have to be equivalent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UlhOKOPoNsGd4BgUgt_Mew.png" /></figure><p>As in practice, the metric density (that means how much physical surface is represented by a pixel) of the radiance maps used is usually higher than that of the PSF, we upsample the PSF to the appropriate size rather than downsampling the radiance map in order to avoid information loss. Of course, this requires to downsample the convolved data afterwards so that it matches with the original PSF.</p><p>In other terms, as the ratio between the distance of any slice of the scene with the diffuser and its width/height is constant, we must set the PSF resolution to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eY18jynY3kMbodVpYn2PEA.png" /></figure><p>That being done, all that remains to be done is to compute the convolution between each scene layer and the corresponding PSF and to stack all of the results in a single image, since the light from all depths gets projected on a single sensor. Each layer can be computed individually on a separate thread to improve performance.</p><p>This is how it translates in terms of code:</p><pre># pseudocode<br>def simulate_scene(psf, cam_settings, radiance_map, depths_map):<br><br>  # split the scene in several layers<br>  psf_depths = range(psf.shape[0])/psf.shape[0]* (cam_settings.scene_max_dep<br>      - cam_settings.scene_min_dep) + cam_settings.scene_min_dep<br>  scene_depths = depths_map * (cam_settings.scene_max_dep<br>      - cam_settings.scene_min_dep) + cam_settings.scene_min_dep<br>  thresholds = [psf_depths[0]] + [(psf_depths[i] + psf_depths[i + 1]) / 2<br>                for i in range(psf_depths.size - 1)] + [psf_depths[-1]]<br>  <br>  slices = split(radiance_map, scene_depths, thresholds)<br>  <br>  # outputs a partial radiance map for each psf_depth. The map is empty<br>  # everywhere exept for the pixels whose corresponding depth is included<br>  # in the between the right thresholds <br>  # resize the psf accordingly<br>  new_res_x = radiance.shape[0] * cam_settings.sensor_width  *<br>              cam_settings.scene_max_dep / (cam_settings.scene_width *<br>              cam_settings.distance)<br>  new_res_y = radiance.shape[1] * cam_settings.sensor_height *<br>              cam_settings.scene_max_dep / (cam_settings.scene_height *<br>              cam_settings.distance)<br>  <br>  # keep the scaling in memory for later<br>  factor_x = psf.shape[1] / new_res_x <br>  factor_y = psf.shape[2] / new_res_y<br>  <br>  # actually resize the psf<br>  for p in psf:<br>    p = p.resize(new_res_x, new_res_y)<br>  convolved = array(psf_depths.shape)<br>  <br>  # each execution of this loop is independant and can be computed in an<br>  # indepentent thread<br>  for i in range psf_depths.shape:<br>    convolved = convolve(slices[i],psf[i]) # e.g. with scipy.signal.fftconvolve<br>  <br>  # sum and scale the output back<br>  result = sum(convolved, axis=0)<br>  result = result.resize(result.shape[0] * factor_x,<br>                         result.shape[1] * factor_y)<br>  return result</pre><p>Now, if we take the same scene that we rendered with the ray tracing renderer and try to compute it as well with the convolution-based renderer, we obtain the following data, and see that it is indeed equivalent!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*uxCSEi8dgCygIYjKVYk_Hw.png" /><figcaption><strong>Comparison between the two render engines</strong></figcaption></figure><h3>Results showcase</h3><p>Now that we have both extended the LenslessPiCam reconstruction algorithm to 3D and implemented a 3D lensless data simulator, let’s:</p><ul><li>Build a scene and a PSF;</li><li>Generate the corresponding lensless data;</li><li>And try to reconstruct it!</li></ul><p>We will take the radiance and depth maps of one of the scene that we presented before :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nb_jSrRPLerk3tmdDK2qfg.png" /></figure><p>For the PSF, we will take one that was generated with the height map that we presented before and whose parameters are the following :</p><ul><li><strong>Sensor Dimensions : 1.5 cm × 1.5 cm</strong></li><li><strong>Diffuser Dimensions : 1.0 cm × 1.0 cm × 0.01 cm</strong></li><li><strong>Sensor-Diffuser Distance : 0.15 cm</strong></li><li><strong>Scene Width/Height : 20.0 cm × 20.0 cm</strong></li><li><strong>Scene Depth : 0.8 cm to 2.0 cm</strong></li></ul><pre>#Set the scene parameters :<br>python scripts/simulator/store_settings.py --path=custom --scene_min_depth=0.8<br> --scene_max_depth=2 --sensor_width=1.5 --focal_distance=0.15 --scene_width=20<br><br>#Generating a new PSF from a height map :<br>python scripts/simulator/generate_psf.py --input_fp=heights.png<br> --output_fp=result.npy --mode=height --save_normals --camera_fp custom-cam.npy<br><br>#Rendering the scene:<br>python scripts/simulator/render_scene.py --radiance_fp=scene.png<br> --depths_fp=scene_dep.png --psf_fp=psf.npy --out_fp=out.png<br> --camera_fp custom-cam.npy --scene_fp custom-scene.npy</pre><p>The 4 depth layers that were generated accordingly at the depth levels 0.8, 1.2, 1.6 and 2.0 have the following shapes :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIYssWHW6MP8zCNNRnVzAQ.png" /></figure><p>Generated lensless data is the following :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*dMPxpMpZJ0uyZgnOY4E5jQ.png" /></figure><p>The reconstruction is the following. Each frame corresponds to 10 iterations of gradient descent for a total of 500 iterations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*bh8YoR5PGbhmScj-oJ0NYw.gif" /></figure><p>We can see that the reconstruction seems to converge and stabilise itself around 400 iterations, and looks fairly similar to the original scene!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*L36_iZkpl1M9tRJ3YeCl3Q.png" /></figure><p>The data is distributed along the different depth layers as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2sfcIA05Mw31pz-K5hGsJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RBgxui3RfHS9ms7A1M5Zg.png" /></figure><p>Although the general shape of the reconstruction is satisfying, we could have expected for the reconstructed depths to be more representative of the original depth map. If we pay close attention to each depth layer, we can see that the closer ones have indeed higher values for the parts of the scenes that are closer from the camera, such as the V from the logo. However, seeing that the whole logo has been fully reconstructed on three of the depths and partially on the remaining one is still quite surprising.</p><p>This is much likely due to the fact that the 3D PSF that we used for generating the lensless data has very similar PSFs for its three last depth levels. The approximation therefore struggles to distinguish which patterns of the lensless data were produced by which layer of the 3D PSF. The way to solve this issue would be to try and tweak the parameters used to generate the PSF in the first place until finding a configuration that would yield the most different patterns possible for each depth. This is a whole topic of study in its own right and will be explored in the future. In any case, all the tools are available to start generating data!</p><p>(In order to quantitatively qualify the accuracy of our reconstruction, we could inspire us from the case of 2D reconstructions, for which there exists several metrics, already implemented in LenslessPiCam, that can be used for this purpose. However, these metrics would likely also need to be ported to 3D in order to stay meaningful, and ended by not being in the scope of this project due to time constraints.)</p><h4>Additional notes</h4><p>Regarding the reconstruction from simulated data, it should be mentioned that in the actual state of the code, the simulated lensless data has a correct ratio of metric unit per pixels relatively to the corresponding PSFs, but they usually have a higher pixel resolution than the corresponding PSFs, which will produce inconsistent results if directly used as is in the LenslessPiCam reconstruction algorithms. Therefore, before reconstructing such scenes, the corresponding PSFs should be padded with black pixels in order to match the resolution of the data image. Moreover, reconstructing a scene that was generated with a grayscale PSF but a RGB radiance map could also produce a dimension error when directly re-using the same PSF in LenslessPiCam. The quickest fix for now would be to convert the PSF to RGB in order for its shape to match the shape of the data.</p><pre>import numpy as np<br>import cv2<br>psf = np.load(&quot;psf.npy&quot;)<br>data = cv.imread(&quot;data.tiff&quot;)<br># padding<br>shape = [psf.shape[0]] + data.shape<br>padded = np.zeros(shape)<br>x_offset = (shape[1] - psf.shape[1]) // 2<br>x_offset = (shape[2] - psf.shape[2]) // 2<br>padded[:,x_offset:x_offset+psf.shape[1],y_offset:y_offset+psf.shape[2]] = psf<br># if necessary, grayscale to rgb<br>if len(psf.shape) == 3 and len(data.shape) == 3:<br>  padded = np.repeat(padded[:,:,:,np.newaxis],axis=3)<br>return padded</pre><p>Another detail to take in account is that, when reconstructing a scene, one could realise that the reconstruction appears rotated by a half-turn. This is due to the fact that the first simulator that has been implemented was the ray tracing simulator, which in a sense follows the principle of the pinhole camera and produce flipped images. When implementing the convolution-based simulator, it appeared logical to flip the input scene so that it would match the existing simulator ; but it now appears that it would be way more convenient to produce lensless data that would produce scenes that would already be in the right orientation when reconstructed !</p><p>Both of these issues will hopefully be fixed in the near future, as the reason of their existence is understood, but in the mean time, they can be handled as mentioned instead.</p><h3>Conclusion</h3><p>We demonstrated a functioning implementation of a reconstruction algorithm for lensless data from 3D scenes that relies on classical gradient descent and other variants of it such as Nesterov gradient descent and FISTA. We compared the results that it could produce with the ADMM reconstruction algorithm from the DiffuserCam project of Waller’s lab, using the sample data provided with it. The reconstructions proved to look quite similar, although they have their differences.</p><p>We also demonstrated the implementation of 3D PSF simulator based on ray-optics for cameras using diffusers and amplitude masks as optics, as well as the implementation of lensless data simulator that can produce lensless data with the help of 3D PSFs, should they be collected from real cameras or simulated.</p><p>Finally, we showed that using both of these tools, we were able to produce convincing reconstructions of scenes that were used to generate lensless data, laying the foundations of a powerful and convenient tool to study the behaviour of such reconstructions without needing to extensively capture data from real lensless cameras.</p><p>There is, of course, still plenty of room for improvements. On the side of the reconstruction algorithms, the implementation of faster algorithms such as the ADMM gradient descent remains to be done in Python, although a MATLAB version exists in the DiffuserCam project. Some research around the use of priors and regulariser terms that would be specific to 3D scenes could also be done in order to improve the quality of the reconstructions.</p><p>On the side of the PSF simulator, the next great step forward would be to output differentiable data in order to be able to study more efficiently how the caustic patterns formed by the diffusers are altered by the different parameters at our disposition, which would eventually allow for the design of especially efficient diffusers whose PSFs would vary a lot with depths, making the reconstruction of 3D scenes from corresponding lensless data more accurate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*sK_8_4oyfk5fQ3F7ZVFdZA.png" /></figure><h4>Previously</h4><ul><li><a href="https://medium.com/@julien.sahli/3d-imaging-with-lensless-camera-822983618455"><strong>Part 1:</strong> 3D Imaging with lensless camera</a></li><li><a href="https://medium.com/@julien.sahli/simulating-lensless-camera-psfs-with-ray-tracing-a224ca11f758"><strong>Part 2:</strong> Simulating lensless camera PSFs with ray tracing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3da3daf50e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simulating lensless camera PSFs with ray tracing]]></title>
            <link>https://medium.com/@julien.sahli/simulating-lensless-camera-psfs-with-ray-tracing-a224ca11f758?source=rss-5246763fb747------2</link>
            <guid isPermaLink="false">https://medium.com/p/a224ca11f758</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[optics]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[cameras]]></category>
            <dc:creator><![CDATA[Julien Sahli]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 15:47:16 GMT</pubDate>
            <atom:updated>2023-03-21T14:17:23.935Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reconstructing 3D scenes from lensless data and simulating the collection of such lensless data from virtual scenes — Part 2/3</h4><p><em>This work is in line with the </em><a href="https://github.com/LCAV/LenslessPiCam"><em>LenslessPiCam</em></a><em> project conducted at the </em><a href="https://www.epfl.ch/labs/lcav/"><em>LCAV</em></a><em> lab from EPFL. Before continuing, if you wish to delve in the subject more in detail, a general introduction to this project as well as links to specific parts of its implementation can be found in </em><a href="https://medium.com/@bezzam/a-complete-lensless-imaging-tutorial-hardware-software-and-algorithms-8873fa81a660"><em>this post</em></a>, <em>and the corresponding code is available at </em><a href="https://github.com/LCAV/LenslessPiCam"><em>this link</em></a><em>. The current work aims at extending it to 3D as well as building a lensless data simulator. (The corresponding code will be available soon).</em></p><p>This work is divided in three parts:</p><ul><li><a href="https://medium.com/@julien.sahli/3d-imaging-with-lensless-camera-822983618455">Part 1: 3D Imaging with lensless camera</a></li><li><strong>Part 2: Simulating lensless camera PSFs with ray tracing</strong></li><li><a href="https://medium.com/@julien.sahli/simulating-lensless-camera-data-from-3d-scenes-a3da3daf50e">Part 3: Simulating lensless camera data from 3D scenes</a></li></ul><h3>Simulating point spread functions</h3><p>As we have seen in <a href="https://medium.com/@julien.sahli/3d-imaging-with-lensless-camera-822983618455">Part 1</a>, the core component of the lensless model is the PSF of the diffuser at each depth level. Depending on the shape of the PSFs, the reconstruction can be easier or harder. In particular, having very different PSFs at each depth will help to distinguish the depth levels of the scene. Designing diffusers and masks of specific shapes whose PSFs would be more efficient for reconstruction is a whole task in itself. The first step towards it consists of being able to simulate the PSF of a given diffuser or mask. This section presents how do so.</p><p>Before continuing, we will need to parameterise the camera whose PSF we will simulate. These parameters will be the following:</p><ul><li><strong>Type of mask:</strong> in this work, we support two types of optics: diffusers as shown above and amplitude masks. The latter attenuate or completely block rays from their scene. Diffusers allow all light to pass through, but refracts it into caustic patterns. Its thickness, refractive index, and height profile will determine who light propagates through it (via refraction). In practice, amplitude masks will hardly ever be used in concrete cases, but thanks to the simplicity of their functioning, they will consist an accessible first step to reach before simulating the more complex diffusers, and will also be used later in order to test and compare the different data rendering algorithms.</li><li><strong>Sensor width / height:</strong> Affects how large is the surface on which we will simulate data (e.g. 2 cm × 2 cm)</li><li><strong>Sensor — Mask distance:</strong> Affects the field of view of the camera as well as the location where the light rays refracted through the diffuser or attenuated by the mask will hit the sensor. (e.g. 0.1 cm)</li><li><strong>Mask width / height:</strong> Affects how large is the aperture through which the light from the scene will be able to reach the sensor. (e.g. 1 cm × 1 cm)</li><li><strong>Diffuser thickness:</strong> For diffuser cameras, affects how the light will be refracted when going through the diffuser. (e.g. 0.01 cm)</li></ul><p>Unless stated otherwise, the values that will be used from now on in the rest of this article will be the ones indicated above. As the presented system is based on ray optics, the provided units are only indicative, and can therefore be scaled arbitrarily without modifying the result of the simulation, as long as the same proportions are kept between the different parameters. It should however be kept in mind that past a certain point of scaling down the size of the camera, significant wave effects would happen on real cameras, making the ray optics model incorrect. Such wave effects would require different simulation methods than the one presented in this project, such as those from <a href="https://github.com/ebezzam/waveprop">this other LCAV project</a>.</p><h4>Simulating Amplitude Masks</h4><p>Simulating the behaviour of amplitude masks is quite straightforward. We can parameterise the mask as a grayscale or RGB transparency. Black pixels are totally opaque and block the light rays intersecting with them, while white pixels are totally transparent, and every colour shade in between partially blocks the light. We will also need to specify the different depths for which we desire to generate the PSFs, which will need to correspond to the parameters of the scenes we will generate afterwards.</p><p>Using Intercept Theorem, we can show that the PSF of the amplitude mask will be a projection of the amplitude mask itself, whose size will depend on the distances between the amplitude mask and the light source, as well as the distances between the amplitude mask and the sensor, which we will respectively call <strong>D</strong> and <strong>d. </strong>Actually, <strong>Projection size = Mask size × (D + d) / D.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*JcVg1e8Ji5PjLpkABJqeCA.png" /></figure><p>We can therefore compute the size of each projection depending on the different values that <strong>D</strong> can take for the each different depths for which we want to simulate the PSF. It is relevant to note that the smaller D becomes, the bigger the projection gets, and that therefore, the size of the projection will eventually exceed the size of the sensor past a certain point. It is not a behaviour that we are looking for, and we will therefore take care of not selecting too small values for <strong>D</strong> in order to avoid it to happen, as the projection would be cropped.</p><p>In terms of code, we can specify an arbitrary pixel resolution for the PSF, which will correspond to light received by the whole sensor. By computing the size of the projection and comparing it to the size of the sensor, we can deduce how much place the projection will take on the sensor, and therefore, how much pixels it will occupy in the image. We can then scale the input image that represents the mask in order to make it as big, and finally pad it with black pixels until it matches the desired resolution, to account for the area where the sensor receives no light.</p><pre># pseudocode <br>def project_mask_psf(mask, cam_settings, distance, out_width, out_height):<br>  scale = (distance + cam_settings.distance) / distance<br>  proj_width = cam_settings.diffuser_width * scale<br>  proj_height = cam_settings.diffuser_height * scale<br>  w_ratio = proj_width / cam_settings.sensor_width<br>  h_ratio = proj_height / cam_settings.sensor_height<br>  projection = resize(mask, out_width * w_ratio, out_height * h_ratio)<br>  psf = pad(projection, out_width, out_height)<br>  return psf</pre><p>However, as we are sampling the light rays according to the surface they illuminate rather than according to the distribution of the light source, we also have to account for the fact that the density of the light is not the same on different areas of then sensor, neither if we move the light source. Indeed, it can be shown that the quantity of emitted light reaching the sensor decreases with the following:</p><ul><li>the distance between the sensor and the light source, as the radiance emitted by a point light disperses in every direction around it;</li><li>the angle between the normal to the sensor and the incoming light rays, as it gets spread on a bigger surface when the angle increases.</li></ul><p>More exactly, the attenuation of the light according to the distance follows an inverse-square law, and the diminution according to the angle is proportional to the cosine between the light ray direction and the sensor normal. The actual PSF can therefore be computed in the following way:</p><pre># pseudocode<br>def compute_mask_psf(mask, cam_settings, dist, out_width, out_height):<br>  projection = project_mask_psf(mask,cam_settings,dist,out_width,out_height)<br><br># calculated by mapping the pixel indexes to the coordinates of the sensor<br>  pixel_positions = ... <br>  <br>  distances = pixel_positions - [0, 0, dist + cam_settigns.distance]<br>  dist_factor = 1 / squared_norm(distances)<br>  <br>  # as normal to the sensor is parallel to the z-axis, the cosine is given<br>  # by the z-component of the normalized direction.<br>  cos_factor = normalize(distances)[:,:,2]<br> <br>  return projection * dist_factor * cos_factor</pre><h4>Simulating Diffusers</h4><p>Whereas simulating the PSFs of masks rely on the fact that the light rays do not get refracted in the mask, simulating the PSFs of diffusers requires to track the individual trajectory of each light ray that we sample. Doing so will require to know the shape of the diffuser ; therefore, the input data for such PSFs will consist of the <a href="https://en.wikipedia.org/wiki/Normal_mapping">normal map</a> of the diffuser. As for the masks, we begin by specifying the distances at which we want to place the light source used for the PSF generation, but the similarity stops here. In order to track how the light gets refracted through the diffuser, we will use the following procedure:</p><ul><li>Sample one light ray per pixel of the normal map;</li><li>Compute the first refraction of each light ray through the diffuser;</li><li>Compute the second refraction of each light ray through the diffuser;</li><li>Compute the intersection point between the light ray and the sensor;</li><li>Distribute the light from the ray through the four closest pixels of the output image (using linear interpolation).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*rscMWN-9pEClt1vJrKvYwg.png" /><figcaption><strong>Light rays getting refracted through the diffuser</strong></figcaption></figure><p>Computing the refraction of the light rays can be done with <a href="https://en.wikipedia.org/wiki/Snell%27s_law">Snell’s law</a>, which states that the ratio between the sines of the angles between the ingoing and outgoing rays with the normal of the interface is equal to the ratio between the refractive indexes of the two mediums.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-g3sNS-KcQdm8SY9sM7mg.png" /><figcaption>Source: <a href="http://en.wikipedia.org/wiki/File:Fresnel.svg">http://en.wikipedia.org/wiki/File:Fresnel.svg</a>, with minor edits</figcaption></figure><p>In addition to this, we will also keep track of the diminution of the light as in the mask case — with the distance factor being dependent on the distance travelled by the light, not the euclidean distance between the position of light source and the position of the end point of the ray — but also accounting for the <a href="https://en.wikipedia.org/wiki/Fresnel_equations">Fresnel equations</a>, that state that when a light ray passes from a medium to another, a certain part of it gets indeed refracted through the new medium, but another part of it is reflected back instead, effectively diminishing the light throughput. This reflection depends on the polarisation of the light and is given by the following equations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*agVeuUz5afBe_9uVPtHaJQ.png" /><figcaption><strong>Fresnel equations</strong></figcaption></figure><p>Here, Rs is the reflectance of the s-polarised light and Rp is the reflectance of the p-polarised light. Assuming that our light source emits light of all polarisations equally, we can simply average Rs and Rp to get the reflectance of our system. The amount of light getting though is therefore <strong>1–0.5 × (Rs + Rp)</strong>.</p><p>Another common way of computing the reflectance of light for a refraction is to use <a href="https://en.wikipedia.org/wiki/Schlick%27s_approximation">Schlick’s approximation</a>, which can be faster to compute. However, this approximation is mostly used for refractions between air and mediums with refractive indexes within a certain range ; when leaving this specific range, the approximation can deviate from the actual reflectance value. As the computation of the reflectance was not the most time-consuming part of the simulation, I therefore choose to not make use of this approximation to keep the simulation as close as possible to reality.</p><p>However, the existence the reflectance calls for another phenomenon to take into account: internal reflection. Namely, a light ray that is reflected (at the second interface) can reflect back at the first interface and refract out of the second interface, etc, as illustrated in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*hC56dlR5Q84U0Vx3gE4ixw.png" /><figcaption><strong>Internal reflection</strong></figcaption></figure><p>In order to fully represent these subsequent reflections, our simulation should compute each of them, by keeping in mind that the surface of our diffuser is actually bumpy and that each additional reflection will produce generally different angles with the surface, which would be quite time-consuming. To quickly picture ourselves how much quantity of light we would omit by not computing these additional reflections, we can generate a new PSF for a diffuser of standard parameters (reflective index are 1 and 1.5, distances are the one specified in the camera parameters presented above) and print the average reflectance of the light at the second interface. Conducting such a test practical test with roughly 850&#39;000 light rays yields an average reflectance of 0.04, which means that the first reflection inside the medium will, on average, carry only 4% of the energy of the light ray. Given that this ray must be reflected a second time, when reaching again the first interface, we can suppose that its average reflectance will again be of 0.04, which in total accounts for 0.16% of the initial ray energy. Given how small this is, we can spare ourselves the computation of the subsequent reflections and declare that in practice, this should indeed represent a negligible difference in the general case.</p><p>(However, this remains an estimation of the overall light throughput. When generating our PSF, it is also interesting to print what the maximum value the reflectance can take, which is of <strong>0.31 = 31%</strong> in our case. Supposing that the particular ray that produced this reflectance value will have the same reflectance value when bouncing a second time as it reaches the first interface again, this would account for a light throughput of <strong>0.31 × 0.31 = 9.61%</strong>. It would then be reflected again on the second interface, and by supposing it would have the same reflectance again, the amount of light getting refracted through would be of <strong>0.31 × 0.31 × (1–0.31) = 6.63%</strong>. This could suggest that it would therefore still be meaningful to take those subsequent reflections in account, but we must keep in mind that this is the case of one light ray among 850&#39;000 and that supposing that the ray gets refracted twice in a row with a such high reflectance of 0.31 is also a quite bold supposition. In practice, it should statistically be more likely that the second reflection would be closer to the average reflectance in the simulation than the one of the first reflection, which was likely caused by a almost horizontal normal on the first side of the diffuser and should not occur a second time on the other side that is totally slick.)</p><p>Still, this stays an estimation that was done on the simulation of a single PSF, and it could still be reasonable to imagine specific conditions where these subsequent reflections would be meaningful to compute, in return for a computation time roughly doubled ; hence it is one of the improvements that could be added to the simulation in the future — and quite easily, actually — but that was not covered in this project due to time constraints.</p><p>Another simplification of the model that was made to avoid spending computation time on negligible differences was to ignore the distance travelled by the light rays inside of the diffuser. Indeed, we saw that typical values for the diffuser thickness would be of <strong>0.01 cm</strong>, whereas the surface of the sensor would be of <strong>2 cm</strong> <strong>× 2 cm</strong>. Light is simply considered to reach the first face of the diffuser and immediately being refracted twice before getting out on the other side. As the second face is totally flat, a light ray would refract in the same fashion whichever its exact position would be when reaching the second face, and relatively to the scale of the whole camera + scene system, the distance travelled while in the diffuser is minimal and can therefore be neglected without deviating too much from reality. Still, as for the precedent estimation, implementing the path of the light ray while in the diffuser could be an easily implemented extension that could prove being useful should we desire to simulate PSFs for thicker diffusers.</p><p>To sum up, the simulation of the diffuser PSFs is done in the following way:</p><pre># pseudocode<br>def compute_diffuser_psf(normals, cam_settings, distance,<br>                         out_width, out_height, n1, n2):<br><br>### from light source to diffuser<br>  <br># calculated by mapping the pixel indexes of the normal map to the<br># coordinates of the diffuser<br>  incident_rays_position = ... <br>  incident_rays = incident_rays_positions<br>                  - [0, 0, distance + cam_settigns.distance]<br>  <br>### first refraction<br><br>  # in the local coordinate systems corresponding to the normal of the diffuser<br>  # computes the value of the incident vectors in the local coordinates system<br>  local_incident_rays = to_local(incident_rays, normals)<br><br>  # the cosine of the angle between a normalized vector and the z_axis<br>  # is given by itsz-component<br>  local_incident_angles = acos(normalize(local_incident_rays)[:,:,2])<br><br>  # Snell&#39;s law<br>  local_refracted_angles = asin(sin(local_incident_angles) * n1 / n2)<br>  <br>  # changes the z-component of incident rays to match the cosine of the<br>  # refracted angle and scales the other components accordingly<br>  local_refracted_rays = refract(local_incident_rays, local_refracted_angles) <br>  <br>### second refraction<br><br>  # reciprocal of to_local<br>  global_incident_rays = to_global(local_refracted_angles, normals)<br><br>  # same as before<br>  global_incident_angles = acos(normalize(global_incident_rays)[:,:,2])<br><br>  # we also have to take in account the cases of total refraction which yield<br>  # sines values greater than 1, not shown here<br>  global_refracted_angles = asin(sin(global_incident_angles_2) * n2 / n1) <br>  <br>  # same as before<br>  global_refracted_rays = refract(global_incident_rays, global_refracted_rays) <br>  <br>### reach the sensor<br><br>  # output rays intersection with the sensor plane. Scale the out directions<br>  # s.t. their z component match the distance between the diffuser and sensor<br>  out_rays = global_refracted_rays *<br>             cam_settings.distance / global_refracted_rays[:,:,2]<br>  out_position = incident_rays + out_rays<br>  <br>  # we DO NOT take in account the distance between the diffuser<br>  # and the sensor, as light rays are sampled according to the diffuser&#39;s<br>  # surface. Diminution of the light with distance after passing through the<br>  # diffuser characterises by the fact the density of the light rays hitting<br>  # far surfaces will naturally decrease because of distance from now on.<br>  dist_factor = 1 / squared_norm(incident_rays) <br>  fresnel_factor = ... # see the formulas presented in the previous pragraph<br>  light = dist_factor * cos_factor * fresnel_factor   <br>  <br>### assigning rays to output<br>  # this part is the only one that is not properly vectorized in<br>  # the code yet and takes most of the total computation time<br>  output = np.zeros((out_width, out_height))<br>  <br>  for i in range(out_position):<br>    # adds the light coming from the ray on the final psf using<br>    # linear interpolation between the four closest pixels<br>    output = addray(output, out_position[i], light[i]) <br>  return output<br><br>def to_local(ray, normal):<br>  # rotates the ray so that it is expressed in the local coordinates system<br>  # corresponding to the normal. The rotation axis is the cross product<br>  # between the normal and the z-axis. The roation angle&#39;s cosine is the<br>  # scalar product between the normal and the z-axis. rotation is then<br>  # performed using linear algebra.<br>  return ...<br><br>def to_global(ray, normal): <br>   return to_local(ray, normal*[-1, -1, 1])</pre><p>We also have to account for the quantity of rays being traced and the desired resolution of the output. Tracing a small amount of rays could lead to a noisy image, which is a common issue in ray tracing algorithms, depending on the sample density. Because of the refractions occurring in the diffuser we cannot easily sample the incoming light from the sensor itself ; we can only sample it from the surface of the diffuser, which is directly exposed to the light source. However, a simple fix to this issue is to upscale the resolution of the normal map so that the amount of sampled rays gets increased as much until the final image gets smooth enough.</p><p>We will showcase this phenomenon with the following normal map:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*dn9Kl85luos5YQb21PR6pw.png" /><figcaption>Source: <a href="https://en.wikipedia.org/wiki/Normal_mapping#/media/File:Normal_map_example_with_scene_and_result.png">https://en.wikipedia.org/wiki/Normal_mapping#/media/File:Normal_map_example_with_scene_and_result.png</a></figcaption></figure><p>If we try to generate a PSF of resolution <strong>300 px × 300 px</strong>, associated with this normal map sampled at the resolution of <strong>128 px × 128 px</strong>, we will get a noisy output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*YQizhWdYPhdLHk667QrzjQ.gif" /><figcaption><strong>Under-sampled PSF</strong></figcaption></figure><p>However, if we choose to upsample the normal map to <strong>1024 px ×1024 px</strong>, the result gets much better!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*n8ySXiuZpotaPbipsa3Vtg.gif" /><figcaption><strong>Same normals, but upscaled to get more samples</strong></figcaption></figure><h4>Normal Maps Generation</h4><p>Normal maps are used to describe the shape of the surface of objects. As such, they can either be designed by hand — which is a tedious task — or derived from other data. In this project, we will use height maps in the form of grayscale images, which are way easier to design by hand, in order to generate normal maps.</p><p>As the normal at a point of a surface can be viewed as the 2D derivative of the height of the surface at this point with respect to the 2D position of the point, we can get the normals by computing the gradient of the height map. A good approximation of this gradient can be computed with the help of the Sobel operator, which consists of two kernels that are convolved with the height map — one for each axis.</p><p>The most basic Sobel kernel has a size of <strong>3 × 3</strong>, but it can be extended to higher odd sizes in order to generate smoother gradients. The exact definition of how to extend it can vary depending on the implementations and use cases. In this project, we used the following :</p><ul><li>Sobel_x(i, j) = i / (i <strong>× </strong>i + j <strong>× </strong>j) if i != 0 else 0</li><li>Sobel_y(i, j) = j / (i <strong>× </strong>i + j <strong>× </strong>j) if j != 0 else 0</li></ul><p>With i being the distance between the current column and the central column, and j the distance between the current line and the central line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*EWcC7K7xos6Lu8XudEklUA.png" /><figcaption><strong>Example of Sobel_x kernel for sizes 3 and 7</strong></figcaption></figure><p>However, this approximation does not takes the actual dimensions of the diffuser into account. The generated normal assumes that the physical distance between two neighbouring pixels of the image is equal to the physical distance between the highest and lowest values that the normal map can provide, when in practice, the former is equal to the width/height of the diffuser divided by the amount of pixels columns/rows, and the latter is equal to the diffuser thickness that we mentioned earlier. The gradient therefore has to be adapted accordingly in order to actually describe the normals that we want to compute.</p><p>Once the normals are computed, they are stored in memory by mapping their value from the vector space to the RGB space. The used convention is the one of <a href="https://fr.wikipedia.org/wiki/DirectX">DirectX</a>, which maps X (-1;1) to R (0;255), Y (-1;1) to G (0;255), and B (0;1) to B (127;255). Another common convention is the one of <a href="https://en.wikipedia.org/wiki/OpenGL">OpenGL</a> which maps (1 — Y) to G. Both can be recognised by the program when directly using normals to generate PSFs, but when generating normals from a height map, the associated normal map will be saved in the former by default.</p><p>Here is an example of a normal map generated from a handmade height map — that means created with a raster graphics editor such as Photoshop or Gimp. Brighter pixels correspond to the points of the diffuser that have a higher elevation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*ysZYZMZx1gKao6hoSZ1tig.png" /><figcaption><strong>A height map (left) used to generate a normal map (right)</strong></figcaption></figure><p>When used to generate a PSF (for a certain depth), the above normal map yields the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*iECGeynjZncgyFA1KYQRRQ.png" /><figcaption><strong>An example of PSF corresponding to the above normal map</strong></figcaption></figure><p>For reference, the shape of the PSFs used in the works of the DiffuserCam3D project from <a href="https://github.com/Waller-Lab/DiffuserCam/tree/master/example_data">Waller’s lab</a> have such patterns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*GVlp1w9An8NDa1s8Ymlg7g.png" /><figcaption><strong>First depth layer of the Waller’s lab 3D example PSF rendered as an image. </strong>Source : <a href="https://github.com/Waller-Lab/DiffuserCam/blob/master/example_data/example_psfs.mat">https://github.com/Waller-Lab/DiffuserCam/blob/master/example_data/example_psfs.mat</a></figcaption></figure><p>We can see that the overall structure of our simulation is quite similar to the actual measures of a real diffuser. Our simulation is even sharper! This is likeky due to the physical resolution of the sensor and its sensitivity to noise. If needed, we can still adapt our parameters to make it smoother. This is what we will illustrate now, by showing how adapting the different parameters can modify the shape of the PSFs that we generate.</p><p>The above normal map was generated with a Sobel kernel of <strong>7 × 7</strong> (for a height map of resolution <strong>1000 px × 1000 px</strong>), and a diffuser whose dimensions are the standard ones used throughout this article; namely <strong>1 cm × 1 cm × 0.01 cm. </strong>Moreover, the above PSF was generated by considering the material of the PSF to be optical glass (n = 1.5), the diffuser-to-sensor distance to be <strong>0.1 cm</strong>, and the distance between the diffuser and the sensor to be<strong> 0.8 cm</strong>.</p><p>If we increase the thickness of the diffuser from <strong>0.01 cm</strong> to <strong>0.02 cm</strong>, the bumps on its surface will be twice as marked, which in return will refract the light more strongly and produce coarser patterns :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*ibxXq3dcQQxK-kjRr9nPiA.png" /><figcaption><strong>More pronounced normals will generate coarser caustic patterns</strong></figcaption></figure><p>Such coarser patterns can also occur if we increase the refractive index of the diffuser, as a higher refractive index will increase how the light gets refracted in a similar fashion as increasing the inclination of the normals.</p><p>On the other hand, if we decrease the size of the Sobel operator’s kernel, the generated normal map will be more descriptive of high-frequencies differences throughout the height map. In other words, it will take a less wide range of neighbouring pixels when computing the gradient of the height map — which mathematically approach more closely the concept of gradient the image gradient, but that can be more or less convenient to generate a normal map to our liking.</p><p>In the resulting normal map, we can see how a smaller kernel accentuates smaller height differences. If we decrease the size of the Sobel kernel from <strong>7 × 7</strong> to the minimal value of<strong> 3 × 3</strong>, we obtain the following normal map and PSF. We can see that indeed, more detail appears in both in the normal map and in the associated PSF:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*Q3vgiHnqKoAh3ol4O8kG7Q.png" /><figcaption><strong>The upper-left corner was upscaled and slightly sharpened identically in the two normal maps to illustrate the consequences of reducing the size of the kernel</strong></figcaption></figure><p>(As an additional parameter to tweak, the PSF generator also allows to consider the space between the diffuser and the sensor to be made of the same medium than the one the diffuser is made of, effectively cancelling the second refraction that should happen when exiting the medium. Such generated images tend to have less coarse caustic patterns, as the light gets less refracted, in a kind of similar way that reducing the strength of the normals or the refraction index of the medium would do.)</p><p>That being said, if we want to make our PSF appear smoother so that it becomes even more similar to the one from the Diffuser3D data set, we can reduce the thickness of the diffuser as well as its refraction index, and increase the size of the Sobel operator’s kernel.</p><p>For example, if we set the diffuser thickness to be 0.008 cm instead of 0.01 cm, the kernel to be 15 <strong>× </strong>15 instead of 7 <strong>× </strong>7, and the refractive index of the diffuser to be 1.3 instead of 1.5, we obtain the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*tqCgrQhbEV5k9cqukHbJuQ.png" /><figcaption><strong>Appropriate parameters can produce a smoother PSF</strong></figcaption></figure><p>Finally, the following animation displays the different depth layers of the last PSF we generated, from the closest to the furthest. The depths corresponding to the following PSF range from 0.8 cm to 2.0 cm from the diffuser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*BZy4QLx32p3NLohBmH0VkA.gif" /><figcaption><strong>Display of the different depths of a single 3D-PSF</strong></figcaption></figure><p>We can see that, as expected, the PSFs from further depths get smaller and dimmer, and that the shape of the caustic patterns, while generally staying similar from one depth to another, has subtle variations in some places, especially in the borders, due to the decrease of the angles between the incident rays and the diffuser as the light source moves away from it.</p><h4>To read next</h4><ul><li><a href="https://medium.com/@julien.sahli/simulating-lensless-camera-data-from-3d-scenes-a3da3daf50e"><strong>Part 3:</strong> Simulating lensless camera data from 3D scenes</a></li></ul><h4>Previously</h4><ul><li><a href="https://medium.com/@julien.sahli/3d-imaging-with-lensless-camera-822983618455"><strong>Part 1:</strong> Simulating lensless camera PSFs with ray tracing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a224ca11f758" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3D Imaging with Lensless Camera]]></title>
            <link>https://medium.com/@julien.sahli/3d-imaging-with-lensless-camera-822983618455?source=rss-5246763fb747------2</link>
            <guid isPermaLink="false">https://medium.com/p/822983618455</guid>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[optics]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[cameras]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Julien Sahli]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 15:08:22 GMT</pubDate>
            <atom:updated>2023-03-21T14:17:16.241Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reconstructing 3D scenes from lensless data and simulating the collection of such lensless data from virtual scenes — Part 1/3</h4><p><em>This work is in line with the </em><a href="https://github.com/LCAV/LenslessPiCam"><em>LenslessPiCam</em></a><em> project conducted at the </em><a href="https://www.epfl.ch/labs/lcav/"><em>LCAV</em></a><em> lab from EPFL. Before continuing, if you wish to delve in the subject more in detail, a general introduction to this project as well as links to specific parts of its implementation can be found in </em><a href="https://medium.com/@bezzam/a-complete-lensless-imaging-tutorial-hardware-software-and-algorithms-8873fa81a660"><em>this post</em></a>, <em>and the corresponding code is available at </em><a href="https://github.com/LCAV/LenslessPiCam"><em>this link</em></a><em>. The current work aims at extending it to 3D as well as building a lensless data simulator. (The corresponding code will be available soon).</em></p><p>This work is divided in three parts:</p><ul><li><strong>Part 1: 3D Imaging with lensless camera</strong></li><li><a href="https://medium.com/@julien.sahli/simulating-lensless-camera-psfs-with-ray-tracing-a224ca11f758">Part 2: Simulating lensless camera PSFs with ray tracing</a></li><li><a href="https://medium.com/@julien.sahli/simulating-lensless-camera-data-from-3d-scenes-a3da3daf50e">Part 3: Simulating lensless camera data from 3D scenes</a></li></ul><p>Traditional cameras focus light through lenses in order to render sharp images. On the other hand, lensless cameras use diffusers which scatter the light in various patterns which need to be processed afterwards in order to reconstruct what the captured scene should be.</p><p>This form of photography is especially useful for applications where it may be difficult or impossible to install an optical lens due to space constraints or other considerations. However, this is still a developing topic, and many research possibilities are still to be explored.</p><p>First, we are going to look into one of the possible use case of lensless imaging which is for reconstructing 3D scenes, where traditional cameras usually only capture 2D images. As a first step, we will introduce how to produce such reconstructions from lensless data.</p><p>Consequently, we will take the opposite approach and see how we can simulate the behaviour of lensless cameras in order to produce original lensless data from 3D virtual scenes.</p><h3>Quick refresh about 2D lensless reconstruction</h3><p>We will now briefly review the functioning of the 2D reconstruction algorithms already implemented in the LenslessPiCam project.</p><p>As seen in <a href="https://medium.com/@bezzam/lensless-imaging-with-the-raspberry-pi-and-python-diffusercam-473e47662857">this post</a>, the generation of lensless data from 2D scenes can be modelled as a linear shift-invariant system (LSI). Its impulse response, as generally in the domain of the optics, is called the <a href="https://en.wikipedia.org/wiki/Point_spread_function">Point Spread Function</a>, which we will refer as the PSF in the rest of this post.</p><p>LSI is a common assumption in the 2D case, which allows us to model the lensless data as the convolution of the light coming from scene with a single PSF, whose shape does not change regardless of the position from where the light is coming, as illustrated in the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cj7h9gx0sYlJYTf-_mq0jQ.png" /><figcaption>Source: <a href="https://waller-lab.github.io/DiffuserCam/tutorial/algorithm_guide.pdf">https://waller-lab.github.io/DiffuserCam/tutorial/algorithm_guide.pdf</a></figcaption></figure><p>As such a model is usually not invertible, we must find another way to reconstruct the original scene. One way of doing so is through an iterative algorithm which typically as the following steps:</p><ul><li>Enter the current estimate of the into our model for the camera;</li><li>Compare the result with our measurement;</li><li>Compare the result with our measurement;</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MpMgHw_ANcB76RCORHKiSQ.png" /></figure><p>In practice, we define the problem as such:</p><ul><li>The forward model that represents our system is the convolution between the light emitted by the original scene and the PSF of the diffuser, followed by a cropping:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*3KeY61ot4oKZ2g0FrauT7A.png" /></figure><ul><li>The estimate is computed by minimising the following error metric, while taking in account certain priors like non-negativity of the original scene. This can be done by applying <a href="https://en.wikipedia.org/wiki/Gradient_descent">Gradient Descent</a> on the error metric, or any equivalent variant of this algorithm:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*IQ2y4lPc_C_lebCqQA2Ojw.png" /></figure><p>By doing so, we are able to produce accurate reconstructions of 2D scenes such as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*m8Bx1nDbnO9_gA_kjJt4_g.png" /><figcaption>Source: <a href="https://medium.com/@bezzam/image-similarity-metrics-applied-to-diffusercam-21998967af8d">https://medium.com/@bezzam/image-similarity-metrics-applied-to-diffusercam-21998967af8d</a></figcaption></figure><h3>Extension of 2D reconstruction to 3D scenes</h3><p>Let’s now turn to the section on extending the above algorithm to 3D scenes. One could think that tackling the reconstruction of 3D scenes using 3D PSFs could simply consist of using the same method, by computing the convolution of the 3D scene with the system’s PSF in order to generate 3D data. Unfortunately, it is not the case.</p><p>To understand why, we have to think about how the collected image forms on the sensor. In the 2D case, we can model the scene as an image that is parallel to the camera sensor. As we have seen, any point on this image that is a light source will project the PSF on the sensor at a position which will depend on the position of the point in the scene.</p><p>Increasing the horizontal or vertical distance between light source and the centre of the scene by a certain factor will therefore increase the horizontal or vertical distance between the centre of the projection on the sensor and the centre of the sensor. We can therefore retrieve the scene by operating a deconvolution on the gathered data, by knowing the PSF of the system.</p><p>When we translate this system to 3D, we add an additional dimension to the scene, which means that, of course, the light sources which compose the scene acquire a new coordinate. However, the sensor of the camera does not changes, and still collects data that is in 2D, by stacking together the light coming from multiple depths.</p><p><strong>Retrieving the 3D scene by performing a deconvolution on the sensor data as in the 2D case would require a device that could collect data in three dimensions, which our camera does not!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*5YUdHpQRWTLC_kGWni0MEw.png" /><figcaption><strong>Wrong camera model for 3D reconstruction</strong></figcaption></figure><p>Indeed, if we try to naïvely reconstruct a 3D scene in this way, it will produce an output whose values are all equal along the depths axis, as the same data that we collected on the 2D sensor would be broadcasted to match the dimensions of the scene. Therefore, we will need to find another method to reconstruct 3D scenes. Moving a point along the depth axis will not simply translate its representation along the depth axis as our sensor is only 2D! Similar to a magnifying lens, we will have a rescaling of an object as its distance to the camera changes. Moreover, a point source moving along the depth axis will not simply be translations but rather something akin to a rescaling of the caustic pattern.</p><p>Even if we consider the diffuser to be a simple 2D mask whose PSF would be its projection on the plane, the dimensions of this projection would be dependent of the distance of the light source casting the projection on the plane : the closer to the diffuser, the bigger the projection. In practice, when using actual diffusers, the shape of the PSF can change even more due to how the caustic patterns in it forms on the sensor — allowing for even better reconstructions — but the same observation still holds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*OIuOb4OVHjgrLk-CU0XxyA.png" /><figcaption>Source: <a href="https://opg.optica.org/optica/fulltext.cfm?uri=optica-5-1-1&amp;id=380297">https://opg.optica.org/optica/fulltext.cfm?uri=optica-5-1-1&amp;id=380297</a></figcaption></figure><p>We can use this property to our advantage by splitting the 3D scene into multiple planes along the depth axis. Reconstructing the content of these layers can be approximated to reconstruct 2D scenes, with each one having their own PSF. The 3D PSF that we will use is therefore not the PSF of a system which would output 3D data from the 3D scene, as we do not have such a device. Instead, it is the stack of several 2D PSFs of systems which output 2D data from the specific specific 2D layers of the scene, situated at different depths:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*1bvvh6JwIG_CgnXCjhVUPw.png" /><figcaption><strong>Right camera model for 3D reconstruction</strong></figcaption></figure><p>The equation to solve the system therefore becomes the following :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*95PNlLt724kWXvooXeANPg.png" /></figure><p>In terms of code, most of the changes to the 2D case consist of adding an additional dimension to the input PSF as well as to the scene estimate, but not to the lensless data.</p><p>In order to verify the correctness of the reconstructions, a scene from the <a href="https://opg.optica.org/optica/fulltext.cfm?uri=optica-5-1-1&amp;id=380297">Diffuser3D</a> <a href="https://github.com/Waller-Lab/DiffuserCam/tree/master/example_data">dataset</a> was reconstructed once with their algorithm and software (ADMM implemented in MATLAB). Their reconstruction was compared with the LenslessPiCam’s gradient descent extended to 3D. The result are the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4NngmhgQsSy1rJn9icfzGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v3uiPUaLWNTnKxmMYkWt4Q.png" /></figure><p>Several observations can be made. In the first place, we can see that the general shape of the two reconstructions is quite similar, especially when summing the data along the Z-axis (which is the main image in the upper left corner of both figures). However, we can notice the presence of small visual artefacts on either sides of the DiffuserCam reconstruction, which also appear a little bit in the LenslessPiCam reconstruction, but are way less noticeable. This is likely due to the functioning of the ADMM gradient descent that, relatively to the classic gradient descent, trades a little bit of precision against a faster convergence rate. Indeed, the ADMM reconstruction only took 40 iterations to already give a pretty good estimation of the original scene, which seems to be a <a href="https://en.wikipedia.org/wiki/1951_USAF_resolution_test_chart">resolution test chart</a>, whereas the gradient descent was given more iterations to converge. Moreover, the Diffuser3D reconstruction present a scene whose elements are concentrated on a few of the closest depth levels available, where the LenslessPiCam reconstruction is distributed more broadly along the depth levels available. That is likely due to the use of regularization terms that would penalise the presence of several light sources that would be aligned on the depth axis and therefore hiding each other in real life, which have not been implemented in LenslessPiCam yet. Nevertheless, the similarities between the two reconstructions are quite promising! Once we’ll have implemented the lensless data simulators, we will try to reconstruct other scenes with LenslessPiCam and directly compare how they relate to the original scenes.</p><h4>To read next</h4><ul><li><a href="https://medium.com/@julien.sahli/simulating-lensless-camera-psfs-with-ray-tracing-a224ca11f758"><strong>Part 2:</strong> Simulating lensless camera PSFs with ray tracing</a></li><li><a href="https://medium.com/@julien.sahli/simulating-lensless-camera-data-from-3d-scenes-a3da3daf50e"><strong>Part 3:</strong> Simulating lensless camera data from 3D scenes</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=822983618455" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>