<?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 Christophe Grosjean on Medium]]></title>
        <description><![CDATA[Stories by Christophe Grosjean on Medium]]></description>
        <link>https://medium.com/@christophe.grosjean?source=rss-80b74855580b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DHzdnBqVbWu-qGhQ.jpg</url>
            <title>Stories by Christophe Grosjean on Medium</title>
            <link>https://medium.com/@christophe.grosjean?source=rss-80b74855580b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 00:05:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@christophe.grosjean/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[Fisheye Dewarping: 6 Custom Implementations]]></title>
            <link>https://medium.com/@christophe.grosjean/fisheye-dewarping-6-custom-implementations-1df2f6355731?source=rss-80b74855580b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1df2f6355731</guid>
            <category><![CDATA[ffmpeg]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[numpy-performance]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Christophe Grosjean]]></dc:creator>
            <pubDate>Wed, 14 Jan 2026 23:06:16 GMT</pubDate>
            <atom:updated>2026-01-14T23:06:16.017Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p><em>TL;DR: Facing a critical bug in production, I had to rewrite a fisheye dewarper from scratch. Three years later, I revisit this problem to compare 6 different approaches — command-line FFmpeg, pure Python, vectorized NumPy, OpenCV Python/C++, and an optimized custom C++ library.</em></p><p><strong>January 2022</strong>. Our Docker container crashes in prod after a few hours on certain sites. The diagnosis comes in: a memory leak in the proprietary library that handles the dewarping of 360° fisheye cameras.</p><p>Quick context: our AI analyzes video streams to detect gestures. Our models are trained on flat views, not on distorted circular views. Without dewarping, zero detections on fisheye cameras, representing just 1% of the fleet, but important clients.</p><p>The crashing library? Provided by the camera manufacturer. We can neither patch it nor wait for a fix.</p><p><strong>Verdict:</strong> we code our own version.</p><p>Fifteen days deep diving into projective geometry books, a C++ implementation based on quaternions and spherical projections, a few weeks of optimization… and we had our solution in prod.</p><p>Three years later, with a bit of hindsight and some free time, a question is nagging at me: what if we had done it differently?</p><p>What would have been the best approach given our constraints?</p><ul><li><strong>Ceiling-mounted</strong> fisheye cameras</li><li>Need for multiple <strong>flat views</strong> per frame</li><li><strong>Static</strong> virtual camera viewpoints (no dynamic rotation)</li><li><strong>Critical performance</strong>: real-time processing of multiple video streams</li><li>“Sufficient” quality for detection (no need for photographic perfection)</li></ul><p>This article compares 6 different implementations for this specific use case, backed by benchmarks.</p><h3>Article Outline</h3><ol><li>The theoretical basics of fisheye dewarping (short version, I promise)</li><li>Three implementations of the same algorithm:<br>- Command-line FFmpeg<br>- Native Python (loops, no libs)<br>- Vectorized NumPy</li><li>Comparative benchmarks: execution time, RAM, implementation complexity</li><li>A teaser for Part 2, where we explore OpenCV and an ad-hoc C++ implementation.</li></ol><p><strong>Important:</strong> This comparison is specific to our use case (fixed cameras, static views, real-time performance). If your needs differ — mobile cameras, dynamic recalibration, maximum quality, etc. — adapt accordingly.</p><h3>A bit of theory (just enough)</h3><h4>The problem in pictures</h4><p>A ceiling-mounted 360° fisheye camera captures the entire surrounding space in a distorted circular image. For our detection algorithms to work, we extract several flat rectangular views from it. The simplest is to show an image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xB2EUNeVgRN7_RYdSej6lQ.png" /><figcaption>The 5 flat views expected from dewarping</figcaption></figure><p>In practice, dewarping breaks down into two phases:</p><ol><li><strong>Mapping calculation:</strong> we create a lookup table. For each pixel of our 5 output flat views, we calculate which fisheye image pixel to fetch. Concretely, each point of the fisheye image is projected onto a hemisphere. We define virtual cameras pointed in the direction of interest and calculate which portion of the hemisphere they “see”. Ultimately, for each point in the final image (the one seen by the virtual camera), we obtain the coordinates of the point in the fisheye image that it sees. What matters at this stage is that the calculation is accurate. For optimal rendering, we should technically account for optical lens distortions, but in our use case, we don’t really care.</li><li><strong>Mapping application:</strong> The mapping is calculated only <strong>once</strong>. It is a bit heavy to compute, but it is just geometry and does not depend on the image. It is then used for every image, and this part is much heavier on the total computing time. It has to go through all the pixels of the final image and apply the mapping, meaning fetch all points in the initial fisheye image and do that for every image of the stream. This is the part to optimize if we want performance.</li></ol><p><strong>A detail to notice</strong>: during the first phase, the coordinates of the pixel to fetch from the original image generally do not fall on integer values. To find the right color, one typically averages the values of the surrounding pixels. The technical term is <em>interpolation</em>. Since we prioritize speed over precision, we skip the complex interpolation and keep only the nearest pixel (the “nearest neighbor” interpolation technique).</p><h3>FFmpeg — No Code Required</h3><p>FFmpeg natively supports this type of dewarping via its v360 filter. The implementation is therefore straightforward, and we just &quot;simply&quot; call the command-line tool. Of course, it&#39;s never that simple, and finding the right parameters for the views we care about is a real pain.</p><pre>ffmpeg -y -i &quot;fisheye.mp4&quot; \<br> -vf &quot;crop=1920:1920,v360=input=fisheye:output=flat:interp=near:yaw=0:pitch=45:roll=0:v_fov=90:w=960:h=960&quot;\<br> &quot;unwarped_1.mp4&quot;\<br> -vf &quot;rotate=4*72*PI/180,crop=1920:1920,v360=input=fisheye:output=flat:interp=near:yaw=0:pitch=45:roll=0:v_fov=90:w=960:h=960&quot;\<br> &quot;unwarped_2.mp4&quot;\<br> -vf &quot;rotate=3*72*PI/180,crop=1920:1920,v360=input=fisheye:output=flat:interp=near:yaw=0:pitch=45:roll=0:v_fov=90:w=960:h=960&quot;\<br> &quot;unwarped_3.mp4&quot;\<br> -vf &quot;rotate=2*72*PI/180,crop=1920:1920,v360=input=fisheye:output=flat:interp=near:yaw=0:pitch=45:roll=0:v_fov=90:w=960:h=960&quot;\<br> &quot;unwarped_4.mp4&quot;\<br> -vf &quot;rotate=72*PI/180,crop=1920:1920,v360=input=fisheye:output=flat:interp=near:yaw=0:pitch=45:roll=0:v_fov=90:w=960:h=960&quot;\<br> &quot;unwarped_5.mp4&quot;</pre><p>In theory: <em>yaw</em>, <em>pitch</em>, and <em>roll</em> are the angles describing the orientation of the fisheye camera. These angles, widely used in aviation, come from navigation. <strong>Yaw</strong> is a rotation around the optical axis, i.e., a flat rotation towards another direction. <strong>Pitch</strong> is the degree of nose-up or nose-down, and <strong>Roll</strong> is the inclination of the wings to the left or right. However, our fisheye camera is, in a way, a diving plane, which makes their interpretation less intuitive.</p><p>The role of pitch is fairly clear: we don’t want a pitch of zero (camera looking down), so we pitch up by 45 degrees to aim it at the middle of the dome. There is no way to achieve the desired rotation for the different views by tweaking yaw and roll; all values result in tilting or distorting the final flat image to the left or right. Only yaw=0 and roll=0 yield the desired “flat image, horizon up” orientation. This is a bit surprising because, as we will see later, we don’t have this problem at all when programming the rotation matrix ourselves; in that case, varying the roll is sufficient, which is what one expects for a fisheye camera.</p><p>Fortunately, it is quite simple to overcome this obstacle by applying a pre-rotation to the original fisheye image.</p><p>v_fov=90` and w=960:960 describe the field of view of the output view’s virtual camera: v_fov is a vertical angle of 90° (from the ground to the horizon from the center), and width and height are 960 pixels, i.e., half of each dimension of the source image (1920x1920). As already indicated, we opt for the fastest interpolation: interp=near (linear is the default).</p><p>The performance measurements for this specific case provide a baseline but are also slightly biased, as the measured time includes decoding the original video and re-encoding the five resulting videos (which is unnecessary in our use case). The creation of these five videos happens simultaneously in parallel, and ffmpeg is globally very efficient.</p><p>To compare the results obtained with other methods against ffmpeg’s performance, I fed ffmpeg a video containing 1024 frames, while the other methods are applied successively to 1024 frames (1024 times the same frame but we don’t care for performances benchmarking). The idea it to reduce the importance of time spent performing the projective geometry calculations, as it doesn’t matter much in actual use case.</p><p>Actually if I were a bit less lazy, I should have provided two separate benchmarks, one for the projective calculations, one for the pixel mapping. Leaving that as an exercise for the reader.</p><pre>./unwarper_ffmpeg.sh fisheye_video.mp4<br>======================================================================<br>BENCHMARK RESULTS<br>======================================================================<br>Wall time:              208.64s<br>User time:           1401.84s<br>System time:         10.00s<br>CPU utilization:        676%<br>Cores used:             ~6.8<br>Peak memory:            1784.20 MB (1827016 KB)<br>Page faults:            387273 minor, 0 major<br>Context switches:       328327 vol, 712451 invol<br>Exit status:            0<br>Parallel speedup:       6.77x<br>(CPU time / Wall time = 1411.84s / 208.64s)<br>======================================================================</pre><p><strong>Results</strong>: 208 seconds to process 1024 frames and generate 5 views, amounting to 5120 extracted flat images, or about 40ms per flat image.</p><p>FFmpeg leverages the 8 available cores very well (~676% CPU usage), with a parallel speedup of 6.8x. Memory usage, however, climbs to 1.7 GB, which is significant. This memory usage does not depend on the length of the film.</p><p>FFmpeg provides fast, parallelized processing but suffers from high memory consumption and limited flexibility. While effective as a fallback, its black-box nature and resource demands make it a poor fit for our integrated Python pipeline (actually direct calls to underlying libs used by ffmpeg could fix that). Nevertheless, now we have some reference figures to go on.</p><h3>Pure Python — Coding from Scratch</h3><p>Following the “black box” solution with FFmpeg, here is a second implementation in pure Python that uses only standard libraries and NumPy for array manipulation. However, we are not yet trying to optimize the NumPy code using its vectorization capabilities.</p><p>The objective here is not performance, but understanding. It’s intended to be used as the educational reference serving as a baseline for our future optimizations: a proof of concept.</p><pre>#!/usr/bin/env python3<br>&quot;&quot;&quot;<br>Pure Python Fisheye Unwarper<br><br>Cette implémentation en Python pur du dewarping fisheye utilise uniquement<br>des bibliothèques standard et numpy pour manipuler des tableaux,<br>sans optimisation vectorielle.<br>&quot;&quot;&quot;<br><br>def multiply_quaternion(a: np.ndarray, b: np.ndarray) -&gt; np.ndarray:<br>    &quot;&quot;&quot;<br>    Multiply two quaternions using Python primitives.<br>    <br>    Args:<br>        a: First quaternion [w, x, y, z]<br>        b: Second quaternion [w, x, y, z]<br>        <br>    Returns:<br>        Result quaternion [w, x, y, z]<br>    &quot;&quot;&quot;<br>    w1, x1, y1, z1 = a<br>    w2, x2, y2, z2 = b<br>    <br>    w = w1*w2 - x1*x2 - y1*y2 - z1*z2<br>    x = w1*x2 + x1*w2 + y1*z2 - z1*y2<br>    y = w1*y2 - x1*z2 + y1*w2 + z1*x2<br>    z = w1*z2 + x1*y2 - y1*x2 + z1*w2<br>    <br>    return np.array([w, x, y, z], dtype=np.float64)<br><br>def get_rotation_matrix(yaw: float, pitch: float, roll: float) -&gt; np.ndarray:<br>    &quot;&quot;&quot;<br>    Generate rotation matrix from yaw, pitch, roll angles (in degrees).<br>    <br>    Args:<br>        yaw: Rotation around Y axis in degrees<br>        pitch: Rotation around X axis in degrees<br>        roll: Rotation around Z axis in degrees<br>    Returns:<br>        3x3 rotation matrix as numpy array<br>    &quot;&quot;&quot;<br>    # Yaw quaternion, rotate view around Y axis<br>    yaw = np.deg2rad(0)<br>    yaw_q = np.array([np.cos(yaw/2.0), 0.0, np.sin(yaw/2.0), 0.0], dtype=np.float64)<br>    # Pitch quaternion, rotate view around X axis (look up 45 degrees)<br>    pitch = np.deg2rad(45)             <br>    pitch_q = np.array([np.cos(pitch/2.0), np.sin(pitch/2.0), 0.0, 0.0], dtype=np.float64)<br>    # Roll quaternion, rotate view around Z axis (look in different direction)<br>    roll = np.deg2rad(roll)<br>    roll_q = np.array([np.cos(roll/2.0), 0.0, 0.0, np.sin(roll/2.0)], dtype=np.float64)<br><br>    rq = multiply_quaternion(roll_q, multiply_quaternion(pitch_q, yaw_q))<br><br>    # Build spherical projection matrix from quaternions<br>    w, x, y, z = rq<br>    return np.array([<br>        [ (w*w + x*x - y*y - z*z),  2.0 * (x*y - z*w), 2.0 * (w*y + x*z)],<br>        [ 2.0 * (w*z + x*y), (w*w - x*x + y*y - z*z), 2.0 * (y*z - w*x)],<br>        [ 2.0 * (x*z - y*w), 2.0 * (w*x + y*z), (w*w - x*x - y*y + z*z)]], dtype=np.float64)<br><br><br>def project2D(xyz: np.ndarray) -&gt; Tuple[int, int]:<br>    &quot;&quot;&quot;Project 3D Dome point to 2D Fisheye image&quot;&quot;&quot;<br>    hs = np.hypot(xyz[0],xyz[1])<br>    phi = np.arctan2(hs, xyz[2])<br>    coeff = phi / (hs * np.pi)<br>    src_x = xyz[0] * coeff + 0.5<br>    src_y = xyz[1] * coeff + 0.5<br>    return src_x, src_y<br><br><br>class PythonDewarper:<br>    &quot;&quot;&quot;<br>    Pure Python implementation of the fisheye dewarper.    <br>    &quot;&quot;&quot;<br>    <br>    def __init__(self, width: int, height: int, zones: int = 3):<br>        &quot;&quot;&quot;<br>        Initialize dewarper with image dimensions.<br>        <br>        Args:<br>            width: Image width in pixels<br>            height: Image height in pixels<br>        &quot;&quot;&quot;<br>        self.width = width<br>        self.height = height<br>        self.output_width = self.width // 2<br>        self.output_height = self.height // 2<br>        self.zones = zones<br>        <br>        # Remapping tables for each view<br>        self.remap = self._dewarp_mapping()<br>        self.output_buffer = np.zeros((self.zones, self.output_height, self.output_width, 3), dtype=np.uint8)<br><br>    def _dewarp_mapping(self) -&gt; List[List[List[Tuple[int, int]]]]:<br>        &quot;&quot;&quot;<br>        Create pixel remapping table for specific view.<br>        <br>        This is the core dewarping algorithm using spherical projection.<br>        &quot;&quot;&quot;<br>       <br>        remap = []<br>        for zone_id in range(self.zones):<br>    <br>            # Get rotation matrix for this zone<br>            R = get_rotation_matrix(0, 45, zone_id * (360.0 / self.zones))<br><br>            remap_zone = []<br>            for j in range(self.output_height):<br>                line = []<br>                for i in range(self.output_width):<br>                    v = np.array([i / (0.25 * self.width) - 1.0, j / (0.25 * self.height) - 1.0, 1.0])<br>                    xyz = R @ v.T<br>                    src_x, src_y = project2D(xyz)<br>                    map_y = int(src_y * self.height)<br>                    map_x = int(src_x * self.width)<br>                    if 0 &lt;= map_y &lt; self.height and 0 &lt;= map_x &lt; self.width:    <br>                        line.append((map_y, map_x))<br>                    else:<br>                        line.append((0, 0))<br>                remap_zone.append(line)<br>            remap.append(remap_zone)<br><br>        return remap<br>    <br>    def dewarp_frame(self, image: np.ndarray, zone_id: int = -1):<br>        &quot;&quot;&quot;<br>        Apply dewarping transformation to image.<br>        <br>        Args:<br>            image: Input image as NumPy array (H, W, 3)<br>        &quot;&quot;&quot;<br>        <br>        remap_table = self.remap[zone_id]<br>        output_buffer = self.output_buffer[zone_id]<br><br>        for i in range(self.output_height):<br>            for j in range(self.output_width):<br>                # Note: never out of bound as it is ensured when building remapping<br>                output_buffer[i, j] = image[remap_table[i][j]]<br><br>        return output_buffer.reshape((self.output_height, self.output_width, 3))</pre><p>Let’s take a look under the hood. We are going to talk a bit of math; those allergic to it can skip ahead, but it would be a shame because it’s interesting.</p><p>First, we chose to represent rotations using quaternions. Why quaternions rather than a rotation matrix? Quaternions are a sort of “super complex numbers,” with four dimensions instead of two, invented in 1843 by William Hamilton — yes, the one from the Hamiltonian — to represent rotations in 3D space. A bit denigrated originally because they appeared more complicated than Euler angles, they have since conquered 3D, robotics, aerospace, and… fisheye dewarping.</p><p>Why not classic Euler angles? Euler angles (yaw/pitch/roll) are intuitive but have flaws. The main one is Gimbal Lock (likely the source of the difficulties encountered earlier with FFmpeg parameters settings). For those interested, here are details about Gimbal lock <a href="https://en.wikipedia.org/wiki/Gimbal_lock">https://en.wikipedia.org/wiki/Gimbal_lock</a>. It’s a very real problem, as it nearly compromised the Apollo XI Lunar Mission.</p><p>The other reason for using quaternions is that calculations are simpler on a computer; they are easy to manipulate and avoid the accumulation of numerical errors. A quaternion is a list of four numbers [w,x,y,z] with <strong>w</strong> being the real part of the quaternion and <strong>(x, y, z)</strong> its vector part, which represents the direction of the axis of rotation. A rotation of θ around a unit axis (ax, ay, az) is written simply:</p><pre>q = [cos(θ/2), ax.sin(θ/2), ay.sin(θ/2), az.sin(θ/2)]</pre><p>To retrieve the three directions “yaw”, “pitch”, and “roll”, it suffices to keep only one of the three components x, y, or z of the quaternion. To combine them, we use the quaternion multiplication formula. Be careful: in the case of quaternions, the order of multiplication matters!</p><p>This time, to observe in the different directions, it is enough to change the angle of the roll component, and we obtain the expected behavior.</p><h4>From Quaternion to Projection Matrix</h4><p>The quaternion gives us the orientation of the camera, but to project pixels onto the fisheye disk, we need a 3×3 spherical projection matrix.</p><p>This matrix transforms a point (x, y) of the output image into a point (X, Y, Z) on the virtual hemisphere centered on the fisheye camera.</p><p>The formulas come from the conversion quaternion → rotation matrix, adapted for fisheye spherical projection. Each coefficient of the matrix m[i,j] encodes how the output coordinates (x, y) contribute to the 3D point coordinates (X, Y, Z).</p><p>The 9 coefficients of the matrix are calculated according to this same principle, each combining the quaternion components in a specific way to encode the complete 3D rotation.</p><h4>Final Spherical Projection</h4><p>Once we have the 3D point (X, Y, Z) on the hemisphere, we must re-project it into the source fisheye image:</p><pre>hs = sqrt(X2 + Y2)` # Horizontal distance of the point<br>phi = atan2(hs, Z) #Angle from the zenith (0 to pi/2)<br>src_x = width *(X * phi / (pi * hs) + 0.5)<br>src_y = height *(Y * phi / (pi * hs) + 0.5)</pre><p>This formula implements the equidistant projection, the standard model for fisheye lenses:</p><p>The angle phi (angle from the zenith) is proportional to the radial distance in the fisheye image</p><p>X / hs and Y / hs give the normalized azimuthal direction</p><p>The factor phi / (π × hs) converts the angle into a normalized radial distance [0, 0.5]</p><p>The +0.5 centers the image (shifting from [-0.5, 0.5] to [0, 1])</p><p>This equidistant model means that an object at 45° from the center appears halfway between the center and the edge of the fisheye image; an object at 90° is exactly at the edge.</p><h4><strong>End of the math</strong></h4><p>Those who wanted to skip this part can start reading again here.</p><p><strong>In short:</strong> it’s magic, just use the right formula for the incantations.</p><h4>Benchmark</h4><pre>🔍 Commande: uv run ./unwarper_python.py ../images/fisheye.jpg -r 1024<br>======================================================================<br>📈 BENCHMARK RESULTS<br>======================================================================<br>⏱️  Wall time:              1889.36s<br>⚙️  CPU time (user+sys):    1889.34s<br>    ├─ User time:           1888.94s<br>    └─ System time:         0.40s<br>🔥 CPU used:                99%<br>💻 Cores used:              ~1.0<br>🧠 Peak Memory:             646 MB (662148 KB)<br>======================================================================</pre><p>No need to dwell on performance, especially since the benchmark isn’t very precise (it is affected by the OS doing other tasks). However, we observe that while ffmpeg is much faster in wall-clock time thanks to multi-core processing, the overall CPU consumption of both configurations is of the same order of magnitude because ffmpeg uses 6.8 cores, whereas our Python version uses only 1 core. That is surprisingly efficient for interpreted Python!</p><p>While the implementation is highly readable and memory-efficient — making it perfect for understanding the algorithm — it relies on slow Python loops and lacks vectorization. Consequently, it is strictly for prototyping and is far too slow for real-time production use. But we will fix that!</p><h3>Vectorized NumPy — Major Performance Boost</h3><p>We keep exactly the same algorithm as the pure Python version, but we eliminate Python loops by using NumPy’s vectorized operations. The idea is to let NumPy — written in optimized C and using SMID CPU instruction set when possible — handle the millions of iterations instead of the Python interpreter.</p><h4><strong>The Key Changes</strong></h4><p>Instead of iterating pixel by pixel with nested Python loops, we calculate everything at once by manipulating entire arrays of coordinates. The mapping calculation remains identical (quaternions, projection matrix), but the computing becomes massively parallel thanks to broadcasting and vectorization.</p><h4>Phase 1: Vectorized mapping calculation</h4><p><strong>Before (Pure Python):</strong></p><pre>remap_zone = []<br>for j in range(self.output_height):<br> line = []<br> y = j — offset_height<br> for i in range(self.output_width):<br> x = i — offset_width<br><br>  # ... here compute mapped coordinates for this pixel ...<br><br> line.append((src_y, src_x))<br> remap_zone.append(line)</pre><p><strong>After (Vectorized NumPy):</strong></p><pre># Create a grid of all coordinates at once<br>i_coords, j_coords = np.meshgrid(<br>    np.arange(self.output_width),<br>    np.arange(self.output_height),<br>    indexing=&#39;xy&#39;)<br><br># Flatten en recenter coordinates<br>x_coords = i_coords.flatten() * inv_width  - 1.0<br>y_coords = j_coords.flatten() * inv_height - 1.0<br><br># Stack into a matrix of homogeneous coordinates<br>coords = np.column_stack([x_coords, y_coords, np.ones_like(x_coords)]).T<br><br># ONE (matrix multiplication) to rule them ALL<br>xyz = R @ coords<br><br># Vectorized calculations (applied to coordinates simultaneously)<br>hs = np.hypot(xyz[0, :],xyz[1, :])<br>phi = np.arctan2(hs, xyz[2, :])<br>coeff = phi / (hs * np.pi)<br>src_x = (self.width * (xyz[0, :] * coeff + 0.5)).astype(np.int32)<br>src_y = (self.height * (xyz[1, :] * coeff + 0.5)).astype(np.int32)<br><br># Clip to stay within image bounds<br>src_x = np.clip(src_x, 0, self.width - 1)<br>src_y = np.clip(src_y, 0, self.height - 1)<br><br># # Reshape into 2D and store<br>zone_mapping = np.stack([<br>    src_x.reshape((self.output_height, self.output_width)),<br>    src_y.reshape((self.output_height, self.output_width))<br>], axis=-1)</pre><p>Gain: Instead of 960×960 = 921,600 Python loop iterations, we have a single matrix multiplication optimized in C plus a few vectorized operations. NumPy uses the CPU’s SIMD instructions (SSE, AVX) to process multiple values simultaneously. That’s good, but it’s a step we only perform once.</p><h4>Phase 2: Vectorized mapping application</h4><p><strong>Before (Pure Python):</strong></p><pre>for i in range(self.output_height):<br>    for j in range(self.output_width):<br>        try:<br>            output_buffer[i, j] = image[remap_table[i][j]]<br>        except IndexError:<br>            output_buffer[i, j] = [0, 0, 0]</pre><p><strong>After (Vectorized NumPy):</strong></p><pre># Extract source coordinates<br>src_x = remap_table[:, :, 0]<br>src_y = remap_table[:, :, 1]<br><br># Advanced NumPy indexing: copy ALL pixels at once<br>output_buffer = image[src_y, src_x]</pre><p><strong>Critical Detail: The Validity Mask Trap</strong></p><p>An initial version attempted to explicitly handle out-of-bounds pixels using a boolean mask:</p><pre>valid_mask = ((src_y &gt;= 0) &amp; (src_y &lt; self.height) &amp;<br>              (src_x &gt;= 0) &amp; (src_x &lt; self.width))<br>output_buffer[valid_mask] = image[src_y[valid_mask], src_x[valid_mask]]</pre><p>Very bad idea! With the mask the mapping is more than two times slower, which is not really surprising, the copy of pixels works in a tight loop and any added computing there has a high cost and may affects memory cache performance and branch prediction.</p><p>It’s much more elegant to clip coordinates when computing mapping (Phase 1). The few out of bound pixels are redirected to the left upper corner of the image, which is invisible in the final image.</p><pre>src_x = np.clip(src_x, 0, self.width - 1)<br>src_y = np.clip(src_y, 0, self.height - 1)</pre><h4>Benchmark</h4><pre>🔍 python3 unwarper_numpy.py -r 1024 ../images/fisheye.jpg<br>======================================================================<br>📈 BENCHMARK RESULTS<br>======================================================================<br>⏱️  Wall time:              110.11s<br>⚙️  CPU time (user+sys):    113.83s<br>    ├─ User time:           113.14s<br>    └─ System time:         0.69s<br>🔥 CPU used:                103%<br>💻 Cores used:              ~1.0<br>🧠 Peak Memory:             255.73 MB (261868 KB)<br>======================================================================</pre><p>At about 20ms per frame per view the code becomes actually usable for our needs. We can still go faster (and we will in part two), but result of such small changes is impressive. A few vectorized instructions has made our python process 17x faster!</p><p><strong>Side benefit:</strong> for our use case using only a single core is not a problem at all, as the system handles several streams at once and the other cores are busy anyway. This means that compared to FFmpeg using about 7 times fewer CPU resources is even more significant than the 2x improvement in wall-clock time.</p><p><strong>Full code:</strong> <a href="http://github.com/pykoder/fisheye-dewarping">github.com/pykoder/fisheye-dewarping</a></p><h3>To be continued</h3><p>In the next article, I will explore three other implementations that push performance gains even further.</p><ul><li><strong>OpenCV Python:</strong> using cv2.remap() with multi-core parallelism</li><li><strong>OpenCV C++:</strong> compiled native OpenCV code to eliminate Python overhead.</li><li><strong>Custom C++ Library</strong>: (spoiler alert) 4× faster than numpy version while consuming only 80 MB of RAM</li></ul><p>If you don’t want to wait to see the result, it’s already available on my github repository.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1df2f6355731" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>