diff --git a/Gaussian2DFilter.cpp b/Gaussian2DFilter.cpp index 1a69fb0..26c58f5 100644 --- a/Gaussian2DFilter.cpp +++ b/Gaussian2DFilter.cpp @@ -248,10 +248,20 @@ void FastGaussian2DSIMD(float *data, std::size_t width, std::size_t height, // Entry point void FastGaussian2D(float *data, std::size_t width, std::size_t height, float sigma) { + if (!(sigma > 0.0f)) + return; + // Recursive coefficients (Eq 11b) are valid only for sigma >= 0.5 and + // inaccurate near that bound; direct convolution is cheap for such small + // kernels. + if (sigma < 1.0f) { + gaussian_internal::DirectGaussian2D(data, width, height, sigma); + return; + } #ifdef USE_HIGHWAY_SIMD - return gaussian_internal::FastGaussian2DSIMD(data, width, height, sigma); -#endif + gaussian_internal::FastGaussian2DSIMD(data, width, height, sigma); +#else gaussian_internal::FastGaussian2DScalar(data, width, height, sigma); +#endif } #endif diff --git a/Gaussian2DFilter.h b/Gaussian2DFilter.h index 11476b8..ecf4989 100644 --- a/Gaussian2DFilter.h +++ b/Gaussian2DFilter.h @@ -1,9 +1,11 @@ #pragma once +#include #include #include #include #include +#include void FastGaussian2D(float *data, std::size_t width, std::size_t height, float sigma); @@ -11,7 +13,7 @@ void FastGaussian2D(float *data, std::size_t width, std::size_t height, namespace gaussian_internal { // Eq 11b -template inline float q(F sigma) { +template inline F q(F sigma) { assert(sigma > F(0.0)); // Note: This function, as given in the paper, is not continuous at sigma = @@ -58,24 +60,20 @@ template inline F B(std::array bp) { template inline void ForwardFilter(F *data, std::size_t size, F B, std::array bp, std::size_t stride = Stride) { - const auto s = Stride > 0 ? Stride : stride; - F *const pend = data + size * s; - F *p = data; if (size < 1) return; - F cur = *p; + const auto s = Stride > 0 ? Stride : stride; + F cur = data[0]; // Replicate the 3 pixels outside the border. F prev1 = cur; F prev2 = cur; F prev3 = cur; - p += s; - for (; p < pend; p += s) { + for (std::size_t k = 1; k < size; ++k) { prev3 = prev2; prev2 = prev1; prev1 = cur; - cur = *p; - cur = B * cur + bp[0] * prev1 + bp[1] * prev2 + bp[2] * prev3; - *p = cur; + cur = B * data[k * s] + bp[0] * prev1 + bp[1] * prev2 + bp[2] * prev3; + data[k * s] = cur; } } @@ -83,24 +81,20 @@ inline void ForwardFilter(F *data, std::size_t size, F B, std::array bp, template inline void BackwardFilter(F *data, std::size_t size, F B, std::array bp, std::size_t stride = Stride) { - const auto s = Stride > 0 ? Stride : stride; - F *const prend = data - 1; - F *p = data + (size - 1) * s; if (size < 1) return; - F cur = *p; + const auto s = Stride > 0 ? Stride : stride; + F cur = data[(size - 1) * s]; // Replicate the 3 pixels outside of the border. F next1 = cur; F next2 = cur; F next3 = cur; - p -= s; - for (; p > prend; p -= s) { + for (std::size_t k = size - 1; k-- > 0;) { next3 = next2; next2 = next1; next1 = cur; - cur = *p; - cur = B * cur + bp[0] * next1 + bp[1] * next2 + bp[2] * next3; - *p = cur; + cur = B * data[k * s] + bp[0] * next1 + bp[1] * next2 + bp[2] * next3; + data[k * s] = cur; } } @@ -123,6 +117,46 @@ void FastGaussian2DScalar(F *data, std::size_t width, std::size_t height, } } +// Separable convolution with a sampled Gaussian kernel truncated at 3 sigma, +// with replicated boundaries. +template +void DirectGaussian2D(F *data, std::size_t width, std::size_t height, + F sigma) { + if (width == 0 || height == 0) + return; + const auto radius = std::max( + 1, static_cast(std::ceil(F(3) * sigma))); + std::vector kernel(static_cast(2 * radius + 1)); + F sum = 0; + for (std::ptrdiff_t k = -radius; k <= radius; ++k) { + const F w = std::exp(-F(k * k) / (F(2) * sigma * sigma)); + kernel[static_cast(k + radius)] = w; + sum += w; + } + for (auto &w : kernel) + w /= sum; + + std::vector buf(std::max(width, height)); + const auto convolve = [&](std::size_t size, std::size_t stride, F *line) { + for (std::size_t k = 0; k < size; ++k) + buf[k] = line[k * stride]; + const auto last = static_cast(size) - 1; + for (std::ptrdiff_t k = 0; k <= last; ++k) { + F acc = 0; + for (std::ptrdiff_t m = -radius; m <= radius; ++m) { + const auto idx = std::clamp(k + m, 0, last); + acc += kernel[static_cast(m + radius)] * + buf[static_cast(idx)]; + } + line[static_cast(k) * stride] = acc; + } + }; + for (std::size_t j = 0; j < height; ++j) + convolve(width, 1, data + j * width); + for (std::size_t i = 0; i < width; ++i) + convolve(height, width, data + i); +} + // For unit test access void FastGaussian2DSIMD(float *data, std::size_t width, std::size_t height, float sigma); diff --git a/SimObjectiveTurret.h b/SimObjectiveTurret.h index d32c1b6..6ae0404 100644 --- a/SimObjectiveTurret.h +++ b/SimObjectiveTurret.h @@ -60,7 +60,7 @@ class SimObjectiveTurret : public CStateDeviceBase { // ----- CPropertyAction *pAct = new CPropertyAction(this, &SimObjectiveTurret::OnState); - ret = CreateIntegerProperty(MM::g_Keyword_State, 0, false, pAct); + ret = CreateIntegerProperty(MM::g_Keyword_State, 1, false, pAct); if (ret != DEVICE_OK) return ret; @@ -122,5 +122,5 @@ class SimObjectiveTurret : public CStateDeviceBase { std::string name_; SimHub *hub_ = nullptr; // Read by the camera thread via the hub - std::atomic state_{0}; + std::atomic state_{1}; }; diff --git a/Specimen.h b/Specimen.h index c767665..7d8bea8 100644 --- a/Specimen.h +++ b/Specimen.h @@ -12,14 +12,19 @@ #include constexpr double PI = 3.1415926535897; +constexpr float EMISSION_WAVELENGTH_UM = 0.52f; // GFP-like template inline F GaussianSigmaForDefocus(F defocus_um, F numericalAperture, - F refractiveIndex) { - const auto radius = - numericalAperture * std::fabs(defocus_um) / refractiveIndex; - // Apply an (arbitrary) multiplier and minimum. - return F(0.5) * radius + F(1.0); + F refractiveIndex, F wavelength_um) { + // Gaussian approximation of the in-focus widefield PSF (Zhang et al. + // 2007, Appl Opt 46:1819): sigma = 0.21 lambda / NA. + const F sigma0 = F(0.21) * wavelength_um / numericalAperture; + // Geometric defocus blur radius, with an (arbitrary) scaling to sigma. + const F sigmaDefocus = + F(0.5) * numericalAperture * std::fabs(defocus_um) / refractiveIndex; + // Convolved Gaussians add in variance. + return std::sqrt(sigma0 * sigma0 + sigmaDefocus * sigmaDefocus); } // Renders the expected (noise-free) signal of a specimen into signal (width * @@ -33,8 +38,14 @@ void RenderSpecimenImage(float *signal, double x_um, double y_um, double z_um, std::size_t width, std::size_t height, double um_per_px, double na, double intensity, ContentFn &&drawContent) { - BLImage img(static_cast(width), static_cast(height), - BL_FORMAT_XRGB32); + const std::size_t nPixels = width * height; + + BLImage img; + if (img.create(static_cast(width), static_cast(height), + BL_FORMAT_XRGB32) != BL_SUCCESS) { + std::fill(signal, signal + nPixels, 0.0f); + return; + } BLContext ctx(img); ctx.clearAll(); @@ -51,8 +62,6 @@ void RenderSpecimenImage(float *signal, double x_um, double y_um, double z_um, ctx.end(); - const std::size_t nPixels = width * height; - BLImageData data; BLResult status = img.getData(&data); if (status != BL_SUCCESS) { @@ -60,22 +69,20 @@ void RenderSpecimenImage(float *signal, double x_um, double y_um, double z_um, return; // Give up (shouldn't happen). } - const auto *pix = static_cast(data.pixelData); - - // Stride is the stride of scanlines; negative stride means bottom-up. - const std::intptr_t stride = data.stride / sizeof(std::uint32_t); - const std::intptr_t start = stride >= 0 ? 0 : (height - 1) * (-stride); - for (std::intptr_t j = 0; j < std::intptr_t(height); ++j) { - for (std::intptr_t i = 0; i < std::intptr_t(width); ++i) { - const auto p = pix[start + i + j * stride]; + // pixelData points to the top-left pixel; stride (bytes) may be negative. + const auto *base = static_cast(data.pixelData); + for (std::size_t j = 0; j < height; ++j) { + const auto *row = reinterpret_cast( + base + std::intptr_t(j) * data.stride); + for (std::size_t i = 0; i < width; ++i) { // Green sample - signal[i + j * width] = static_cast((p >> 8) & 0xff); + signal[i + j * width] = static_cast((row[i] >> 8) & 0xff); } } // Defocus - const auto sigmaUm = - GaussianSigmaForDefocus(float(z_um), float(na), 1.33f); + const auto sigmaUm = GaussianSigmaForDefocus(float(z_um), float(na), 1.33f, + EMISSION_WAVELENGTH_UM); const auto sigmaPixels = sigmaUm / float(um_per_px); FastGaussian2D(signal, width, height, sigmaPixels); @@ -91,6 +98,9 @@ class FilamentsSpecimen { std::vector filaments_; + static constexpr double filamentWidthUm_ = 0.025; // microtubule + static constexpr double relativeBrightness_ = 0.1; // arbitrary + public: explicit FilamentsSpecimen() { using std::cos; @@ -114,8 +124,16 @@ class FilamentsSpecimen { std::size_t width, std::size_t height, double um_per_px, double na, double intensity) const { const auto &filaments = filaments_; + // Blend2D renders 8-bit, so a sub-pixel stroke would quantize away. + // Draw at least 1 px wide and scale intensity by the width ratio, + // preserving signal per unit length (antialiasing gives the pixel + // coverage). + const double strokeWidth = std::max(filamentWidthUm_, um_per_px); + const double filamentIntensity = + intensity * relativeBrightness_ * filamentWidthUm_ / strokeWidth; RenderSpecimenImage(signal, x_um, y_um, z_um, width, height, um_per_px, - na, intensity, [&](BLContext &ctx) { + na, filamentIntensity, [&](BLContext &ctx) { + ctx.setStrokeWidth(strokeWidth); for (const Filament &f : filaments) { BLPath path; path.moveTo(f.x0, f.y0); diff --git a/test_SimulatedCamera.cpp b/test_SimulatedCamera.cpp index 184386a..9b2e538 100644 --- a/test_SimulatedCamera.cpp +++ b/test_SimulatedCamera.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -248,6 +249,70 @@ TEST_CASE("FastGaussian2D") { } } +TEST_CASE("DirectGaussian2D") { + using Catch::Matchers::WithinAbs; + constexpr float sigma = 0.7f; + + SECTION("impulse") { + std::vector data(7 * 7); + data[7 * 3 + 3] = 1.0f; + gaussian_internal::DirectGaussian2D(data.data(), 7, 7, sigma); + + CHECK_THAT(std::accumulate(data.begin(), data.end(), 0.0), + WithinAbs(1.0, 1e-5)); + for (std::size_t j = 0; j < 7; ++j) { + for (std::size_t i = 0; i < 7; ++i) { + CAPTURE(j, i); + CHECK_THAT(data[j * 7 + i], + WithinAbs(data[j * 7 + 7 - i - 1], 1e-7)); + CHECK_THAT(data[j * 7 + i], + WithinAbs(data[(7 - j - 1) * 7 + i], 1e-7)); + CHECK_THAT(data[j * 7 + i], WithinAbs(data[i * 7 + j], 1e-7)); + } + } + + const int radius = int(std::ceil(3.0f * sigma)); + float wsum = 0.0f; + for (int k = -radius; k <= radius; ++k) { + wsum += std::exp(-float(k * k) / (2.0f * sigma * sigma)); + } + const float w0 = 1.0f / wsum; + CHECK_THAT(data[7 * 3 + 3], WithinAbs(w0 * w0, 1e-6)); + } + + SECTION("constant") { + std::vector data(7 * 5, 3.0f); + gaussian_internal::DirectGaussian2D(data.data(), 7, 5, sigma); + for (float v : data) { + CHECK_THAT(v, WithinAbs(3.0f, 1e-5)); + } + } +} + +TEST_CASE("FastGaussian2D-small-sigma") { + using Catch::Matchers::WithinAbs; + const float sigma = GENERATE(0.1f, 0.3f, 0.7f); + CAPTURE(sigma); + + SECTION("impulse") { + std::vector data(7 * 7); + data[7 * 3 + 3] = 1.0f; + FastGaussian2D(data.data(), 7, 7, sigma); + CHECK(std::all_of(data.begin(), data.end(), + [](float v) { return v >= 0.0f; })); + CHECK_THAT(std::accumulate(data.begin(), data.end(), 0.0), + WithinAbs(1.0, 1e-5)); + } + + SECTION("constant") { + std::vector data(7 * 5, 3.0f); + FastGaussian2D(data.data(), 7, 5, sigma); + for (float v : data) { + CHECK_THAT(v, WithinAbs(3.0f, 1e-5)); + } + } +} + TEST_CASE("FastPoisson-mean-variance") { using Catch::Matchers::WithinAbs; rnd::mt19937 rng(12345); @@ -337,6 +402,25 @@ TEST_CASE("ReadOut-clamp") { [](std::uint16_t v) { return v == 65535; })); } +TEST_CASE("GaussianSigmaForDefocus") { + using Catch::Matchers::WithinRel; + const float na = GENERATE(0.3f, 0.75f, 1.4f); + CAPTURE(na); + + SECTION("in focus") { + CHECK_THAT(GaussianSigmaForDefocus(0.0f, na, 1.33f, 0.52f), + WithinRel(0.21f * 0.52f / na, 1e-5f)); + } + + SECTION("large defocus") { + for (const float dz : {-200.0f, 200.0f}) { + CAPTURE(dz); + CHECK_THAT(GaussianSigmaForDefocus(dz, na, 1.33f, 0.52f), + WithinRel(0.5f * na * std::fabs(dz) / 1.33f, 1e-3f)); + } + } +} + TEST_CASE("Specimen-Draw-deterministic") { const std::size_t width = 64, height = 48; std::vector a(width * height, -1.0f);