Algorithm Search⌘K

Algorithmintro

B-mode image formation

Also called brightness mode imaging.

Turn beamformed ultrasound RF lines into a gray-scale image: detect the envelope of each line, compensate the loss with depth, compress on a log scale and map the lines to pixels.

Time
O(K n log n + P) worst
Space
O(n) extra
Where
K = the number of lines; P = the number of output pixels; n = the number of samples per line
Properties
deterministicexactnot linear in dataiterative

B-mode (brightness mode) image formation turns the beamformed radio frequency (RF) lines of an ultrasound scan into the gray-scale image that a user sees. Each line is the output of a beamformer, for example delay-and-sum with dynamic receive focusing, along one beam direction. The RF line oscillates at the transmit frequency, so the brightness comes from its envelope, the modulus of the analytic signal built with the Hilbert transform. A depth-dependent gain, time gain compensation, offsets the attenuation of the tissue. The envelope spans a range of about 60 dB or more between strong and weak echoes, so it is compressed on a log scale to the 256 gray levels of a display. Last, scan conversion maps the lines, given in depth and angle for a sector scan, to the pixels of a Cartesian image. The depth of a sample at time tt is z=ct/2z = c t / 2, because the echo travels down and back.

In plain words

The scanner sends a pulse along one direction and records the echoes over time. Echoes from deeper places come back later, so time tells depth. The recording wiggles up and down very fast; what matters is how strong the wiggles are, so you trace their outline, the envelope. Deep echoes are weaker because sound loses energy on the way, so you turn up the gain with depth. Strong echoes are many thousands of times stronger than weak ones, so you use a log scale, as in decibels, before you turn strength into brightness. Finally, the recordings fan out from the probe, so you redraw them on a square grid of pixels.

The problem

The input is KK real RF lines xk=(xk[0],…,xk[n−1])x_k = (x_k[0], \ldots, x_k[n-1]), one for each beam angle θk\theta_k of a sector scan, sampled at the times t0+q/fst_0 + q/f_s. The parameters are the speed of sound cc, a dynamic range DD in dB, an optional gain GG in dB per mm and an output grid of pixels (x,z)(x, z). The output is a gray level in {0,…,255}\{0, \ldots, 255\} for every pixel; pixels outside the sector are 00.

The algorithm

  1. B-MODE(x_1 … x_K, D, G) ▷ returns gray levels per line and sample
  2. 1for each line k do
  3. 2X ← DFT(x_k)
  4. 3a ← IDFT(h · X) ▷ h: 1 at 0 and n/2, 2 for positive, 0 for negative frequencies
  5. 4e_k ← |a| ▷ envelope
  6. 5e_k[q] ← e_k[q] · 10^{G z_q / 20} ▷ time gain compensation, z_q = c (t_0 + q/f_s)/2
  7. 6e_max ← max over all k, q of e_k[q]
  8. 7d ← 20 log10(e_k[q] / e_max) ▷ for every k, q
  9. 8d ← max(-D, d) ▷ clip to the dynamic range
  10. 9ℓ_k[q] ← ⌊255 (d + D)/D + 1/2⌋
  11. SCAN-CONVERT(ℓ, θ_1 … θ_K, z_0 … z_{n-1}, pixels)
  12. 10for each pixel (x, z): r ← √(x² + z²), θ ← atan2(x, z)
  13. 11if (θ, r) is outside the grid of angles and depths then the pixel is 0
  14. 12else the pixel is the bilinear interpolation of ℓ at (θ, r) from the 4 nearest samples

Lines L2 and L3 compute the analytic signal of the line in the frequency domain; its real part is the line itself. Line L5 runs only when a gain is given. The log mapping of L6 to L9 is relative to the brightest value of the whole image. Scan conversion uses bilinear interpolation in the polar grid; the angles and depths must be evenly spaced.

Example

Log compression. With D=40D = 40 dB, the envelope values 1,0.1,0.01,0.001,01, 0.1, 0.01, 0.001, 0 give 0,−20,−40,−60,−∞0, -20, -40, -60, -\infty dB, the clip of L8 gives 0,−20,−40,−40,−400, -20, -40, -40, -40, and L9 gives the gray levels 255,128,0,0,0255, 128, 0, 0, 0. Every echo more than 40 dB below the brightest one is black.

Depth axis. With t0=6.5t_0 = 6.5 us, fs=40f_s = 40 MHz, n=64n = 64 and c=1.54c = 1.54 mm/us, the samples cover the depths from 1.54⋅6.5/2=5.0051.54 \cdot 6.5 / 2 = 5.005 mm to 6.2186.218 mm, in steps of c/(2fs)=0.01925c/(2 f_s) = 0.01925 mm.

A point scatterer. The tests simulate 21 lines from −20-20 to 2020 degrees in steps of 2 degrees, a Gaussian pulse at f0=5f_0 = 5 MHz with σt=0.1\sigma_t = 0.1 us, and a crude beam model with a Gaussian angular weight of width 2 degrees. A scatterer at depth 5.6 mm and angle 4 degrees is at (x,z)=(0.391,5.586)(x, z) = (0.391, 5.586) mm. On a grid with steps of 0.1 mm in xx and 0.05 mm in zz, the brightest pixel of the converted image is at (0.4,5.6)(0.4, 5.6), with the gray level 252.5 after interpolation.

