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
- Model
- Real RAM
- Properties
- deterministicexactnot linear in dataiterative
- Evidence
- Proof sketchCode in 1 languages
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 is , 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 real RF lines , one for each beam angle of a sector scan, sampled at the times . The parameters are the speed of sound , a dynamic range in dB, an optional gain in dB per mm and an output grid of pixels . The output is a gray level in for every pixel; pixels outside the sector are .
The algorithm
B-MODE(x_1 … x_K, D, G) ▷ returns gray levels per line and sample- 1
for each line k do - 2
X ← DFT(x_k) - 3
a ← IDFT(h · X) ▷ h: 1 at 0 and n/2, 2 for positive, 0 for negative frequencies - 4
e_k ← |a| ▷ envelope - 5
e_k[q] ← e_k[q] · 10^{G z_q / 20} ▷ time gain compensation, z_q = c (t_0 + q/f_s)/2 - 6
e_max ← max over all k, q of e_k[q] - 7
d ← 20 log10(e_k[q] / e_max) ▷ for every k, q - 8
d ← max(-D, d) ▷ clip to the dynamic range - 9
ℓ_k[q] ← ⌊255 (d + D)/D + 1/2⌋ SCAN-CONVERT(ℓ, θ_1 … θ_K, z_0 … z_{n-1}, pixels)- 10
for each pixel (x, z): r ← √(x² + z²), θ ← atan2(x, z) - 11
if (θ, r) is outside the grid of angles and depths then the pixel is 0 - 12
else 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 dB, the envelope values give dB, the clip of L8 gives , and L9 gives the gray levels . Every echo more than 40 dB below the brightest one is black.
Depth axis. With us, MHz, and mm/us, the samples cover the depths from mm to mm, in steps of mm.
A point scatterer. The tests simulate 21 lines from to degrees in steps of 2 degrees, a Gaussian pulse at MHz with 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 mm. On a grid with steps of 0.1 mm in and 0.05 mm in , the brightest pixel of the converted image is at , 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 dB, which is 38 gray levels at dB. A gain of 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 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 dB to 0. Scan conversion is a convex combination of the four nearest samples and is exact for functions of the form . The gain of L5 with removes an attenuation of 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 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 , its DFT is , and the inverse has the factor . Indices of are taken modulo . The weights of line L3 are , for , when is even, and for the other .
Theorem 1 (the real part of the analytic signal is the line). Let (lines L2 and L3). Then for every , so the imaginary part is a discrete Hilbert transform of and .
Proof. For any complex vector with DFT , the DFT of is , so the DFT of is . Take . Since is real, , and is real, so . Check for every : for it is ; for even and it is ; for it is ; for it is . So the DFT of is , and .
Theorem 2 (the envelope of a tone). Let with and an integer . Then and the envelope of line L4 is the constant .
Proof. , so is at , at , and elsewhere. Line L3 doubles the first and removes the second, because . The inverse DFT of at is the stated .
For a pulse with a smooth envelope whose spectrum does not reach the zero frequency, the envelope is close to , 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 for a Gaussian envelope with us at MHz, MHz and .
Theorem 3 (time gain compensation). Suppose the echo of a scatterer at depth has the amplitude , with an attenuation of dB per mm one way. Line L5 with the gain dB per mm gives , independent of .
Proof. when .
In this model the two echoes of the test, at 5.3 and 5.9 mm with dB/mm, differ by 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 be the largest envelope value (line L6) and the dynamic range in dB. Line L9 maps to the gray level with . Then:
- depends only on the ratio , so scaling all envelopes by gives the same image;
- is nondecreasing in , , and for every , including ;
- every level lies in .
Proof. (1) Scaling by scales by too. (2) The logarithm, the clipping of line L8, the affine map and the rounding are nondecreasing. At , and . For , and . (3) , so , and rounding keeps it in that range.
For example, with dB, the ratios give dB and the levels , and .
Theorem 5 (scan conversion). Let the polar samples be 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 exactly when has the form . Pixels outside the sector get (line L11).
Proof. The weights , , and with are nonnegative and sum to . Bilinear interpolation on one cell reproduces the functions , , and : for , the result is because , and the same holds for ; for the weights factor into a product of the two one-dimensional cases. By linearity it reproduces their combinations.
Theorem 6 (cost). For lines of samples and output pixels, the envelopes cost with a radix-2 FFT (the helper uses it when is a power of 2, and an DFT otherwise), lines L5 to L9 cost , and lines L10 to L12 cost .
Proof. Each step is a fixed number of operations per sample or per pixel, apart from the DFT pair of each line.
Complexity
In the real-RAM model, the envelope of a line of samples costs with a radix-2 FFT, so all lines cost . Lines L5 to L9 cost , and scan conversion costs per pixel, in total. The extra space is for one line. A real scanner computes the envelope with an IQ demodulator or a short Hilbert filter, at 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 and the gain curve are display choices. Values such as dB are tuned for the eye and the tissue, not derived.
- The depth resolution is set by the pulse length, about for a pulse of duration ; the lateral resolution is set by the beamformer.
Variants and improvements
- IQ demodulation. Mix the RF line with 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 and , 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 , not .
- Rectification in place of the envelope. Taking 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 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.
# 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag P3DHGZ Edit this page History Report an error Markdown