Depth gain. Two equal scatterers at 5.3 and 5.9 mm in a medium with an attenuation of 5 dB/mm one way differ by 2⋅5⋅0.6=62 \cdot 5 \cdot 0.6 = 6 dB, which is 38 gray levels at D=40D = 40 dB. A gain of G=10G = 10 dB per mm of depth brings them to within one gray level.

Correctness

The real part of the discrete analytic signal of L3 is the input line, because the weights hk+h−kh_k + h_{-k} add to 2 at every frequency; for a tone with a whole number of cycles, the envelope is exactly the amplitude. The log mapping depends only on ratios to the brightest value, is monotone, maps the peak to 255 and everything at or below −D-D dB to 0. Scan conversion is a convex combination of the four nearest samples and is exact for functions of the form α+βr+γθ+δrθ\alpha + \beta r + \gamma\theta + \delta r\theta. The gain of L5 with G=2αG = 2\alpha removes an attenuation of α\alpha dB per mm in the model. The proofs are in proofs/correctness.md.

For a pulse with a smooth envelope, the detected envelope is close to the true one but not equal, because the line is finite; the test measures an error of 6.4⋅10−46.4 \cdot 10^{-4} for a Gaussian pulse. This is a measurement, not a theorem.

Proof: Each step of B-mode image formation does what it claims, in the discrete model of the pagefull

We prove the facts behind lines L1 to L12 of the main page. A line is a real vector x=(x0,…,xn−1)x = (x_0, \ldots, x_{n-1}), its DFT is Xk=∑qxqe−2πiqk/nX_k = \sum_q x_q e^{-2\pi i q k / n}, and the inverse has the factor 1/n1/n. Indices of XX are taken modulo nn. The weights of line L3 are h0=1h_0 = 1, hk=2h_k = 2 for 0<k<n/20 < k < n/2, hn/2=1h_{n/2} = 1 when nn is even, and hk=0h_k = 0 for the other kk.

Theorem 1 (the real part of the analytic signal is the line). Let a=IDFT⁡(hX)a = \operatorname{IDFT}(h X) (lines L2 and L3). Then Re⁡aq=xq\operatorname{Re} a_q = x_q for every qq, so the imaginary part is a discrete Hilbert transform of xx and ∣aq∣≥∣xq∣|a_q| \ge |x_q|.

Proof. For any complex vector yy with DFT YY, the DFT of yˉ\bar y is k↦Y−k‾k \mapsto \overline{Y_{-k}}, so the DFT of Re⁡y=(y+yˉ)/2\operatorname{Re} y = (y + \bar y)/2 is (Yk+Y−k‾)/2(Y_k + \overline{Y_{-k}})/2. Take Y=hXY = h X. Since xx is real, X−k‾=Xk\overline{X_{-k}} = X_k, and hh is real, so (Yk+Y−k‾)/2=hk+h−k2Xk(Y_k + \overline{Y_{-k}})/2 = \frac{h_k + h_{-k}}{2} X_k. Check hk+h−k=2h_k + h_{-k} = 2 for every kk: for k=0k = 0 it is 1+11 + 1; for nn even and k=n/2k = n/2 it is 1+11 + 1; for 0<k<n/20 < k < n/2 it is 2+02 + 0; for n/2<k<nn/2 < k < n it is 0+20 + 2. So the DFT of Re⁡a\operatorname{Re} a is XX, and Re⁡a=x\operatorname{Re} a = x. □\square

Theorem 2 (the envelope of a tone). Let xq=Acos⁡(2πk0q/n+φ)x_q = A \cos(2\pi k_0 q / n + \varphi) with A≥0A \ge 0 and an integer 0<k0<n/20 < k_0 < n/2. Then aq=Aei(2πk0q/n+φ)a_q = A e^{i(2\pi k_0 q/n + \varphi)} and the envelope of line L4 is the constant AA.

Proof. xq=A2(eiφe2πik0q/n+e−iφe−2πik0q/n)x_q = \frac{A}{2}(e^{i\varphi} e^{2\pi i k_0 q/n} + e^{-i\varphi} e^{-2\pi i k_0 q/n}), so XX is nA2eiφ\frac{nA}{2} e^{i\varphi} at k0k_0, nA2e−iφ\frac{nA}{2} e^{-i\varphi} at n−k0n - k_0, and 00 elsewhere. Line L3 doubles the first and removes the second, because n−k0>n/2n - k_0 > n/2. The inverse DFT of nAeiφn A e^{i\varphi} at k0k_0 is the stated aa. □\square

For a pulse g(t)cos⁡(2πf0t)g(t)\cos(2\pi f_0 t) with a smooth envelope whose spectrum does not reach the zero frequency, the envelope is close to gg, but not exact: the line is finite and the DFT treats it as periodic. This is a heuristic, and the test measures an error of 6.4⋅10−46.4 \cdot 10^{-4} for a Gaussian envelope with σt=0.1\sigma_t = 0.1 us at f0=5f_0 = 5 MHz, fs=40f_s = 40 MHz and n=64n = 64.

Theorem 3 (time gain compensation). Suppose the echo of a scatterer at depth zz has the amplitude b 10−2αz/20b\, 10^{-2\alpha z/20}, with an attenuation of α\alpha dB per mm one way. Line L5 with the gain G=2αG = 2\alpha dB per mm gives bb, independent of zz.

Proof. b 10−2αz/20⋅10Gz/20=bb\, 10^{-2\alpha z/20} \cdot 10^{G z / 20} = b when G=2αG = 2\alpha. □\square

In this model the two echoes of the test, at 5.3 and 5.9 mm with α=5\alpha = 5 dB/mm, differ by 2⋅5⋅0.6=62 \cdot 5 \cdot 0.6 = 6 dB before the gain and by nothing after. Real attenuation depends on the frequency and on the tissue, so a real gain curve is set by the user or by an adaptive rule.

Theorem 4 (log compression). Let emax⁡e_{\max} be the largest envelope value (line L6) and DD the dynamic range in dB. Line L9 maps ee to the gray level ℓ(e)=⌊255(d+D)/D+12⌋\ell(e) = \lfloor 255 (d + D)/D + \tfrac12 \rfloor with d=max⁡(−D,20log⁡10(e/emax⁡))d = \max(-D, 20 \log_{10}(e/e_{\max})). Then:

  1. ℓ\ell depends only on the ratio e/emax⁡e/e_{\max}, so scaling all envelopes by c>0c > 0 gives the same image;
  2. ℓ\ell is nondecreasing in ee, ℓ(emax⁡)=255\ell(e_{\max}) = 255, and ℓ(e)=0\ell(e) = 0 for every e≤emax⁡10−D/20e \le e_{\max} 10^{-D/20}, including e=0e = 0;
  3. every level lies in {0,…,255}\{0, \ldots, 255\}.

Proof. (1) Scaling by cc scales emax⁡e_{\max} by cc too. (2) The logarithm, the clipping of line L8, the affine map and the rounding are nondecreasing. At emax⁡e_{\max}, d=0d = 0 and ℓ=255\ell = 255. For e≤emax⁡10−D/20e \le e_{\max} 10^{-D/20}, d=−Dd = -D and ℓ=0\ell = 0. (3) d∈[−D,0]d \in [-D, 0], so 255(d+D)/D∈[0,255]255(d + D)/D \in [0, 255], and rounding keeps it in that range. □\square

For example, with D=40D = 40 dB, the ratios 1,0.1,0.011, 0.1, 0.01 give 0,−20,−400, -20, -40 dB and the levels 255255, ⌊128.0⌋=128\lfloor 128.0 \rfloor = 128 and 00.

Theorem 5 (scan conversion). Let the polar samples be f(θk,rq)f(\theta_k, r_q) on an evenly spaced grid of angles and depths. For a pixel inside the sector, line L12 returns a convex combination of the four nearest samples, and it returns f(θ,r)f(\theta, r) exactly when ff has the form α+βr+γθ+δrθ\alpha + \beta r + \gamma \theta + \delta r \theta. Pixels outside the sector get 00 (line L11).

Proof. The weights (1−a)(1−b)(1-a)(1-b), a(1−b)a(1-b), (1−a)b(1-a)b and abab with a,b∈[0,1]a, b \in [0, 1] are nonnegative and sum to 11. Bilinear interpolation on one cell reproduces the functions 11, rr, θ\theta and rθr\theta: for rr, the result is (1−b)rq+brq+1=r(1-b) r_q + b r_{q+1} = r because r=rq+b(rq+1−rq)r = r_q + b (r_{q+1} - r_q), and the same holds for θ\theta; for rθr \theta the weights factor into a product of the two one-dimensional cases. By linearity it reproduces their combinations. □\square

Theorem 6 (cost). For KK lines of nn samples and PP output pixels, the envelopes cost O(Knlog⁡n)O(K n \log n) with a radix-2 FFT (the helper uses it when nn is a power of 2, and an O(n2)O(n^2) DFT otherwise), lines L5 to L9 cost O(Kn)O(K n), and lines L10 to L12 cost O(P)O(P).

Proof. Each step is a fixed number of operations per sample or per pixel, apart from the DFT pair of each line. □\square

Complexity

In the real-RAM model, the envelope of a line of nn samples costs O(nlog⁡n)O(n \log n) with a radix-2 FFT, so all lines cost O(Knlog⁡n)O(K n \log n). Lines L5 to L9 cost O(Kn)O(K n), and scan conversion costs O(1)O(1) per pixel, O(P)O(P) in total. The extra space is O(n)O(n) for one line. A real scanner computes the envelope with an IQ demodulator or a short Hilbert filter, at O(1)O(1) per sample.

Properties

  • Not linear: the modulus and the logarithm destroy linearity. Speckle, the granular pattern of tissue, comes from the interference that the modulus makes visible; see speckle.
  • Scale invariant: multiplying the RF data by a constant does not change the image.
  • The dynamic range DD and the gain curve are display choices. Values such as D=60D = 60 dB are tuned for the eye and the tissue, not derived.
  • The depth resolution is set by the pulse length, about c τ/2c\, \tau / 2 for a pulse of duration τ\tau; the lateral resolution is set by the beamformer.

Variants and improvements

  • IQ demodulation. Mix the RF line with e−i2πf0te^{-i 2\pi f_0 t} and low-pass filter it, then take the modulus. This is the usual path in hardware and gives the same envelope for a narrow-band signal.
  • Compounding. Spatial or frequency compounding averages envelopes of different angles or bands to lower the speckle contrast; plane-wave compounding sums before the envelope and does not.
  • Adaptive weights. A coherence factor or another adaptive beamformer changes the lines before this chain.
  • Other compression curves. S-shaped and other gray maps are used in place of the pure log; they keep the order of the levels.
  • Linear arrays. For parallel lines, scan conversion is a plain interpolation in xx and zz, without the polar map.

When to use it

B-mode image formation is the last step of almost every pulse-echo ultrasound system, whatever beamformer comes before it. Skip the log compression and the scan conversion when the data go to further processing, such as Doppler, elastography or quantitative backscatter estimation, which need the complex or linear values.

Pitfalls

  • Wrong depth axis. The depth is ct/2c t / 2, not ctc t.
  • Rectification in place of the envelope. Taking ∣x∣|x| of the RF line gives a rectified signal, not the envelope; use the analytic signal or IQ data.
  • Circular wrap. The DFT treats the line as periodic, so a strong echo near one end leaks into the other end. Pad the line or use a finite Hilbert filter.
  • Log of zero. A zero envelope has the level −∞-\infty dB; clip it, as line L8 does.
  • Nearest-neighbor scan conversion. It gives jagged edges at depth, where the lines are far apart; use at least bilinear interpolation.
  • Gain too high. Noise at depth grows with the gain and fills the image with a gray floor.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

b_mode_image_formation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/b-mode-image-formation/. The authors are listed in prov/P3DHGZ.jsonl.
"""B-mode image formation from beamformed RF lines.

The input is a set of real RF lines after beamforming, one per beam direction,
each sampled at the times t0 + q / fs. The steps are:

1. envelope detection: the magnitude of the analytic signal, computed with a
   DFT that keeps the zero frequency, doubles the positive frequencies and
   removes the negative ones;
2. time gain compensation (optional): multiply by a gain that grows with depth;
3. log compression to a dynamic range DR (a display choice), mapped to the
   gray levels 0 to 255;
4. scan conversion of a sector scan to a Cartesian grid by bilinear
   interpolation in (depth, angle).

Units are millimetres, microseconds and megahertz. Depth is z = c t / 2 with
c = 1.54 mm/us (1540 m/s), a convention for soft tissue.
"""

import math

from imgkit import dft, idft

SOUND_SPEED = 1.54  # mm per microsecond


def analytic_signal(x):
    """The discrete analytic signal of a real line: real part x, imaginary part a discrete Hilbert transform."""
    n = len(x)
    xf = dft(x)  # @line L2
    h = [0.0] * n
    h[0] = 1.0
    if n % 2 == 0:
        h[n // 2] = 1.0
        for k in range(1, n // 2):
            h[k] = 2.0
    else:
        for k in range(1, (n + 1) // 2):
            h[k] = 2.0
    return idft([hk * v for hk, v in zip(h, xf)])  # @line L3


def envelope(x):
    """The envelope |x + i H x| of a real line."""
    return [abs(v) for v in analytic_signal(x)]  # @line L4


def sample_depths(n, t0, fs, c=SOUND_SPEED):
    """Depth of sample q: z_q = c (t0 + q / fs) / 2."""
    return [c * (t0 + q / fs) / 2 for q in range(n)]


def tgc(env, depths, gain_db_per_mm):
    """Time gain compensation: multiply by 10^(gain_db_per_mm z / 20)."""
    return [e * 10 ** (gain_db_per_mm * z / 20) for e, z in zip(env, depths)]  # @line L5


def log_compress(lines, dynamic_range_db):
    """Gray levels 0..255 from envelopes: 20 log10(e / max) clipped to [-DR, 0], mapped linearly."""
    peak = max(max(row) for row in lines)  # @line L6
    out = []
    for row in lines:
        g = []
        for e in row:
            d = 20 * math.log10(e / peak) if e > 0 else -math.inf  # @line L7
            d = max(-dynamic_range_db, d)  # @line L8
            g.append(math.floor(255 * (d + dynamic_range_db) / dynamic_range_db + 0.5))  # @line L9
        out.append(g)
    return out


def scan_convert(polar, angles, depths, xs, zs):
    """Bilinear interpolation of polar[k][q] (line k at angle angles[k], depth depths[q]) on the grid (x, z).

    The angles and depths must be increasing and evenly spaced. The apex is at
    the origin and angle 0 points along +z. Pixels outside the sector are 0.
    """
    da = angles[1] - angles[0]
    dr = depths[1] - depths[0]
    out = []
    for z in zs:
        row = []
        for x in xs:
            r = math.hypot(x, z)  # @line L10
            th = math.atan2(x, z)
            u = (th - angles[0]) / da
            v = (r - depths[0]) / dr
            k, q = math.floor(u), math.floor(v)
            if u < 0 or v < 0 or u > len(angles) - 1 or v > len(depths) - 1:  # @line L11
                row.append(0.0)
                continue
            k, q = min(k, len(angles) - 2), min(q, len(depths) - 2)
            a, b = u - k, v - q
            row.append((1 - a) * (1 - b) * polar[k][q] + a * (1 - b) * polar[k + 1][q]  # @line L12
                       + (1 - a) * b * polar[k][q + 1] + a * b * polar[k + 1][q + 1])
        out.append(row)
    return out


def b_mode(lines, dynamic_range_db, gain_db_per_mm=0.0, t0=0.0, fs=1.0, c=SOUND_SPEED):
    """Envelope, optional TGC and log compression of every line (the image before scan conversion)."""
    depths = sample_depths(len(lines[0]), t0, fs, c)
    env = []
    for line in lines:  # @line L1
        e = envelope(line)
        if gain_db_per_mm:
            e = tgc(e, depths, gain_db_per_mm)
        env.append(e)
    return log_compress(env, dynamic_range_db)


def simulate_sector_lines(angles, n, t0, fs, f0, sigma_t, scatterers, beam_width, atten_db_per_mm=0.0,
                          c=SOUND_SPEED):
    """RF lines of a sector scan with point scatterers given as (r, theta, amplitude).

    A crude beam model: line k sees a scatterer at angle theta with the weight
    exp(-((theta - angle_k) / beam_width)^2 / 2). The echo is a Gaussian pulse
    at the two-way time 2 r / c, times 10^(-atten_db_per_mm 2 r / 20).
    """
    lines = []
    for ang in angles:
        line = [0.0] * n
        for (r, th, amp) in scatterers:
            w = amp * math.exp(-0.5 * ((th - ang) / beam_width) ** 2) * 10 ** (-atten_db_per_mm * 2 * r / 20)
            tau = 2 * r / c
            for q in range(n):
                dt = t0 + q / fs - tau
                line[q] += w * math.exp(-dt * dt / (2 * sigma_t * sigma_t)) * math.cos(2 * math.pi * f0 * dt)
        lines.append(line)
    return lines
imgkit.py 322 lines
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small images and signals for the imaging and inverse problems pages.

Conventions:
- A signal is a list of numbers. An image is a list of rows, img[i][j], with
  row i from the top and column j from the left.
- An n x n image covers the square [-1, 1]^2. The center of pixel (i, j) is
  x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n, so y goes up.
- DFT: X_k = sum_j x_j exp(-2 pi i j k / n), unnormalized; the inverse has
  the factor 1 / n. Index k stands for frequency k for k < n / 2 and k - n
  otherwise. fftshift moves the zero frequency to position n // 2.
- Periodic convolution kernels are stored with their center at index 0
  (wrapped around), so a delta kernel gives the identity and no shift.
"""

import cmath
import math

# ------------------------------------------------------------------ images


def new_image(n1, n2, value=0.0):
    """An n1 x n2 image (n1 rows, n2 columns) filled with value."""
    return [[value] * n2 for _ in range(n1)]


def img_add(a, b):
    """The pixelwise sum a + b."""
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def img_scale(a, c):
    """The image c a."""
    return [[c * x for x in row] for row in a]


def img_dot(a, b):
    """<a, b> = sum conj(a_ij) b_ij."""
    return sum(x.conjugate() * y for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def img_norm(a):
    """The Euclidean (Frobenius) norm of an image."""
    return math.sqrt(sum(abs(x) ** 2 for row in a for x in row))


def flatten(img):
    """Row-major vector of an image."""
    return [x for row in img for x in row]


def unflatten(v, n1, n2):
    """The n1 x n2 image of a row-major vector."""
    return [list(v[i * n2:(i + 1) * n2]) for i in range(n1)]


# ------------------------------------------------------------------ DFT


def _is_pow2(n):
    return n > 0 and n & (n - 1) == 0


def _fft_pow2(x):
    """Iterative radix-2 FFT, unnormalized forward transform."""
    n = len(x)
    a = [complex(v) for v in x]
    j = 0
    for i in range(1, n):
        bit = n >> 1
        while j & bit:
            j ^= bit
            bit >>= 1
        j |= bit
        if i < j:
            a[i], a[j] = a[j], a[i]
    size = 2
    while size <= n:
        half = size // 2
        tw = [cmath.exp(-2j * math.pi * k / size) for k in range(half)]
        for start in range(0, n, size):
            for k in range(half):
                u = a[start + k]
                v = a[start + k + half] * tw[k]
                a[start + k] = u + v
                a[start + k + half] = u - v
        size *= 2
    return a


def dft(x):
    """X_k = sum_j x_j exp(-2 pi i j k / n). Radix-2 FFT when n is a power of 2."""
    n = len(x)
    if n == 0:
        return []
    if _is_pow2(n):
        return _fft_pow2(x)
    w = [cmath.exp(-2j * math.pi * t / n) for t in range(n)]
    return [sum(x[j] * w[(j * k) % n] for j in range(n)) for k in range(n)]


def idft(xf):
    """x_j = (1/n) sum_k X_k exp(2 pi i j k / n)."""
    n = len(xf)
    if n == 0:
        return []
    y = dft([complex(v).conjugate() for v in xf])
    return [v.conjugate() / n for v in y]


def _rows_then_cols(img, f):
    rows = [f(row) for row in img]
    cols = [f(list(col)) for col in zip(*rows)]
    return [list(r) for r in zip(*cols)]


def dft2(img):
    """2D DFT: X_kl = sum_jq x_jq exp(-2 pi i (j k / n1 + q l / n2))."""
    return _rows_then_cols(img, dft)


def idft2(img):
    """Inverse 2D DFT, with the factor 1 / (n1 n2)."""
    return _rows_then_cols(img, idft)


def _shift1(x, s):
    return list(x[s:]) + list(x[:s])


def fftshift(x):
    """Move the zero frequency to position n // 2 (1D, or both axes of an image)."""
    if x and isinstance(x[0], (list, tuple)):
        rows = [fftshift(r) for r in x]
        return _shift1(rows, (len(rows) + 1) // 2)
    return _shift1(x, (len(x) + 1) // 2)


def ifftshift(x):
    """The inverse of fftshift (1D, or both axes of an image)."""
    if x and isinstance(x[0], (list, tuple)):
        rows = [ifftshift(r) for r in x]
        return _shift1(rows, len(rows) // 2)
    return _shift1(x, len(x) // 2)


def circ_conv(x, h):
    """Periodic convolution y_i = sum_j h_j x_{(i - j) mod n}, kernel centered at index 0."""
    n = len(x)
    nz = [(j, hj) for j, hj in enumerate(h) if hj != 0]
    return [sum(hj * x[(i - j) % n] for j, hj in nz) for i in range(n)]


def circ_conv2(img, h):
    """Periodic 2D convolution with the kernel h centered at index (0, 0)."""
    n1, n2 = len(img), len(img[0])
    nz = [(p, q, h[p][q]) for p in range(len(h)) for q in range(len(h[0])) if h[p][q] != 0]
    out = new_image(n1, n2)
    for i in range(n1):
        for j in range(n2):
            out[i][j] = sum(v * img[(i - p) % n1][(j - q) % n2] for p, q, v in nz)
    return out


# ------------------------------------------------------------------ phantoms


def pixel_centers(n):
    """(xs, ys): xs[j] = -1 + (2 j + 1) / n and ys[i] = 1 - (2 i + 1) / n."""
    xs = [-1.0 + (2 * j + 1) / n for j in range(n)]
    ys = [1.0 - (2 * i + 1) / n for i in range(n)]
    return xs, ys


# Rows: rho, A, B, x0, y0, phi (degrees). A is the semi-axis along the
# direction phi (counterclockwise from the x axis), B the other semi-axis.
# Geometry and densities of Shepp and Logan (1974), as reproduced in Kak and
# Slaney, Principles of Computerized Tomographic Imaging, Table 3.1. The value
# at the center (0, 0) is 2 - 0.98 = 1.02.
SHEPP_LOGAN = [
    (2.0, 0.92, 0.69, 0.0, 0.0, 90.0),
    (-0.98, 0.874, 0.6624, 0.0, -0.0184, 90.0),
    (-0.02, 0.31, 0.11, 0.22, 0.0, 72.0),
    (-0.02, 0.41, 0.16, -0.22, 0.0, 108.0),
    (0.01, 0.25, 0.21, 0.0, 0.35, 90.0),
    (0.01, 0.046, 0.046, 0.0, 0.1, 0.0),
    (0.01, 0.046, 0.046, 0.0, -0.1, 0.0),
    (0.01, 0.046, 0.023, -0.08, -0.605, 0.0),
    (0.01, 0.023, 0.023, 0.0, -0.605, 0.0),
    (0.01, 0.046, 0.023, 0.06, -0.605, 90.0),
]

# The same ellipses with the gray levels of Toft (1996), which give more
# contrast. The value at the center is 1 - 0.8 = 0.2.
MODIFIED_SHEPP_LOGAN = [
    (rho, a, b, x0, y0, phi)
    for rho, (_, a, b, x0, y0, phi) in zip(
        (1.0, -0.8, -0.2, -0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1), SHEPP_LOGAN
    )
]


def ellipse_value(x, y, table):
    """The phantom value at the point (x, y): the sum of rho over the ellipses that hold it."""
    total = 0.0
    for rho, a, b, x0, y0, phi in table:
        c, s = math.cos(math.radians(phi)), math.sin(math.radians(phi))
        dx, dy = x - x0, y - y0
        u = dx * c + dy * s
        v = -dx * s + dy * c
        if (u / a) ** 2 + (v / b) ** 2 <= 1.0:
            total += rho
    return total


def ellipse_phantom(n, table):
    """The n x n image of an ellipse table, sampled at the pixel centers."""
    xs, ys = pixel_centers(n)
    return [[ellipse_value(x, y, table) for x in xs] for y in ys]


def disk_phantom(n, radius):
    """1 at pixel centers with x^2 + y^2 <= radius^2, 0 elsewhere."""
    xs, ys = pixel_centers(n)
    r2 = radius * radius
    return [[1.0 if x * x + y * y <= r2 else 0.0 for x in xs] for y in ys]


def spikes_1d(n, positions, amplitudes):
    """A signal of length n with the given amplitudes at the given positions."""
    out = [0.0] * n
    for p, a in zip(positions, amplitudes):
        out[p] += a
    return out


# ------------------------------------------------------------------ projector


def parallel_beam_matrix(n, angles, nbins):
    """Pixel-driven discrete Radon transform of an n x n image on [-1, 1]^2.

    Each pixel center (x, y) projects to s = x cos(theta) + y sin(theta). Its
    value times the pixel area over the bin width is split linearly between
    the two nearest bin centers. The bins cover [-sqrt(2), sqrt(2)]. Row
    a * nbins + b holds angle a and bin b; column i * n + j holds pixel (i, j).
    Returns the sparse rows, each a list of (column, weight) pairs.
    Pixel-driven projection has a ripple: with a bin width close to the pixel
    size, a disk projection is off by up to about 10 percent in some bins. A
    bin of about twice the pixel size (nbins = 23 for n = 32) keeps it near
    1 percent.
    """
    xs, ys = pixel_centers(n)
    smax = math.sqrt(2.0)
    width = 2.0 * smax / nbins
    scale = (2.0 / n) ** 2 / width
    rows = []
    for theta in angles:
        c, s = math.cos(theta), math.sin(theta)
        acc = [dict() for _ in range(nbins)]
        for i, y in enumerate(ys):
            for j, x in enumerate(xs):
                t = (x * c + y * s + smax) / width - 0.5
                b0 = math.floor(t)
                frac = t - b0
                col = i * n + j
                for b, w in ((b0, 1.0 - frac), (b0 + 1, frac)):
                    if 0 <= b < nbins and w > 0.0:
                        acc[b][col] = acc[b].get(col, 0.0) + w * scale
        rows.extend(sorted(d.items()) for d in acc)
    return rows


def sp_matvec(rows, x):
    """y = A x for sparse rows of (column, weight) pairs."""
    return [sum(w * x[c] for c, w in row) for row in rows]


def sp_rmatvec(rows, y, ncols):
    """x = A^H y for sparse rows of (column, weight) pairs and ncols columns."""
    out = [0.0] * ncols
    for row, yi in zip(rows, y):
        if yi == 0:
            continue
        for c, w in row:
            out[c] += w.conjugate() * yi
    return out


# ------------------------------------------------------------------ noise


def gauss_noise(rng, shape, sigma):
    """Independent N(0, sigma^2) values: a list for an int shape, an image for (n1, n2)."""
    if isinstance(shape, int):
        return [rng.gauss(0.0, sigma) for _ in range(shape)]
    n1, n2 = shape
    return [[rng.gauss(0.0, sigma) for _ in range(n2)] for _ in range(n1)]


def _poisson_small(rng, lam):
    """Knuth's product method, exact for a mean lam <= 30."""
    limit = math.exp(-lam)
    k, p = 0, rng.random()
    while p > limit:
        k += 1
        p *= rng.random()
    return k


def poisson_sample(rng, lam):
    """An exact Poisson(lam) sample: a sum of Knuth samples with means at most 30."""
    if lam < 0:
        raise ValueError("negative mean")
    total = 0
    while lam > 30.0:
        total += _poisson_small(rng, 30.0)
        lam -= 30.0
    if lam > 0.0:
        total += _poisson_small(rng, lam)
    return total
test_b_mode_image_formation.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/b-mode-image-formation/. The authors are listed in prov/P3DHGZ.jsonl.

import math
import random

from b_mode_image_formation import (analytic_signal, b_mode, envelope, log_compress, sample_depths, scan_convert,
                                    simulate_sector_lines)

N, FS, F0, SIGMA, T0 = 64, 40.0, 5.0, 0.1, 6.5
DEG = math.pi / 180
ANGLES = [(-20 + 2 * k) * DEG for k in range(21)]


def test_real_part_is_the_input() -> None:
    rng = random.Random(5501)
    for n in (64, 45):
        x = [rng.uniform(-1, 1) for _ in range(n)]
        a = analytic_signal(x)
        assert all(abs(v.real - xi) < 1e-12 for v, xi in zip(a, x))


def test_envelope_of_a_whole_number_of_cycles_is_constant() -> None:
    x = [1.5 * math.cos(2 * math.pi * 8 * q / N + 0.3) for q in range(N)]
    assert all(abs(e - 1.5) < 1e-12 for e in envelope(x))


def test_envelope_of_a_gaussian_pulse() -> None:
    x = [math.exp(-((q / FS - 0.8) ** 2) / (2 * SIGMA ** 2)) * math.cos(2 * math.pi * F0 * (q / FS - 0.8))
         for q in range(N)]
    g = [math.exp(-((q / FS - 0.8) ** 2) / (2 * SIGMA ** 2)) for q in range(N)]
    assert max(abs(a - b) for a, b in zip(envelope(x), g)) < 2e-3


def test_depth_axis_is_half_the_two_way_path() -> None:
    d = sample_depths(N, T0, FS)
    assert abs(d[0] - 1.54 * 6.5 / 2) < 1e-12
    assert abs(d[1] - d[0] - 1.54 / (2 * FS)) < 1e-12


def test_log_compression_levels() -> None:
    assert log_compress([[1.0, 0.1, 0.01, 0.001, 0.0]], 40) == [[255, 128, 0, 0, 0]]
    # gray levels depend only on ratios to the brightest value
    assert log_compress([[3.0, 0.3], [0.03, 0.0]], 60) == log_compress([[1.0, 0.1], [0.01, 0.0]], 60)


def test_scan_conversion_is_exact_for_bilinear_functions() -> None:
    depths = sample_depths(N, T0, FS)

    def f(r, th):
        return 2 + 0.5 * r + 3 * th + r * th

    polar = [[f(r, th) for r in depths] for th in ANGLES]
    xs = [-1.2, -0.37, 0.0, 0.41, 1.1]
    zs = [5.2, 5.55, 6.0]
    out = scan_convert(polar, ANGLES, depths, xs, zs)
    for i, z in enumerate(zs):
        for j, x in enumerate(xs):
            assert abs(out[i][j] - f(math.hypot(x, z), math.atan2(x, z))) < 1e-9


def test_pixels_outside_the_sector_are_zero() -> None:
    depths = sample_depths(N, T0, FS)
    polar = [[1.0] * N for _ in ANGLES]
    out = scan_convert(polar, ANGLES, depths, [-4.0, 0.0, 4.0], [1.0, 5.5, 9.0])
    assert out == [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]]


def test_point_scatterer_appears_at_its_place() -> None:
    lines = simulate_sector_lines(ANGLES, N, T0, FS, F0, SIGMA, [(5.6, 4 * DEG, 1.0)], 2 * DEG)
    img = b_mode(lines, 40, t0=T0, fs=FS)
    depths = sample_depths(N, T0, FS)
    xs = [round(-1.5 + 0.1 * k, 10) for k in range(31)]
    zs = [round(5.0 + 0.05 * k, 10) for k in range(25)]
    sc = scan_convert(img, ANGLES, depths, xs, zs)
    v, i, j = max((v, i, j) for i, row in enumerate(sc) for j, v in enumerate(row))
    assert (zs[i], xs[j]) == (5.6, 0.4)
    assert v > 240


def test_tgc_balances_attenuation() -> None:
    # 5 dB/mm one way is 10 dB per mm of depth on the two-way path
    lines = simulate_sector_lines(ANGLES, N, T0, FS, F0, SIGMA, [(5.3, 0.0, 1.0), (5.9, 0.0, 1.0)], 2 * DEG, 5.0)
    depths = sample_depths(N, T0, FS)
    q1 = min(range(N), key=lambda q: abs(depths[q] - 5.3))
    q2 = min(range(N), key=lambda q: abs(depths[q] - 5.9))
    raw = b_mode(lines, 40, 0.0, T0, FS)[10]
    fixed = b_mode(lines, 40, 10.0, T0, FS)[10]
    assert max(raw[q1 - 3:q1 + 4]) - max(raw[q2 - 3:q2 + 4]) > 30
    assert abs(max(fixed[q1 - 3:q1 + 4]) - max(fixed[q2 - 3:q2 + 4])) <= 1

History

Two-dimensional pulse-echo images of the body appeared in the 1950s, made with one transducer moved over the skin by a mechanical arm, and showed only bright echoes in black and white. Gray-scale display, with a log compression of the echo amplitude, came in the 1970s, together with real-time scanners that steer the beam electronically with arrays. Digital beamformers later moved the whole chain, envelope detection, compression and scan conversion, into software. The details of these steps are in textbooks such as Szabo (2014).

References

  1. Thomas L. Szabo, Diagnostic Ultrasound Imaging: Inside Out, 2nd edition, Academic Press, 2014, Chapter 10, Imaging systems and applications (signal processing chain, envelope detection, compression and scan conversion); Chapter 4, Attenuation (depth gain)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • at least three sources
  • a scene preset for the example