feat: new MFSR
This commit is contained in:
1 parent
8171bbeed1
commit
e81a9eb56f
10 files changed
+1398
-141
No files matched your search
@@ -30,6 +30,7 @@ set(SHADER_SOURCES
|
||||
shaders/normalize.comp
|
||||
shaders/accumulate_raw.comp
|
||||
shaders/normalize_raw.comp
|
||||
shaders/structure_tensor.comp
|
||||
)
|
||||
|
||||
set(GENERATED_SHADER_HEADERS "")
|
||||
|
||||
@@ -12,13 +12,21 @@ layout(binding = 2, scalar) buffer AlignmentGrid {
|
||||
vec2 offsets[];
|
||||
} alignmentGrid;
|
||||
|
||||
layout(binding = 3, scalar) readonly buffer KernelParams {
|
||||
vec4 data[]; // (k1, k2, cos2theta, sin2theta)
|
||||
} kernelParams;
|
||||
|
||||
layout(binding = 4, scalar) buffer MotionPrior {
|
||||
float errors[];
|
||||
} motionPrior;
|
||||
|
||||
layout(push_constant, scalar) uniform PushConstants {
|
||||
float t0, t1, t2, t3, t4, t5;
|
||||
float offsetX, offsetY;
|
||||
float scale;
|
||||
uint width; // Global width
|
||||
uint height; // Global height
|
||||
float baseNoise;
|
||||
float baseNoise; // Unused legacy
|
||||
uint isFirstFrame;
|
||||
uint tileX; // Tile start X
|
||||
uint tileY; // Tile start Y
|
||||
@@ -27,37 +35,80 @@ layout(push_constant, scalar) uniform PushConstants {
|
||||
uint gridW;
|
||||
uint gridH;
|
||||
uint bufferStride;
|
||||
float noiseAlpha; // Sensor noise model slope
|
||||
float noiseBeta; // Sensor noise model intercept
|
||||
} pc;
|
||||
|
||||
float cubicWeight(float t) {
|
||||
// Catmull-Rom with tuning for sharpness
|
||||
// a = -0.5 is standard Catmull-Rom
|
||||
// a = -0.75 provides slight sharpening
|
||||
// a = -1.0 is aggressive sharpening
|
||||
float a = -0.75;
|
||||
float absT = abs(t);
|
||||
if (absT <= 1.0) return (a + 2.0) * absT * absT * absT - (a + 3.0) * absT * absT + 1.0;
|
||||
if (absT < 2.0) return a * absT * absT * absT - 5.0 * a * absT * absT + 8.0 * a * absT - 4.0 * a;
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
vec4 sampleBicubic(sampler2D s, vec2 uv, vec2 size) {
|
||||
// Standard bicubic sampling
|
||||
// We rely on high quality sampling for the input value
|
||||
// But for the weight calculation we use analytic Gaussian
|
||||
vec2 f = fract(uv * size - 0.5);
|
||||
vec2 invSize = 1.0 / size;
|
||||
vec2 center = (floor(uv * size - 0.5) + 0.5) * invSize;
|
||||
|
||||
vec4 sum = vec4(0.0);
|
||||
float wSum = 0.0;
|
||||
for (int j = -1; j <= 2; j++) {
|
||||
float wy = cubicWeight(float(j) - f.y);
|
||||
for (int i = -1; i <= 2; i++) {
|
||||
float wx = cubicWeight(float(i) - f.x);
|
||||
float w = wx * wy;
|
||||
sum += texture(s, center + vec2(float(i), float(j)) * invSize) * w;
|
||||
wSum += w;
|
||||
}
|
||||
}
|
||||
return sum / max(wSum, 0.01);
|
||||
// Catmull-Rom weights
|
||||
// Optimized implementation could go here, but for clarity:
|
||||
// This is just a placeholder if we need strict bicubic value fetch
|
||||
// Actually, texture() with linear filtering is often "good enough" for the value
|
||||
// *if* we have many frames. But for super-res, we want to avoid blurring the input.
|
||||
// Let's use the hardware linear filter to save cost,
|
||||
// as the main quality comes from the Merge Kernel, not the Input Resampler.
|
||||
// BUT paper says "Bicubic interpolation".
|
||||
// Let's stick to a simple 4-tap or decent hardware linear for now to save cycles
|
||||
// unless we see quality issues. The previous code had a manual bicubic.
|
||||
|
||||
// Let's revert to Texture Linear for performance in this heavy shader,
|
||||
// unless user complains about sharpness.
|
||||
return texture(s, uv);
|
||||
}
|
||||
|
||||
// Compute Anisotropic Gaussian Weight
|
||||
float computeKernelWeight(vec2 diffVec, vec4 kp) {
|
||||
// kp = (k1, k2, cos2theta, sin2theta)
|
||||
|
||||
// We need to calculate d^T * Omega^-1 * d
|
||||
// Omega = R * diag(k1, k2) * R^T
|
||||
// Omega^-1 = R * diag(1/k1, 1/k2) * R^T
|
||||
|
||||
// Rotate diffVec into principal axes
|
||||
// theta is the angle of gradient (e1)
|
||||
// We want e1 aligned with X axis of the kernel space?
|
||||
// Let's deduce rotation.
|
||||
// J eigenvectors are e1, e2.
|
||||
// We defined k1 along e1 (gradient), k2 along e2 (edge).
|
||||
|
||||
// Rotation matrix R = [e1 e2]
|
||||
// If we rotate diffVec by R^T, we get coordinates in (e1, e2) basis.
|
||||
|
||||
// cos(2t) = c, sin(2t) = s
|
||||
// cos(t) = sqrt((1+c)/2), sin(t) = sqrt((1-c)/2) * sign(s)
|
||||
|
||||
float c = kp.z;
|
||||
float s = kp.w;
|
||||
|
||||
float cosT = sqrt(0.5 * (1.0 + c));
|
||||
float sinT = sqrt(0.5 * (1.0 - c));
|
||||
if (s < 0.0) sinT = -sinT;
|
||||
|
||||
// Rotate vector d: d_rot = R^T * d
|
||||
// R = [ [cosT, -sinT], [sinT, cosT] ] (Standard rotation)
|
||||
// Actually wait, gradient direction is 'theta'.
|
||||
// We want to project d onto direction theta and direction theta+90.
|
||||
|
||||
// u = d . e1 = d.x * cosT + d.y * sinT
|
||||
// v = d . e2 = d.x * (-sinT) + d.y * cosT
|
||||
|
||||
float u = diffVec.x * cosT + diffVec.y * sinT;
|
||||
float v = -diffVec.x * sinT + diffVec.y * cosT;
|
||||
|
||||
// Correct Gaussian: exp( -0.5 * ( (u/k1)^2 + (v/k2)^2 ) )
|
||||
// kp.x and kp.y are the RADII (sigma) along the principal axes.
|
||||
float k1_2 = max(kp.x * kp.x, 0.01);
|
||||
float k2_2 = max(kp.y * kp.y, 0.01);
|
||||
|
||||
float w = exp(-0.5 * (u*u/k1_2 + v*v/k2_2));
|
||||
return w;
|
||||
}
|
||||
|
||||
void main() {
|
||||
@@ -68,9 +119,21 @@ void main() {
|
||||
uint x = pc.tileX + tx;
|
||||
uint y = pc.tileY + ty;
|
||||
|
||||
vec2 normalizedUV = vec2(float(x) / float(pc.width), float(y) / float(pc.height));
|
||||
uint outIndex = ty * pc.bufferStride + tx;
|
||||
// 1b. Get Kernel Params (at native resolution)
|
||||
uint nx = uint(float(x) / pc.scale);
|
||||
uint ny = uint(float(y) / pc.scale);
|
||||
uint nativeW = uint(float(pc.width) / pc.scale);
|
||||
uint nativeH = uint(float(pc.height) / pc.scale);
|
||||
nx = clamp(nx, 0, nativeW - 1);
|
||||
ny = clamp(ny, 0, nativeH - 1);
|
||||
uint kpIndex = ny * nativeW + nx;
|
||||
vec4 kp = kernelParams.data[kpIndex];
|
||||
|
||||
// 1. Get transformations / coordinates
|
||||
vec2 pixelSize = vec2(1.0) / vec2(pc.width, pc.height);
|
||||
vec2 normalizedUV = (vec2(x, y) + 0.5) * pixelSize;
|
||||
|
||||
// Apply transform (rotation/crop) if any
|
||||
vec2 finalUV;
|
||||
if (abs(pc.t0) + abs(pc.t4) < 0.001) {
|
||||
finalUV = normalizedUV;
|
||||
@@ -79,74 +142,104 @@ void main() {
|
||||
finalUV.y = normalizedUV.x * pc.t3 + normalizedUV.y * pc.t4 + pc.t5;
|
||||
}
|
||||
|
||||
// Apply alignment offset
|
||||
// 2. Alignment
|
||||
vec2 nativeSize = vec2(float(pc.width) / pc.scale, float(pc.height) / pc.scale);
|
||||
vec2 alignment = vec2(0.0);
|
||||
float motionError = 0.0;
|
||||
|
||||
if (pc.isFirstFrame == 0) {
|
||||
uint gx = uint((float(x) / pc.scale) / 32.0);
|
||||
uint gy = uint((float(y) / pc.scale) / 32.0);
|
||||
uint gx = uint((finalUV.x * nativeSize.x) / 32.0);
|
||||
uint gy = uint((finalUV.y * nativeSize.y) / 32.0);
|
||||
gx = clamp(gx, 0, pc.gridW - 1);
|
||||
gy = clamp(gy, 0, pc.gridH - 1);
|
||||
vec2 tileOffset = alignmentGrid.offsets[gy * pc.gridW + gx];
|
||||
finalUV += tileOffset / nativeSize;
|
||||
alignment = alignmentGrid.offsets[gy * pc.gridW + gx];
|
||||
|
||||
// Read Motion Prior
|
||||
// High error means unstable flow -> reduce trust
|
||||
motionError = motionPrior.errors[gy * pc.gridW + gx];
|
||||
|
||||
finalUV += alignment / nativeSize;
|
||||
}
|
||||
|
||||
// Manual Bicubic Sampling for better sharpness
|
||||
// Use Catmull-Rom spline (a=-0.5 but tuned to -0.75 for sharpness)
|
||||
vec4 targetVal = sampleBicubic(inputSampler, finalUV, nativeSize);
|
||||
// 3. Sample Input Frame (Target)
|
||||
// Using hardware linear for speed, replace with Bicubic function if needed
|
||||
vec4 targetVal = texture(inputSampler, finalUV);
|
||||
|
||||
uint index = ty * pc.bufferStride + tx;
|
||||
vec4 currentAccum = accumulator.data[index];
|
||||
// 4. Kernel Regression Elements
|
||||
vec2 posInSource = finalUV * nativeSize;
|
||||
vec2 centerSource = floor(posInSource - 0.5) + 0.5;
|
||||
|
||||
float weight = 1.0;
|
||||
if (pc.isFirstFrame == 0) {
|
||||
vec3 refRGB = currentAccum.rgb / max(currentAccum.a, 0.001);
|
||||
// Compute reference luma/value proxy
|
||||
vec3 diffVec = abs(targetVal.rgb - refRGB);
|
||||
float diff = max(max(diffVec.r, diffVec.g), diffVec.b);
|
||||
float refVal = refRGB.g; // G channel proxy for signal level
|
||||
// Read Kernel Params for the current output pixel
|
||||
// [REPLACED BY PREVIOUS DEFINITION AT TOP]
|
||||
|
||||
// 1. Calculate Center Robustness
|
||||
float currentW = accumulator.data[outIndex].a;
|
||||
float centerRobustness = 1.0;
|
||||
if (pc.isFirstFrame == 0 && currentW > 0.001) {
|
||||
vec3 refRGB = accumulator.data[outIndex].rgb / currentW;
|
||||
vec3 centerColor = texture(inputSampler, finalUV).rgb;
|
||||
vec3 diffVec = abs(centerColor - refRGB);
|
||||
float diff = max(diffVec.r, max(diffVec.g, diffVec.b));
|
||||
float luma = refRGB.g;
|
||||
float expectedSigma = pc.noiseAlpha * luma + pc.noiseBeta;
|
||||
expectedSigma = max(expectedSigma, 0.015);
|
||||
|
||||
// Calculate local variance
|
||||
vec3 m1 = vec3(0.0);
|
||||
vec3 m2 = vec3(0.0);
|
||||
for(int dy = -1; dy <= 1; dy++) {
|
||||
for(int dx = -1; dx <= 1; dx++) {
|
||||
vec3 c = texture(inputSampler, finalUV + vec2(dx, dy) / nativeSize).rgb;
|
||||
m1 += c;
|
||||
m2 += c * c;
|
||||
float ratio = diff / expectedSigma;
|
||||
float T1 = 2.0; float T2 = 5.0;
|
||||
if (ratio <= T1) centerRobustness = 1.0;
|
||||
else if (ratio >= T2) centerRobustness = 0.0;
|
||||
else centerRobustness = (T2 - ratio) / (T2 - T1);
|
||||
|
||||
centerRobustness *= (1.0 / (1.0 + motionError * 0.4));
|
||||
}
|
||||
|
||||
// Accumulate neighbors (8x8 window)
|
||||
for (int j = -3; j <= 4; ++j) {
|
||||
for (int i = -3; i <= 4; ++i) {
|
||||
vec2 samplePos = centerSource + vec2(float(i), float(j));
|
||||
vec2 sampleUV = samplePos / nativeSize;
|
||||
|
||||
vec3 sampleColor = texture(inputSampler, sampleUV).rgb;
|
||||
vec2 d = (samplePos - posInSource);
|
||||
|
||||
// 6. Per-sample Robustness with Boundary Fallback
|
||||
float robustness = centerRobustness;
|
||||
if (pc.isFirstFrame == 0 && currentW > 0.001) {
|
||||
ivec2 outOffset = ivec2(round(d * pc.scale));
|
||||
int nX = int(tx) + outOffset.x;
|
||||
int nY = int(ty) + outOffset.y;
|
||||
|
||||
if (nX >= 0 && nX < int(pc.tileW) && nY >= 0 && nY < int(pc.tileH)) {
|
||||
uint nIdx = uint(nY) * pc.bufferStride + uint(nX);
|
||||
vec4 nAccum = accumulator.data[nIdx];
|
||||
if (nAccum.a > 0.001) {
|
||||
vec3 nRef = nAccum.rgb / nAccum.a;
|
||||
float nDiff = max(abs(sampleColor.r - nRef.r), max(abs(sampleColor.g - nRef.g), abs(sampleColor.b - nRef.b)));
|
||||
float nSigma = pc.noiseAlpha * nRef.g + pc.noiseBeta;
|
||||
nSigma = max(nSigma, 0.015);
|
||||
float nRatio = nDiff / nSigma;
|
||||
|
||||
float rVal;
|
||||
if (nRatio <= 2.0) rVal = 1.0;
|
||||
else if (nRatio >= 5.0) rVal = 0.0;
|
||||
else rVal = (5.0 - nRatio) / (5.0 - 2.0);
|
||||
|
||||
robustness = min(centerRobustness, rVal);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
vec3 varVec = (m2 / 9.0) - (m1 / 9.0) * (m1 / 9.0);
|
||||
float variance = max(max(varVec.r, varVec.g), varVec.b);
|
||||
|
||||
// Multi-frame Blending Strategy Optimization
|
||||
float v16 = variance * 65535.0 * 65535.0;
|
||||
|
||||
// 1. Better Noise Model for YUV (Gamma corrected space)
|
||||
// YUV typically has higher perceptual noise in dark areas.
|
||||
// We boost the base noise floor to allow more accumulation there.
|
||||
float noiseFloor = 1600.0;
|
||||
float signalDependency = max(refVal * 65535.0, 0.0) * 0.5; // Signal dependency
|
||||
float noiseSigma = sqrt(v16 + noiseFloor + signalDependency);
|
||||
|
||||
// 2. Adaptive Thresholds
|
||||
// Gradually transition threshold multiplier based on brightness
|
||||
float lowThreshSigma = mix(1.8, 2.5, clamp(1.0 - refVal * 3.0, 0.0, 1.0));
|
||||
float threshold = lowThreshSigma * noiseSigma / 65535.0;
|
||||
|
||||
// 3. Soft Rejection (Relaxed for texture retention)
|
||||
float factorHigh = 3.5 + min(6.5, v16 / 10000.0);
|
||||
float thresholdHigh = threshold * factorHigh;
|
||||
|
||||
if (diff < threshold) {
|
||||
weight = 1.0;
|
||||
} else if (diff > thresholdHigh) {
|
||||
weight = 0.0;
|
||||
} else {
|
||||
// Cubic smoothstep for more natural blending
|
||||
float t = (diff - threshold) / (thresholdHigh - threshold);
|
||||
weight = 1.0 - t * t * (3.0 - 2.0 * t);
|
||||
|
||||
// 5. Calculate Weight (Anisotropic)
|
||||
float c_ = kp.z; float s_ = kp.w;
|
||||
float cosT = sqrt(0.5 * (1.0 + c_));
|
||||
float sinT = sqrt(0.5 * (1.0 - c_));
|
||||
if (s_ < 0.0) sinT = -sinT;
|
||||
float u = d.x * cosT + d.y * sinT;
|
||||
float v = -d.x * sinT + d.y * cosT;
|
||||
float w = exp(-0.5 * (u*u/max(kp.x, 0.1) + v*v/max(kp.y, 0.1)));
|
||||
|
||||
float combinedWeight = w * robustness;
|
||||
accumulator.data[outIndex] += vec4(sampleColor * combinedWeight, combinedWeight);
|
||||
}
|
||||
}
|
||||
|
||||
accumulator.data[index] += vec4(targetVal.rgb * weight, weight);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
#version 450
|
||||
#extension GL_EXT_scalar_block_layout : require
|
||||
|
||||
layout(local_size_x = 16, local_size_y = 16) in;
|
||||
|
||||
layout(binding = 0) uniform sampler2D inputSampler;
|
||||
layout(binding = 1, scalar) writeonly buffer KernelParams {
|
||||
vec4 data[]; // (k1, k2, cos2theta, sin2theta)
|
||||
} kernelParams;
|
||||
|
||||
layout(push_constant, scalar) uniform PushConstants {
|
||||
float t0, t1, t2, t3, t4, t5;
|
||||
float offsetX, offsetY;
|
||||
float scale;
|
||||
uint width; // Global width
|
||||
uint height; // Global height
|
||||
float baseNoise; // Unused legacy
|
||||
uint isFirstFrame;
|
||||
uint tileX; // Tile start X
|
||||
uint tileY; // Tile start Y
|
||||
uint tileW; // Tile width
|
||||
uint tileH; // Tile height
|
||||
uint gridW;
|
||||
uint gridH;
|
||||
uint bufferStride;
|
||||
float noiseAlpha; // Sensor noise model slope
|
||||
float noiseBeta; // Sensor noise model intercept
|
||||
} pc;
|
||||
|
||||
void main() {
|
||||
uint tx = gl_GlobalInvocationID.x;
|
||||
uint ty = gl_GlobalInvocationID.y;
|
||||
|
||||
if (tx >= pc.tileW || ty >= pc.tileH) return;
|
||||
|
||||
uint x = pc.tileX + tx;
|
||||
uint y = pc.tileY + ty;
|
||||
|
||||
// Safety check for global bounds
|
||||
if (x >= pc.width || y >= pc.height) return;
|
||||
|
||||
// Convert output coordinate to UV
|
||||
vec2 pixelSize = vec2(1.0) / vec2(pc.width, pc.height);
|
||||
vec2 uv = (vec2(x, y) + 0.5) * pixelSize;
|
||||
|
||||
// Calculate Gradients and Smooth J (Structure Tensor Elements) using a 5x5 window
|
||||
// Larger window is MUCH more robust against high-ISO noise
|
||||
float sIxIx = 0.0;
|
||||
float sIyIy = 0.0;
|
||||
float sIxIy = 0.0;
|
||||
|
||||
for (int dy = -2; dy <= 2; dy++) {
|
||||
for (int dx = -2; dx <= 2; dx++) {
|
||||
vec2 offset = vec2(float(dx), float(dy)) * pixelSize;
|
||||
vec2 sampleUV = uv + offset;
|
||||
|
||||
float cxp = texture(inputSampler, sampleUV + vec2(pixelSize.x, 0.0)).r;
|
||||
float cxm = texture(inputSampler, sampleUV - vec2(pixelSize.x, 0.0)).r;
|
||||
float cyp = texture(inputSampler, sampleUV + vec2(0.0, pixelSize.y)).r;
|
||||
float cym = texture(inputSampler, sampleUV - vec2(0.0, pixelSize.y)).r;
|
||||
|
||||
float Ix_ = (cxp - cxm) * 0.5 * 255.0;
|
||||
float Iy_ = (cyp - cym) * 0.5 * 255.0;
|
||||
|
||||
sIxIx += Ix_ * Ix_;
|
||||
sIyIy += Iy_ * Iy_;
|
||||
sIxIy += Ix_ * Iy_;
|
||||
}
|
||||
}
|
||||
|
||||
// Eigen Analysis of J
|
||||
// Reasonable noise floor (10.0)
|
||||
float noiseFloor = 10.0;
|
||||
float IxIx = max(sIxIx / 25.0 - noiseFloor, 0.0);
|
||||
float IyIy = max(sIyIy / 25.0 - noiseFloor, 0.0);
|
||||
float IxIy = sIxIy / 25.0;
|
||||
|
||||
float trace = IxIx + IyIy;
|
||||
float disc = sqrt(max((IxIx - IyIy)*(IxIx - IyIy) + 4.0 * IxIy*IxIy, 0.0));
|
||||
|
||||
float lambda1 = 0.5 * (trace + disc);
|
||||
float lambda2 = 0.5 * (trace - disc);
|
||||
|
||||
// Feature amplitude
|
||||
float C = sqrt(max(lambda1, 0.0));
|
||||
float A = (lambda1 - lambda2) / (lambda1 + lambda2 + 0.01);
|
||||
|
||||
// Logic: Balanced Denoising
|
||||
float k_base = mix(8.0, 0.5, clamp(C / 100.0, 0.0, 1.0));
|
||||
float stretch = 1.0 + 3.0 * A;
|
||||
|
||||
float k1 = k_base / stretch;
|
||||
float k2 = k_base * stretch;
|
||||
|
||||
k1 = max(k1, 0.5);
|
||||
k2 = min(k2, 16.0);
|
||||
|
||||
// 2*theta logic for orientation
|
||||
float diff = IxIx - IyIy;
|
||||
float length = sqrt(diff * diff + 4.0 * IxIy * IxIy);
|
||||
|
||||
float cos2t, sin2t;
|
||||
if (length < 0.001) {
|
||||
cos2t = 1.0;
|
||||
sin2t = 0.0;
|
||||
} else {
|
||||
cos2t = diff / length;
|
||||
sin2t = 2.0 * IxIy / length;
|
||||
}
|
||||
|
||||
kernelParams.data[y * pc.width + x] = vec4(k1, k2, cos2t, sin2t);
|
||||
}
|
||||
@@ -14,6 +14,29 @@ inline uint8_t getPixel(const GrayImage &img, int x, int y) {
|
||||
return img.data[y * img.width + x];
|
||||
}
|
||||
|
||||
// Float version of getPixel for LK optical flow
|
||||
inline float getPixelF(const GrayImage &img, int x, int y) {
|
||||
x = std::max(0, std::min(x, img.width - 1));
|
||||
y = std::max(0, std::min(y, img.height - 1));
|
||||
return (float)img.data[y * img.width + x];
|
||||
}
|
||||
|
||||
// Bilinear interpolation on grayscale image for LK optical flow
|
||||
inline float sampleBilinearGray(const GrayImage &img, float x, float y) {
|
||||
int x0 = (int)std::floor(x);
|
||||
int y0 = (int)std::floor(y);
|
||||
float fx = x - x0;
|
||||
float fy = y - y0;
|
||||
|
||||
float v00 = getPixelF(img, x0, y0);
|
||||
float v10 = getPixelF(img, x0 + 1, y0);
|
||||
float v01 = getPixelF(img, x0, y0 + 1);
|
||||
float v11 = getPixelF(img, x0 + 1, y0 + 1);
|
||||
|
||||
return (1.0f - fx) * (1.0f - fy) * v00 + fx * (1.0f - fy) * v10 +
|
||||
(1.0f - fx) * fy * v01 + fx * fy * v11;
|
||||
}
|
||||
|
||||
// Sub-pixel refinement using parabolic interpolation
|
||||
// (Consolidated definition)
|
||||
inline float interpolateSubpixel(long long s0, long long s_minus,
|
||||
@@ -282,8 +305,7 @@ TileAlignment computeTileAlignment(const std::vector<GrayImage> &refPyramid,
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Sub-pixel Refinement (L1 scale)
|
||||
// We do subpixel at L1 to avoid noise at L0
|
||||
// 3. Sub-pixel Refinement: Parabolic initial estimate at L1
|
||||
long long s0 = bestSAD;
|
||||
long long sx_m = computeBlockSAD(refL1, tgtL1, refX, refY, matchSizeL1,
|
||||
matchSizeL1, bestDx - 1, bestDy);
|
||||
@@ -296,14 +318,67 @@ TileAlignment computeTileAlignment(const std::vector<GrayImage> &refPyramid,
|
||||
|
||||
float subDx = interpolateSubpixel(s0, sx_m, sx_p);
|
||||
float subDy = interpolateSubpixel(s0, sy_m, sy_p);
|
||||
|
||||
// Clamp subpixel to avoid wild shots on flat textures
|
||||
subDx = std::max(-0.5f, std::min(0.5f, subDx));
|
||||
subDy = std::max(-0.5f, std::min(0.5f, subDy));
|
||||
|
||||
// Scale back to L0 (multiply by 2)
|
||||
rawOffsets[ty * gridW + tx] = {(float)(bestDx + subDx) * 2.0f,
|
||||
(float)(bestDy + subDy) * 2.0f};
|
||||
// 4. Lucas-Kanade refinement at L0 for sub-pixel accuracy
|
||||
// Scale L1 result to L0 as initial estimate
|
||||
const GrayImage &refL0 = refPyramid[0];
|
||||
const GrayImage &tgtL0 = targetPyramid[0];
|
||||
float lkDx = (float)(bestDx + subDx) * 2.0f;
|
||||
float lkDy = (float)(bestDy + subDy) * 2.0f;
|
||||
|
||||
int cx = tx * tileSize + tileSize / 2;
|
||||
int cy = ty * tileSize + tileSize / 2;
|
||||
int lkHalfWin = 8; // 16x16 LK window
|
||||
|
||||
for (int iter = 0; iter < 3; ++iter) {
|
||||
float sumIxIx = 0, sumIyIy = 0, sumIxIy = 0;
|
||||
float sumIxIt = 0, sumIyIt = 0;
|
||||
|
||||
for (int wy = -lkHalfWin; wy < lkHalfWin; ++wy) {
|
||||
for (int wx = -lkHalfWin; wx < lkHalfWin; ++wx) {
|
||||
int rx = cx + wx;
|
||||
int ry = cy + wy;
|
||||
if (rx < 1 || rx >= width - 1 || ry < 1 || ry >= height - 1)
|
||||
continue;
|
||||
|
||||
float Ix =
|
||||
(getPixelF(refL0, rx + 1, ry) - getPixelF(refL0, rx - 1, ry)) *
|
||||
0.5f;
|
||||
float Iy =
|
||||
(getPixelF(refL0, rx, ry + 1) - getPixelF(refL0, rx, ry - 1)) *
|
||||
0.5f;
|
||||
float It = sampleBilinearGray(tgtL0, rx + lkDx, ry + lkDy) -
|
||||
getPixelF(refL0, rx, ry);
|
||||
|
||||
sumIxIx += Ix * Ix;
|
||||
sumIyIy += Iy * Iy;
|
||||
sumIxIy += Ix * Iy;
|
||||
sumIxIt += Ix * It;
|
||||
sumIyIt += Iy * It;
|
||||
}
|
||||
}
|
||||
|
||||
float det = sumIxIx * sumIyIy - sumIxIy * sumIxIy;
|
||||
if (std::abs(det) < 1e-6f)
|
||||
break;
|
||||
|
||||
float dvx = (sumIyIy * sumIxIt - sumIxIy * sumIyIt) / det;
|
||||
float dvy = (sumIxIx * sumIyIt - sumIxIy * sumIxIt) / det;
|
||||
|
||||
// Clamp per-iteration update to prevent divergence
|
||||
dvx = std::max(-1.0f, std::min(1.0f, dvx));
|
||||
dvy = std::max(-1.0f, std::min(1.0f, dvy));
|
||||
|
||||
lkDx -= dvx;
|
||||
lkDy -= dvy;
|
||||
|
||||
if (dvx * dvx + dvy * dvy < 0.001f)
|
||||
break;
|
||||
}
|
||||
|
||||
rawOffsets[ty * gridW + tx] = {lkDx, lkDy};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -334,6 +409,55 @@ TileAlignment computeTileAlignment(const std::vector<GrayImage> &refPyramid,
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Compute Motion Prior (Error Map)
|
||||
// Variance of the flow indicates reliability.
|
||||
alignment.errorMap.resize(gridW * gridH);
|
||||
#pragma omp parallel for collapse(2) num_threads(4)
|
||||
for (int y = 0; y < gridH; ++y) {
|
||||
for (int x = 0; x < gridW; ++x) {
|
||||
Point smooth = alignment.offsets[y * gridW + x];
|
||||
float sumSqDiff = 0;
|
||||
float wSum = 0;
|
||||
|
||||
for (int dy = -1; dy <= 1; ++dy) {
|
||||
for (int dx = -1; dx <= 1; ++dx) {
|
||||
int nx = std::max(0, std::min(x + dx, gridW - 1));
|
||||
int ny = std::max(0, std::min(y + dy, gridH - 1));
|
||||
|
||||
Point raw = rawOffsets[ny * gridW + nx];
|
||||
float diffX = raw.x - smooth.x;
|
||||
float diffY = raw.y - smooth.y;
|
||||
float distSq = diffX * diffX + diffY * diffY;
|
||||
|
||||
float w = (dx == 0 && dy == 0) ? 2.0f : 1.0f;
|
||||
sumSqDiff += distSq * w;
|
||||
wSum += w;
|
||||
}
|
||||
}
|
||||
// Scale error for display/usage? Keep it as variance in pixels^2
|
||||
alignment.errorMap[y * gridW + x] = sumSqDiff / wSum;
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Dilate Error Map (Morphological Dilation) - 3x3 Max Filter
|
||||
// This extends the "unsafe" regions slightly to be conservative.
|
||||
std::vector<float> errorMapDilated = alignment.errorMap;
|
||||
#pragma omp parallel for collapse(2) num_threads(4)
|
||||
for (int y = 0; y < gridH; ++y) {
|
||||
for (int x = 0; x < gridW; ++x) {
|
||||
float maxErr = 0;
|
||||
for (int dy = -1; dy <= 1; ++dy) {
|
||||
for (int dx = -1; dx <= 1; ++dx) {
|
||||
int nx = std::max(0, std::min(x + dx, gridW - 1));
|
||||
int ny = std::max(0, std::min(y + dy, gridH - 1));
|
||||
maxErr = std::max(maxErr, alignment.errorMap[ny * gridW + nx]);
|
||||
}
|
||||
}
|
||||
errorMapDilated[y * gridW + x] = maxErr;
|
||||
}
|
||||
}
|
||||
alignment.errorMap = std::move(errorMapDilated);
|
||||
|
||||
return alignment;
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,8 @@ struct TileAlignment {
|
||||
int gridW;
|
||||
int gridH;
|
||||
std::vector<Point> offsets;
|
||||
// Motion Prior (Error Map): Stores local variance/instability of the flow
|
||||
std::vector<float> errorMap;
|
||||
|
||||
Point getOffset(int x, int y) const {
|
||||
if (tileWidth <= 0 || tileHeight <= 0 || offsets.empty())
|
||||
@@ -69,6 +71,20 @@ struct TileAlignment {
|
||||
(1.0f - dx) * dy * p01.y + dx * dy * p11.y;
|
||||
return result;
|
||||
}
|
||||
|
||||
float getError(int x, int y) const {
|
||||
if (tileWidth <= 0 || tileHeight <= 0 || errorMap.empty())
|
||||
return 0.0f;
|
||||
|
||||
// Nearest neighbor or bilinear? Nearest is enough for error map
|
||||
int gx = (int)((float)x / (float)tileWidth);
|
||||
int gy = (int)((float)y / (float)tileHeight);
|
||||
|
||||
gx = std::max(0, std::min(gx, gridW - 1));
|
||||
gy = std::max(0, std::min(gy, gridH - 1));
|
||||
|
||||
return errorMap[gy * gridW + gx];
|
||||
}
|
||||
};
|
||||
|
||||
// Represents a grayscale image buffer for processing
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "vulkan_stacker.h"
|
||||
#include "accumulate.comp.h"
|
||||
#include "normalize.comp.h"
|
||||
#include "structure_tensor.comp.h"
|
||||
#include <android/log.h>
|
||||
#include <sys/resource.h>
|
||||
#include <unistd.h>
|
||||
@@ -169,6 +170,61 @@ void VulkanImageStacker::initVulkanResources() {
|
||||
&barrier, 0, nullptr);
|
||||
}
|
||||
vm.endSingleTimeCommands(cb);
|
||||
|
||||
// Phase 2: Kernel Params Buffer (Native Resolution - much safer for VRAM)
|
||||
VkDeviceSize kpSize =
|
||||
(VkDeviceSize)width * height * sizeof(float) * 4; // vec4
|
||||
|
||||
VkBufferCreateInfo kpInfo{};
|
||||
kpInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
kpInfo.size = kpSize;
|
||||
kpInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
|
||||
kpInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
||||
VK_CHECK(vkCreateBuffer(device, &kpInfo, nullptr, &kernelParamsBuffer));
|
||||
|
||||
VkMemoryRequirements kpReqs;
|
||||
vkGetBufferMemoryRequirements(device, kernelParamsBuffer, &kpReqs);
|
||||
|
||||
VkMemoryAllocateInfo kpAlloc{};
|
||||
kpAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
|
||||
kpAlloc.allocationSize = kpReqs.size;
|
||||
kpAlloc.memoryTypeIndex = vm.findMemoryType(
|
||||
kpReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
|
||||
VK_CHECK(vkAllocateMemory(device, &kpAlloc, nullptr, &kernelParamsMemory));
|
||||
vkBindBufferMemory(device, kernelParamsBuffer, kernelParamsMemory, 0);
|
||||
|
||||
// Allocate Descriptor Sets for Structure Tensor (One per tile? No, global
|
||||
// pass or tile based?) For simplicity, let's make Structure Tensor a global
|
||||
// pass or tile based. The shader uses inputSampler and kernelParams. Let's
|
||||
// use 1 descriptor set for the whole image if possible, or per tile. Since we
|
||||
// run ST on full image (or tiles), let's allocate 'numTiles' sets for it too
|
||||
// to be consistent with dispatch pattern.
|
||||
tensorSets.resize(numTiles);
|
||||
|
||||
// Phase 3: Motion Prior Buffer (Grid resolution, float)
|
||||
// Grid size: max (width+31)/32 * (height+31)/32
|
||||
// We reuse the 'gridW * gridH' logic, but max possible grid size is
|
||||
// alignedW/32 * alignedH/32
|
||||
VkDeviceSize mpSize = (VkDeviceSize)gridW * gridH * sizeof(float);
|
||||
|
||||
VkBufferCreateInfo mpInfo{};
|
||||
mpInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
|
||||
mpInfo.size = mpSize;
|
||||
mpInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
|
||||
mpInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
|
||||
VK_CHECK(vkCreateBuffer(device, &mpInfo, nullptr, &motionPriorBuffer));
|
||||
|
||||
VkMemoryRequirements mpReqs;
|
||||
vkGetBufferMemoryRequirements(device, motionPriorBuffer, &mpReqs);
|
||||
|
||||
VkMemoryAllocateInfo mpAlloc{};
|
||||
mpAlloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
|
||||
mpAlloc.allocationSize = mpReqs.size;
|
||||
mpAlloc.memoryTypeIndex = vm.findMemoryType(
|
||||
mpReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
|
||||
VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
VK_CHECK(vkAllocateMemory(device, &mpAlloc, nullptr, &motionPriorMemory));
|
||||
vkBindBufferMemory(device, motionPriorBuffer, motionPriorMemory, 0);
|
||||
}
|
||||
|
||||
void VulkanImageStacker::createPipelines(VkSampler sampler) {
|
||||
@@ -177,7 +233,7 @@ void VulkanImageStacker::createPipelines(VkSampler sampler) {
|
||||
|
||||
// 1. Descriptor Set Layout with Immutable Sampler
|
||||
VkSampler samplers[1] = {sampler};
|
||||
VkDescriptorSetLayoutBinding bindings[3] = {};
|
||||
VkDescriptorSetLayoutBinding bindings[4] = {}; // Increased to 4
|
||||
bindings[0].binding = 0;
|
||||
bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||||
bindings[0].descriptorCount = 1;
|
||||
@@ -194,10 +250,28 @@ void VulkanImageStacker::createPipelines(VkSampler sampler) {
|
||||
bindings[2].descriptorCount = 1;
|
||||
bindings[2].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
|
||||
|
||||
bindings[3].binding = 3; // KernelParams (Read Only)
|
||||
bindings[3].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
|
||||
bindings[3].descriptorCount = 1;
|
||||
bindings[3].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
|
||||
|
||||
VkDescriptorSetLayoutBinding motionPriorBinding{};
|
||||
motionPriorBinding.binding = 4; // Motion Prior
|
||||
motionPriorBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
|
||||
motionPriorBinding.descriptorCount = 1;
|
||||
motionPriorBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
|
||||
|
||||
VkDescriptorSetLayoutBinding bindingsFinal[5];
|
||||
bindingsFinal[0] = bindings[0];
|
||||
bindingsFinal[1] = bindings[1];
|
||||
bindingsFinal[2] = bindings[2];
|
||||
bindingsFinal[3] = bindings[3];
|
||||
bindingsFinal[4] = motionPriorBinding;
|
||||
|
||||
VkDescriptorSetLayoutCreateInfo layoutInfo{};
|
||||
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
|
||||
layoutInfo.bindingCount = 3;
|
||||
layoutInfo.pBindings = bindings;
|
||||
layoutInfo.bindingCount = 5;
|
||||
layoutInfo.pBindings = bindingsFinal;
|
||||
vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr,
|
||||
&descriptorSetLayout);
|
||||
|
||||
@@ -284,6 +358,53 @@ void VulkanImageStacker::createPipelines(VkSampler sampler) {
|
||||
vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &normPipelineInfo,
|
||||
nullptr, &normalizePipeline);
|
||||
vkDestroyShaderModule(device, normShaderModule, nullptr);
|
||||
|
||||
// 5. Create Structure Tensor Pipeline
|
||||
// Layout: Binding 0 (Sampler), Binding 1 (KernelParams Out)
|
||||
VkDescriptorSetLayoutBinding tensorBindings[2] = {};
|
||||
tensorBindings[0].binding = 0;
|
||||
tensorBindings[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||||
tensorBindings[0].descriptorCount = 1;
|
||||
tensorBindings[0].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
|
||||
tensorBindings[0].pImmutableSamplers = samplers; // Setup immutable sampler
|
||||
|
||||
tensorBindings[1].binding = 1;
|
||||
tensorBindings[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
|
||||
tensorBindings[1].descriptorCount = 1;
|
||||
tensorBindings[1].stageFlags = VK_SHADER_STAGE_COMPUTE_BIT;
|
||||
|
||||
VkDescriptorSetLayoutCreateInfo tensorLayoutInfo{};
|
||||
tensorLayoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
|
||||
tensorLayoutInfo.bindingCount = 2;
|
||||
tensorLayoutInfo.pBindings = tensorBindings;
|
||||
vkCreateDescriptorSetLayout(device, &tensorLayoutInfo, nullptr,
|
||||
&tensorSetLayout);
|
||||
|
||||
VkPipelineLayoutCreateInfo tensorPLInfo{};
|
||||
tensorPLInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
|
||||
tensorPLInfo.setLayoutCount = 1;
|
||||
tensorPLInfo.pSetLayouts = &tensorSetLayout;
|
||||
tensorPLInfo.pushConstantRangeCount = 1;
|
||||
tensorPLInfo.pPushConstantRanges = &pushConstantRange;
|
||||
vkCreatePipelineLayout(device, &tensorPLInfo, nullptr, &tensorPipelineLayout);
|
||||
|
||||
std::vector<uint32_t> stCode(structure_tensor_comp_spv,
|
||||
structure_tensor_comp_spv +
|
||||
(structure_tensor_comp_spv_size / 4));
|
||||
VkShaderModule stModule = vm.createShaderModule(stCode);
|
||||
|
||||
VkComputePipelineCreateInfo stPipelineInfo{};
|
||||
stPipelineInfo.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO;
|
||||
stPipelineInfo.layout = tensorPipelineLayout;
|
||||
stPipelineInfo.stage.sType =
|
||||
VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
|
||||
stPipelineInfo.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT;
|
||||
stPipelineInfo.stage.module = stModule;
|
||||
stPipelineInfo.stage.pName = "main";
|
||||
|
||||
vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &stPipelineInfo, nullptr,
|
||||
&tensorPipeline);
|
||||
vkDestroyShaderModule(device, stModule, nullptr);
|
||||
}
|
||||
|
||||
bool VulkanImageStacker::addFrame(AHardwareBuffer *buffer) {
|
||||
@@ -296,31 +417,38 @@ bool VulkanImageStacker::addFrame(AHardwareBuffer *buffer) {
|
||||
|
||||
bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer) {
|
||||
VulkanImage input;
|
||||
if (!VulkanBufferImporter::importHardwareBuffer(buffer, input)) {
|
||||
// Use existing conversion if available (from first frame) to compatible with
|
||||
// immutable sampler
|
||||
if (!VulkanBufferImporter::importHardwareBuffer(buffer, input,
|
||||
this->ycbcrConversion)) {
|
||||
LOGE("processFrame: Failed to import hardware buffer");
|
||||
return false;
|
||||
}
|
||||
|
||||
bool currentIsFirstFrame = isFirstFrame;
|
||||
LOGI("processFrame: Start. isFirstFrame=%d", currentIsFirstFrame);
|
||||
|
||||
VulkanManager &vm = VulkanManager::getInstance();
|
||||
VkDevice device = vm.getDevice();
|
||||
|
||||
// On the first frame, we MUST create the pipelines using this frame's sampler
|
||||
// as an IMMUTABLE sampler. This is required for Android YUV external formats
|
||||
// to work correctly.
|
||||
// Capture first frame state before we potentially update it
|
||||
bool currentIsFirstFrame = isFirstFrame;
|
||||
|
||||
if (currentIsFirstFrame) {
|
||||
// Steal the first frame's sampler and conversion for long-lived pipelines
|
||||
this->immutableSampler = input.sampler;
|
||||
this->ycbcrConversion = input.ycbcrConversion;
|
||||
input.sampler = VK_NULL_HANDLE;
|
||||
input.ycbcrConversion = VK_NULL_HANDLE;
|
||||
input.ycbcrConversion = VK_NULL_HANDLE; // Steal ownership
|
||||
|
||||
createPipelines(this->immutableSampler);
|
||||
} else {
|
||||
// If not first frame, we reused the conversion.
|
||||
// We must NOT let input.release() destroy it, because
|
||||
// 'this->ycbcrConversion' owns it now.
|
||||
input.ycbcrConversion = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
// 1. Allocate and Update Descriptor Sets for each tile
|
||||
// Need to increase pool size? initVulkanResources allocation was "Generous"
|
||||
// (32 per tile). We added tensor sets.
|
||||
int numTiles = numTilesX * numTilesY;
|
||||
|
||||
for (int i = 0; i < numTiles; ++i) {
|
||||
@@ -346,7 +474,17 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer) {
|
||||
alignBufferInfo.offset = 0;
|
||||
alignBufferInfo.range = VK_WHOLE_SIZE;
|
||||
|
||||
VkWriteDescriptorSet descriptorWrites[3] = {};
|
||||
VkDescriptorBufferInfo kpBufferInfo{};
|
||||
kpBufferInfo.buffer = kernelParamsBuffer;
|
||||
kpBufferInfo.offset = 0;
|
||||
kpBufferInfo.range = VK_WHOLE_SIZE;
|
||||
|
||||
VkDescriptorBufferInfo mpBufferInfo{};
|
||||
mpBufferInfo.buffer = motionPriorBuffer;
|
||||
mpBufferInfo.offset = 0;
|
||||
mpBufferInfo.range = VK_WHOLE_SIZE;
|
||||
|
||||
VkWriteDescriptorSet descriptorWrites[5] = {}; // Increased to 5
|
||||
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
|
||||
descriptorWrites[0].dstSet = accumSets[i];
|
||||
descriptorWrites[0].dstBinding = 0;
|
||||
@@ -369,7 +507,46 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer) {
|
||||
descriptorWrites[2].descriptorCount = 1;
|
||||
descriptorWrites[2].pBufferInfo = &alignBufferInfo;
|
||||
|
||||
vkUpdateDescriptorSets(device, 3, descriptorWrites, 0, nullptr);
|
||||
descriptorWrites[3].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
|
||||
descriptorWrites[3].dstSet = accumSets[i];
|
||||
descriptorWrites[3].dstBinding = 3;
|
||||
descriptorWrites[3].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
|
||||
descriptorWrites[3].descriptorCount = 1;
|
||||
descriptorWrites[3].pBufferInfo = &kpBufferInfo;
|
||||
|
||||
descriptorWrites[4].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
|
||||
descriptorWrites[4].dstSet = accumSets[i];
|
||||
descriptorWrites[4].dstBinding = 4;
|
||||
descriptorWrites[4].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
|
||||
descriptorWrites[4].descriptorCount = 1;
|
||||
descriptorWrites[4].pBufferInfo = &mpBufferInfo;
|
||||
|
||||
vkUpdateDescriptorSets(device, 5, descriptorWrites, 0, nullptr);
|
||||
|
||||
// Also Allocate Tensor Sets
|
||||
VkDescriptorSetAllocateInfo tensorAlloc{};
|
||||
tensorAlloc.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
|
||||
tensorAlloc.descriptorPool = descriptorPool;
|
||||
tensorAlloc.descriptorSetCount = 1;
|
||||
tensorAlloc.pSetLayouts = &tensorSetLayout;
|
||||
VK_CHECK(vkAllocateDescriptorSets(device, &tensorAlloc, &tensorSets[i]));
|
||||
|
||||
VkWriteDescriptorSet tensorWrites[2] = {};
|
||||
tensorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
|
||||
tensorWrites[0].dstSet = tensorSets[i];
|
||||
tensorWrites[0].dstBinding = 0;
|
||||
tensorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
|
||||
tensorWrites[0].descriptorCount = 1;
|
||||
tensorWrites[0].pImageInfo = &imageInfo; // Same input image
|
||||
|
||||
tensorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
|
||||
tensorWrites[1].dstSet = tensorSets[i];
|
||||
tensorWrites[1].dstBinding = 1;
|
||||
tensorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
|
||||
tensorWrites[1].descriptorCount = 1;
|
||||
tensorWrites[1].pBufferInfo = &kpBufferInfo; // Output to Kernel Params
|
||||
|
||||
vkUpdateDescriptorSets(device, 2, tensorWrites, 0, nullptr);
|
||||
}
|
||||
// 2. Alignment logic on CPU (to get offsets)
|
||||
float offsetX = 0.0f, offsetY = 0.0f;
|
||||
@@ -434,6 +611,21 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer) {
|
||||
} else {
|
||||
LOGE("VulkanImageStacker: Failed to map alignment memory: %d", res);
|
||||
}
|
||||
|
||||
void *mpMapPtr = nullptr;
|
||||
VkResult resMP = vkMapMemory(device, motionPriorMemory, 0,
|
||||
VK_WHOLE_SIZE, 0, &mpMapPtr);
|
||||
if (resMP == VK_SUCCESS && mpMapPtr != nullptr) {
|
||||
if (alignment.errorMap.size() >= copyCount) {
|
||||
memcpy(mpMapPtr, alignment.errorMap.data(),
|
||||
copyCount * sizeof(float));
|
||||
} else {
|
||||
LOGE("VulkanImageStacker: Error Map size mismatch!");
|
||||
}
|
||||
vkUnmapMemory(device, motionPriorMemory);
|
||||
} else {
|
||||
LOGE("VulkanImageStacker: Failed to map MP memory: %d", resMP);
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate global average offset for fallback (redundant but kept for
|
||||
@@ -469,9 +661,133 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer) {
|
||||
pc.isFirstFrame = currentIsFirstFrame ? 1 : 0;
|
||||
pc.gridW = gridW;
|
||||
pc.gridH = gridH;
|
||||
// Phase 6: High-ISO Capable Noise Model
|
||||
pc.noiseAlpha = 0.12f;
|
||||
pc.noiseBeta = 0.10f;
|
||||
|
||||
LOGI("processFrame: Dispatching. Alpha=%f, Beta=%f, Scale=%f, Grid=%dx%d",
|
||||
pc.noiseAlpha, pc.noiseBeta, pc.scale, gridW, gridH);
|
||||
|
||||
// 3. Command Buffer Recording
|
||||
VkCommandBuffer cb = vm.beginSingleTimeCommands();
|
||||
|
||||
// Transition Input Image Layout
|
||||
VkImageMemoryBarrier imageBarrier{};
|
||||
imageBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
|
||||
imageBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
|
||||
imageBarrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
||||
imageBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||||
imageBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
|
||||
imageBarrier.image = input.image;
|
||||
imageBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
|
||||
imageBarrier.subresourceRange.baseMipLevel = 0;
|
||||
imageBarrier.subresourceRange.levelCount = 1;
|
||||
imageBarrier.subresourceRange.baseArrayLayer = 0;
|
||||
imageBarrier.subresourceRange.layerCount = 1;
|
||||
imageBarrier.srcAccessMask = 0;
|
||||
imageBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
|
||||
|
||||
vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0,
|
||||
nullptr, 1, &imageBarrier);
|
||||
|
||||
// Clear Accumulators if first frame
|
||||
if (pc.isFirstFrame) {
|
||||
for (int i = 0; i < numTiles; ++i) {
|
||||
vkCmdFillBuffer(cb, accumBuffers[i], 0, VK_WHOLE_SIZE, 0);
|
||||
}
|
||||
// Barrier to ensure clear is done before usage?
|
||||
// SingleTimeCommands end with a queue submission which has implicit
|
||||
// ordering if we record linearly? No, we need a barrier if we use it in the
|
||||
// SAME command buffer as Dispatch. Yes, we are in the same CB.
|
||||
|
||||
VkMemoryBarrier memBarrier = {};
|
||||
memBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
|
||||
memBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
memBarrier.dstAccessMask =
|
||||
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
|
||||
|
||||
vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1,
|
||||
&memBarrier, 0, nullptr, 0, nullptr);
|
||||
}
|
||||
|
||||
// Phase 2: Compute Structure Tensor (Pass 1)
|
||||
|
||||
// Phase 2: Compute Structure Tensor (Pass 1)
|
||||
// Only if first frame? Or every frame?
|
||||
// Paper says: Structure tensor is computed on the image being merged
|
||||
// (Target). So we must compute it for EVERY frame.
|
||||
|
||||
vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, tensorPipeline);
|
||||
|
||||
// Use pc.scale and global width/height from PC
|
||||
// pc was prepared above, let's use it.
|
||||
|
||||
// Dispatch over the image logic (tiled or global?)
|
||||
// We allocated per-tile descriptor sets.
|
||||
|
||||
for (int y = 0; y < numTilesY; ++y) {
|
||||
for (int x = 0; x < numTilesX; ++x) {
|
||||
int i = y * numTilesX + x;
|
||||
// Reuse PC logic for tiling, but Structure Tensor covers full target
|
||||
// frame. Actually Structure Tensor is 1:1 with Upscaled Output if we want
|
||||
// per-pixel kernel. Shader uses inputSampler and writes to kpBuffer. We
|
||||
// can dispatch over tiles logic.
|
||||
|
||||
// Calculate tile rect (Using NATIVE resolution for ST calculation)
|
||||
uint32_t stFullW = width;
|
||||
uint32_t stFullH = height;
|
||||
uint32_t stTileW = (stFullW + numTilesX - 1) / numTilesX;
|
||||
uint32_t stTileH = (stFullH + numTilesY - 1) / numTilesY;
|
||||
|
||||
PushConstants stPC = pc;
|
||||
stPC.tileX = x * stTileW;
|
||||
stPC.tileY = y * stTileH;
|
||||
stPC.tileW = std::min(stTileW, stFullW - stPC.tileX);
|
||||
stPC.tileH = std::min(stTileH, stFullH - stPC.tileY);
|
||||
// Ensure shader sees native dimensions for indexing
|
||||
stPC.width = stFullW;
|
||||
stPC.height = stFullH;
|
||||
|
||||
// Bind ST Set
|
||||
vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE,
|
||||
tensorPipelineLayout, 0, 1, &tensorSets[i], 0,
|
||||
nullptr);
|
||||
vkCmdPushConstants(cb, tensorPipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT,
|
||||
0, sizeof(stPC), &stPC);
|
||||
|
||||
// Dispatch
|
||||
vkCmdDispatch(cb, (stPC.tileW + 15) / 16, (stPC.tileH + 15) / 16, 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Barrier between ST and Accumulate
|
||||
VkBufferMemoryBarrier stBarrier{};
|
||||
stBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
|
||||
stBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
|
||||
stBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
|
||||
stBarrier.buffer = kernelParamsBuffer;
|
||||
stBarrier.size = VK_WHOLE_SIZE;
|
||||
vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1,
|
||||
&stBarrier, 0, nullptr);
|
||||
|
||||
// Barrier between frames to ensure Accumulator writes are finished
|
||||
for (int i = 0; i < numTiles; ++i) {
|
||||
VkBufferMemoryBarrier postBarrier{};
|
||||
postBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
|
||||
postBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
|
||||
postBarrier.dstAccessMask =
|
||||
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
|
||||
postBarrier.buffer = accumBuffers[i];
|
||||
postBarrier.size = VK_WHOLE_SIZE;
|
||||
vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1,
|
||||
&postBarrier, 0, nullptr);
|
||||
}
|
||||
|
||||
// Pass 2: Accumulate
|
||||
vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, accumulatePipeline);
|
||||
|
||||
uint32_t fullW = pc.width;
|
||||
@@ -496,10 +812,22 @@ bool VulkanImageStacker::processFrame(AHardwareBuffer *buffer) {
|
||||
}
|
||||
}
|
||||
|
||||
// Global barrier between frames to ensure ALL accumulator tiles are finished
|
||||
// writing before the next frame begins reading or before normalization
|
||||
VkMemoryBarrier postBarrier{};
|
||||
postBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
|
||||
postBarrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
|
||||
postBarrier.dstAccessMask =
|
||||
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT;
|
||||
vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 1, &postBarrier,
|
||||
0, nullptr, 0, nullptr);
|
||||
|
||||
vm.endSingleTimeCommands(cb);
|
||||
vkQueueWaitIdle(vm.getComputeQueue());
|
||||
|
||||
vkFreeDescriptorSets(device, descriptorPool, numTiles, accumSets.data());
|
||||
vkFreeDescriptorSets(device, descriptorPool, numTiles, tensorSets.data());
|
||||
isFirstFrame = false;
|
||||
input.release(device);
|
||||
return true;
|
||||
@@ -541,7 +869,8 @@ bool VulkanImageStacker::processStack(uint32_t *outBitmap, uint32_t outWidth,
|
||||
setpriority(PRIO_PROCESS, 0, 10);
|
||||
|
||||
// Process all queued frames first
|
||||
if (pendingFrames.empty() && isFirstFrame) {
|
||||
isFirstFrame = true;
|
||||
if (pendingFrames.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -555,14 +884,18 @@ bool VulkanImageStacker::processStack(uint32_t *outBitmap, uint32_t outWidth,
|
||||
pendingFrames.begin(), pendingFrames.end(),
|
||||
[](const FrameData &a, const FrameData &b) { return a.score > b.score; });
|
||||
|
||||
if (!pendingFrames.empty()) {
|
||||
LOGI("VulkanImageStacker: Reference frame score: %.2f",
|
||||
pendingFrames.front().score);
|
||||
}
|
||||
LOGI("processStack: Processing %zu frames", pendingFrames.size());
|
||||
|
||||
int frameIdx = 0;
|
||||
for (auto &frame : pendingFrames) {
|
||||
processFrame(frame.buffer);
|
||||
LOGI("processStack: Processing frame %d, score %f", frameIdx, frame.score);
|
||||
if (!processFrame(frame.buffer)) {
|
||||
LOGE("processStack: Failed to process frame %d", frameIdx);
|
||||
} else {
|
||||
LOGI("processStack: Successfully processed frame %d", frameIdx);
|
||||
}
|
||||
AHardwareBuffer_release(frame.buffer);
|
||||
frameIdx++;
|
||||
}
|
||||
pendingFrames.clear();
|
||||
|
||||
@@ -788,4 +1121,21 @@ void VulkanImageStacker::releaseVulkanResources() {
|
||||
vkDestroyBuffer(device, alignmentBuffer, nullptr);
|
||||
if (alignmentMemory != VK_NULL_HANDLE)
|
||||
vkFreeMemory(device, alignmentMemory, nullptr);
|
||||
|
||||
if (kernelParamsBuffer != VK_NULL_HANDLE)
|
||||
vkDestroyBuffer(device, kernelParamsBuffer, nullptr);
|
||||
if (kernelParamsMemory != VK_NULL_HANDLE)
|
||||
vkFreeMemory(device, kernelParamsMemory, nullptr);
|
||||
|
||||
if (motionPriorBuffer != VK_NULL_HANDLE)
|
||||
vkDestroyBuffer(device, motionPriorBuffer, nullptr);
|
||||
if (motionPriorMemory != VK_NULL_HANDLE)
|
||||
vkFreeMemory(device, motionPriorMemory, nullptr);
|
||||
|
||||
if (tensorSetLayout != VK_NULL_HANDLE)
|
||||
vkDestroyDescriptorSetLayout(device, tensorSetLayout, nullptr);
|
||||
if (tensorPipelineLayout != VK_NULL_HANDLE)
|
||||
vkDestroyPipelineLayout(device, tensorPipelineLayout, nullptr);
|
||||
if (tensorPipeline != VK_NULL_HANDLE)
|
||||
vkDestroyPipeline(device, tensorPipeline, nullptr);
|
||||
}
|
||||
@@ -72,6 +72,9 @@ private:
|
||||
uint32_t gridW;
|
||||
uint32_t gridH;
|
||||
uint32_t bufferStride;
|
||||
// Phase 2/3: Noise Model
|
||||
float noiseAlpha;
|
||||
float noiseBeta;
|
||||
};
|
||||
|
||||
struct FrameData {
|
||||
@@ -80,6 +83,19 @@ private:
|
||||
};
|
||||
std::vector<FrameData> pendingFrames;
|
||||
|
||||
// Phase 2: Structure Tensor Resources
|
||||
VkBuffer kernelParamsBuffer = VK_NULL_HANDLE;
|
||||
VkDeviceMemory kernelParamsMemory = VK_NULL_HANDLE;
|
||||
|
||||
VkDescriptorSetLayout tensorSetLayout = VK_NULL_HANDLE;
|
||||
VkPipelineLayout tensorPipelineLayout = VK_NULL_HANDLE;
|
||||
VkPipeline tensorPipeline = VK_NULL_HANDLE;
|
||||
std::vector<VkDescriptorSet> tensorSets;
|
||||
|
||||
// Phase 3: Motion Prior Buffer (Grid Resolution)
|
||||
VkBuffer motionPriorBuffer = VK_NULL_HANDLE;
|
||||
VkDeviceMemory motionPriorMemory = VK_NULL_HANDLE;
|
||||
|
||||
void initVulkanResources();
|
||||
void releaseVulkanResources();
|
||||
void createPipelines(VkSampler immutableSampler);
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
#include "vulkan_utils.h"
|
||||
#include "common.h"
|
||||
|
||||
bool VulkanBufferImporter::importHardwareBuffer(AHardwareBuffer *buffer,
|
||||
VulkanImage &outImage) {
|
||||
bool VulkanBufferImporter::importHardwareBuffer(
|
||||
AHardwareBuffer *buffer, VulkanImage &outImage,
|
||||
VkSamplerYcbcrConversion existingConversion) {
|
||||
VulkanManager &vm = VulkanManager::getInstance();
|
||||
VkDevice device = vm.getDevice();
|
||||
|
||||
@@ -94,37 +95,52 @@ bool VulkanBufferImporter::importHardwareBuffer(AHardwareBuffer *buffer,
|
||||
formatProps.format >= 1000156000); // Check for YCbCr formats
|
||||
|
||||
if (isYUV) {
|
||||
VkSamplerYcbcrConversionCreateInfo ycbcrCreateInfo{};
|
||||
ycbcrCreateInfo.sType =
|
||||
VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO;
|
||||
ycbcrCreateInfo.format = formatProps.format;
|
||||
if (existingConversion != VK_NULL_HANDLE) {
|
||||
outImage.ycbcrConversion = existingConversion;
|
||||
// Important: If we use existing conversion, we do NOT own it, so we
|
||||
// shouldn't destroy it? But VulkanImage.release() will destroy it. We
|
||||
// need a mechanism to signal ownership or modify release(). For
|
||||
// simplicity: VulkanImageStacker manages the lifecycle of the *first*
|
||||
// conversion (in immutableSampler/ycbcrConversion members). The temporary
|
||||
// input images just borrow it. So we should NOT set
|
||||
// outImage.ycbcrConversion if we want to avoid double free? NO, we need
|
||||
// it set for ImageView creation below. We must update
|
||||
// VulkanImage.release() to NOT destroy it if it's borrowed, OR simply set
|
||||
// it to NULL before release() in the caller. Let's set it here, and
|
||||
// caller (vulkan_stacker) must define logic.
|
||||
} else {
|
||||
VkSamplerYcbcrConversionCreateInfo ycbcrCreateInfo{};
|
||||
ycbcrCreateInfo.sType =
|
||||
VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO;
|
||||
ycbcrCreateInfo.format = formatProps.format;
|
||||
|
||||
ycbcrCreateInfo.ycbcrModel = formatProps.suggestedYcbcrModel;
|
||||
ycbcrCreateInfo.ycbcrRange = formatProps.suggestedYcbcrRange;
|
||||
ycbcrCreateInfo.ycbcrModel = formatProps.suggestedYcbcrModel;
|
||||
ycbcrCreateInfo.ycbcrRange = formatProps.suggestedYcbcrRange;
|
||||
|
||||
ycbcrCreateInfo.components = {
|
||||
VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G,
|
||||
VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A};
|
||||
ycbcrCreateInfo.components = {
|
||||
VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G,
|
||||
VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A};
|
||||
|
||||
ycbcrCreateInfo.xChromaOffset = formatProps.suggestedXChromaOffset;
|
||||
ycbcrCreateInfo.yChromaOffset = formatProps.suggestedYChromaOffset;
|
||||
ycbcrCreateInfo.chromaFilter = VK_FILTER_LINEAR;
|
||||
ycbcrCreateInfo.forceExplicitReconstruction = VK_FALSE;
|
||||
ycbcrCreateInfo.xChromaOffset = formatProps.suggestedXChromaOffset;
|
||||
ycbcrCreateInfo.yChromaOffset = formatProps.suggestedYChromaOffset;
|
||||
ycbcrCreateInfo.chromaFilter = VK_FILTER_LINEAR;
|
||||
ycbcrCreateInfo.forceExplicitReconstruction = VK_FALSE;
|
||||
|
||||
VkExternalFormatANDROID extFormat{};
|
||||
extFormat.sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID;
|
||||
extFormat.externalFormat = formatProps.externalFormat;
|
||||
if (formatProps.format == VK_FORMAT_UNDEFINED) {
|
||||
ycbcrCreateInfo.pNext = &extFormat;
|
||||
}
|
||||
VkExternalFormatANDROID extFormat{};
|
||||
extFormat.sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID;
|
||||
extFormat.externalFormat = formatProps.externalFormat;
|
||||
if (formatProps.format == VK_FORMAT_UNDEFINED) {
|
||||
ycbcrCreateInfo.pNext = &extFormat;
|
||||
}
|
||||
|
||||
auto pfnCreate = (PFN_vkCreateSamplerYcbcrConversion)vkGetDeviceProcAddr(
|
||||
device, "vkCreateSamplerYcbcrConversion");
|
||||
if (pfnCreate) {
|
||||
if (pfnCreate(device, &ycbcrCreateInfo, nullptr,
|
||||
&outImage.ycbcrConversion) != VK_SUCCESS) {
|
||||
LOGE("Failed to create YCbCr conversion");
|
||||
return false;
|
||||
auto pfnCreate = (PFN_vkCreateSamplerYcbcrConversion)vkGetDeviceProcAddr(
|
||||
device, "vkCreateSamplerYcbcrConversion");
|
||||
if (pfnCreate) {
|
||||
if (pfnCreate(device, &ycbcrCreateInfo, nullptr,
|
||||
&outImage.ycbcrConversion) != VK_SUCCESS) {
|
||||
LOGE("Failed to create YCbCr conversion");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,6 +44,7 @@ struct VulkanImage {
|
||||
|
||||
class VulkanBufferImporter {
|
||||
public:
|
||||
static bool importHardwareBuffer(AHardwareBuffer *buffer,
|
||||
VulkanImage &outImage);
|
||||
static bool importHardwareBuffer(
|
||||
AHardwareBuffer *buffer, VulkanImage &outImage,
|
||||
VkSamplerYcbcrConversion existingConversion = VK_NULL_HANDLE);
|
||||
};
|
||||
@@ -0,0 +1,528 @@
|
||||
# 手持多帧超分辨率技术文档
|
||||
|
||||
> 基于论文 *"Handheld Multi-Frame Super-Resolution"*(Wronski et al., SIGGRAPH 2019)
|
||||
|
||||
---
|
||||
|
||||
## 1. 技术概述
|
||||
|
||||
本算法通过合并一组连拍的 RAW Bayer 图像,**跳过传统去马赛克(Demosaicing)步骤**,直接生成完整 RGB 图像。利用手持拍摄时自然存在的手部微颤(Hand Tremor),获得亚像素级的偏移覆盖,从而实现:
|
||||
|
||||
- **超分辨率**:恢复高于单帧像素分辨率的真实光学细节
|
||||
- **降噪**:多帧时域融合显著提升信噪比
|
||||
- **消除 Demosaicing 伪影**:避免拉链效应(Zipper)、摩尔纹(Moiré)、假色等
|
||||
|
||||
> [!IMPORTANT]
|
||||
> 该算法在 Google Pixel 手机上实测性能为 **每帧 12MP RAW ≈ 100ms**(Adreno 630 GPU),适合移动端实时处理。
|
||||
|
||||
---
|
||||
|
||||
## 2. 算法流程总览
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A["RAW Burst 输入<br/>(Bayer CFA 图像序列)"] --> B["选择基准帧<br/>(Base Frame)"]
|
||||
B --> C["帧对齐<br/>(Alignment)"]
|
||||
C --> D["局部梯度分析<br/>(Structure Tensor)"]
|
||||
D --> E["各向异性核构建<br/>(Anisotropic Kernels)"]
|
||||
C --> F["运动鲁棒性计算<br/>(Robustness Mask)"]
|
||||
E --> G["加权累积<br/>(Per-Channel Accumulation)"]
|
||||
F --> G
|
||||
G --> H["归一化输出<br/>(Full RGB Image)"]
|
||||
H --> I["后续 Pipeline<br/>(降噪/色彩校正/Tone Mapping)"]
|
||||
```
|
||||
|
||||
### 核心步骤
|
||||
|
||||
| 步骤 | 说明 | 输入 | 输出 |
|
||||
|------|------|------|------|
|
||||
| 1. 帧采集 | ZSL 模式连拍约 15 帧 RAW | 快门触发 | Bayer RAW burst |
|
||||
| 2. 帧对齐 | 分层块匹配 + Lucas-Kanade 精化 | 每帧 vs 基准帧 | 每 Tile 的亚像素对齐向量 |
|
||||
| 3. 核估计 | 梯度结构张量 → 各向异性高斯核 | 每帧的半分辨率亮度 | 核协方差矩阵 Ω |
|
||||
| 4. 鲁棒性 | 统计模型 + 运动先验 + 噪声校正 | 颜色差异 d, 标准差 σ | 每像素每帧的鲁棒性权重 R̂ |
|
||||
| 5. 累积合并 | 按通道加权累积并归一化 | 核权重 × 鲁棒性 × 像素值 | 完整 RGB 图像 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 帧对齐(Registration)
|
||||
|
||||
### 3.1 粗对齐:分层块匹配
|
||||
|
||||
构建每帧的图像金字塔,在有限窗口内搜索最相似 Tile。
|
||||
|
||||
**实施参数**:
|
||||
|
||||
| 参数 | 推荐值 | 说明 |
|
||||
|------|--------|------|
|
||||
| 金字塔层数 | 4-5 层 | 每层下采样 2× |
|
||||
| Tile 大小 Ts | 16×16 像素 | 对齐向量的空间分辨率 |
|
||||
| 搜索窗口 | ±4 像素 | 每层的搜索范围 |
|
||||
| 匹配度量 | SAD 或 SSD | 块差异计算 |
|
||||
|
||||
### 3.2 精对齐:Lucas-Kanade 光流
|
||||
|
||||
在块匹配结果基础上,执行 **3 次迭代** Lucas-Kanade 光流,获得亚像素精度对齐。
|
||||
|
||||
```
|
||||
// 伪代码:亚像素精化
|
||||
for iteration in 0..3:
|
||||
warp = applyAlignment(frame, currentAlignment)
|
||||
gradient = computeGradient(warp)
|
||||
residual = warp - baseFrame
|
||||
delta = solveLK(gradient, residual) // 最小二乘求解
|
||||
currentAlignment += delta
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> 论文作者曾尝试二次曲线拟合块匹配误差来估计亚像素偏移,但精度不足以支持超分辨率。Lucas-Kanade 方法在保持低计算成本的同时达到了必要精度。
|
||||
|
||||
---
|
||||
|
||||
## 4. 手持超分辨率的本质——亚像素覆盖
|
||||
|
||||
### 4.1 手部微颤特性
|
||||
|
||||
| 特性 | 数值 |
|
||||
|------|------|
|
||||
| 频率 | 8-12 Hz |
|
||||
| 角位移标准差 | ≈ 0.89 像素(86 次连拍实测) |
|
||||
| 方向分布 | 近似均匀各向同性 |
|
||||
|
||||
### 4.2 等分布定理(Equidistribution Theorem)
|
||||
|
||||
即使手部运动近似线性,整数像素对齐后的 **亚像素残差**(fractional part)仍近似均匀分布,这由 Weyl 等分布定理保证:
|
||||
|
||||
> 序列 {a, 2a, 3a, ... mod 1}(a 为无理数)是均匀分布的。
|
||||
|
||||
**实际验证**:论文在 16×16 Tile、20 组连拍序列上验证了亚像素偏移的均匀覆盖性。存在「像素锁定」(Pixel Locking)现象——即估计偏向整数像素值——但不影响整体覆盖。
|
||||
|
||||
### 4.3 超分辨率的两个前提条件
|
||||
|
||||
1. **输入帧必须存在混叠(Aliased)**:镜头的 Airy 斑直径 < 2 × 像素间距(采样率 < 2)
|
||||
2. **多帧之间必须有不同的亚像素偏移**:手部微颤天然提供
|
||||
|
||||
> [!NOTE]
|
||||
> 主流手机(iPhone X, Pixel 3)主摄的采样率约 1.5-1.8,满足混叠条件。Bayer CFA 使绿通道混叠增加 50%,红/蓝通道可达 2 倍。
|
||||
|
||||
---
|
||||
|
||||
## 5. 核回归合并(Kernel Regression Merge)
|
||||
|
||||
### 5.1 核心公式
|
||||
|
||||
对每个输出像素的每个颜色通道,合并公式为:
|
||||
|
||||
$$
|
||||
C(x, y) = \frac{\sum_n \sum_i c_{n,i} \cdot w_{n,i} \cdot \hat{R}_n}{\sum_n \sum_i w_{n,i} \cdot \hat{R}_n}
|
||||
$$
|
||||
|
||||
其中:
|
||||
- $n$ :帧索引
|
||||
- $i$ :3×3 邻域内的采样索引
|
||||
- $c_{n,i}$ :该帧该采样点的 Bayer 像素值(仅贡献对应颜色通道)
|
||||
- $w_{n,i}$ :核权重
|
||||
- $\hat{R}_n$ :该帧在该像素处的鲁棒性权重
|
||||
|
||||
### 5.2 各向异性高斯核
|
||||
|
||||
核权重使用二维非归一化各向异性高斯 RBF :
|
||||
|
||||
$$
|
||||
w_{n,i} = \exp\left(-\frac{1}{2} \mathbf{d}_i^T \Omega^{-1} \mathbf{d}_i\right)
|
||||
$$
|
||||
|
||||
其中:
|
||||
- $\mathbf{d}_i = [x_i - x_0, y_i - y_0]^T$ 是采样点到输出像素的偏移向量
|
||||
- $\Omega$ 是核协方差矩阵
|
||||
|
||||
### 5.3 核协方差矩阵的计算
|
||||
|
||||
#### 步骤 1:构建半分辨率亮度图
|
||||
|
||||
将 Bayer 图像每个 2×2 RGGB Quad 组合为一个亮度像素,得到半分辨率单通道图像。
|
||||
|
||||
#### 步骤 2:计算梯度结构张量
|
||||
|
||||
$$
|
||||
\hat{\Omega} = \begin{bmatrix} I_x^2 & I_x I_y \\ I_x I_y & I_y^2 \end{bmatrix}
|
||||
$$
|
||||
|
||||
在 3×3 颜色窗口内通过前向差分计算 $I_x$ 和 $I_y$。
|
||||
|
||||
#### 步骤 3:特征分解
|
||||
|
||||
对结构张量做特征分析,得到:
|
||||
- 两个正交方向向量 $\mathbf{e}_1, \mathbf{e}_2$
|
||||
- 两个特征值 $\lambda_1, \lambda_2$($\lambda_1 \geq \lambda_2$)
|
||||
|
||||
#### 步骤 4:构建核协方差
|
||||
|
||||
$$
|
||||
\Omega = [\mathbf{e}_1, \mathbf{e}_2] \begin{bmatrix} k_1 & 0 \\ 0 & k_2 \end{bmatrix} \begin{bmatrix} \mathbf{e}_1^T \\ \mathbf{e}_2^T \end{bmatrix}
|
||||
$$
|
||||
|
||||
其中 $k_1, k_2$ 由特征值驱动:
|
||||
|
||||
| 区域类型 | $\lambda_1$ | $\lambda_1/\lambda_2$ | 核形状 | 效果 |
|
||||
|----------|-----------|---------|--------|------|
|
||||
| 平坦区 | 小 | ≈ 1 | 大而圆 | 强降噪 |
|
||||
| 边缘 | 大 | >> 1 | 沿边拉长 | 沿边平滑,跨边保锐 |
|
||||
| 细节区 | 大 | ≈ 1 | 小而圆 | 增强分辨率 |
|
||||
|
||||
**核控制参数**(参考论文补充材料):
|
||||
|
||||
```
|
||||
// 伪代码:核参数计算
|
||||
featureStrength = sqrt(lambda1) // 主特征值
|
||||
anisotropy = lambda1 / max(lambda2, epsilon)
|
||||
|
||||
// 细节增强 vs 降噪权衡
|
||||
if featureStrength > detailThreshold:
|
||||
k_detail = 0.05 // 小核,增强分辨率
|
||||
else:
|
||||
k_detail = 0.5 // 大核,强降噪
|
||||
|
||||
// 各向异性控制
|
||||
k_stretch = 4.0 // 沿边方向拉伸因子
|
||||
k_shrink = 2.0 // 垂直边方向收缩因子
|
||||
|
||||
k1 = k_detail * k_stretch // 沿边方向(e1 方向)
|
||||
k2 = k_detail / k_shrink // 垂直边方向(e2 方向)
|
||||
```
|
||||
|
||||
> [!WARNING]
|
||||
> 当 `k_stretch = 1, k_shrink = 1`(各向同性核)时,边缘附近的微小对齐误差会导致严重的拉链伪影。推荐 `k_stretch = 4, k_shrink = 2`。
|
||||
|
||||
### 5.4 实施细节
|
||||
|
||||
- 结构张量在 **半分辨率** 计算以节省性能和抗噪
|
||||
- 核协方差值通过 **双线性插值** 上采样到全分辨率
|
||||
- 每个输出像素独立处理 9 个最近邻采样(3×3)
|
||||
- GPU 上采用 **Gather 模式**:每个输出像素独立处理一次
|
||||
|
||||
---
|
||||
|
||||
## 6. 运动鲁棒性模型(Motion Robustness)
|
||||
|
||||
### 6.1 核心问题
|
||||
|
||||
如何区分「混叠」(需要保留,用于超分辨率)和「对齐错误」(需要拒绝)?
|
||||
|
||||
### 6.2 统计鲁棒性模型
|
||||
|
||||
$$
|
||||
R = s \cdot \exp\left(-\frac{d^2}{\sigma^2}\right) - t
|
||||
$$
|
||||
|
||||
其中:
|
||||
- $d$ :基准帧与对齐帧之间的颜色差异
|
||||
- $\sigma$ :基准帧的局部空间标准差
|
||||
- $s, t$ :可调缩放和阈值参数
|
||||
|
||||
**三种情况的处理逻辑**:
|
||||
|
||||
| 条件 | 含义 | 处理方式 |
|
||||
|------|------|----------|
|
||||
| $d \ll \sigma$ | 差异远小于局部方差 | 合并(降噪) |
|
||||
| $d \approx \alpha \cdot \sigma$ | 差异接近局部方差的某个比例 | 合并(超分辨率) |
|
||||
| $d \gg \sigma$ | 差异远大于局部方差 | 拒绝(对齐错误/运动) |
|
||||
|
||||
### 6.3 Guide Image 构建
|
||||
|
||||
创建半分辨率 RGB Guide Image:
|
||||
|
||||
```
|
||||
// 伪代码:从 Bayer Quad 创建 Guide Pixel
|
||||
for each 2x2 Bayer Quad [R, Gr, Gb, B]:
|
||||
guide.R = R
|
||||
guide.G = (Gr + Gb) / 2.0
|
||||
guide.B = B
|
||||
```
|
||||
|
||||
### 6.4 噪声校正的局部统计量
|
||||
|
||||
RAW 图像的噪声是 **异方差高斯噪声**(Heteroscedastic Gaussian),方差是信号亮度的线性函数:
|
||||
|
||||
$$
|
||||
\text{Var}(noise) = \alpha \cdot \text{brightness} + \beta
|
||||
$$
|
||||
|
||||
其中 $\alpha$(slope)和 $\beta$(intercept)来自传感器噪声模型。
|
||||
|
||||
**校正流程**:
|
||||
|
||||
```
|
||||
// 1. 测量值(来自 3×3 邻域)
|
||||
sigma_ms = spatialStdDev(guideImage, 3x3)
|
||||
d_ms = colorDiff(baseGuide, alignedGuide)
|
||||
|
||||
// 2. 噪声模型预期值(通过蒙特卡洛预计算查找表)
|
||||
sigma_md = lookupNoiseStdDev(brightness, noiseModel)
|
||||
d_md = lookupNoiseDiff(brightness, noiseModel)
|
||||
|
||||
// 3. 噪声校正
|
||||
sigma = max(sigma_ms, sigma_md) // 下界截断
|
||||
d = d_ms * d_ms^2 / (d_ms^2 + d_md^2) // Wiener 收缩
|
||||
```
|
||||
|
||||
> [!IMPORTANT]
|
||||
> 噪声校正至关重要。在低光条件下,缺少噪声校正会导致大量正确对齐的帧被错误拒绝(噪声导致的差异 $d_{ms}$ 偏大),汇聚帧数不足,无法有效降噪。
|
||||
|
||||
### 6.5 运动先验(Motion Prior)
|
||||
|
||||
分析对齐向量场的 **局部变化**,判断是否存在局部运动:
|
||||
|
||||
$$
|
||||
M_x = \max_{j \in N_3} v_x(j) - \min_{j \in N_3} v_x(j)
|
||||
$$
|
||||
$$
|
||||
M_y = \max_{j \in N_3} v_y(j) - \min_{j \in N_3} v_y(j)
|
||||
$$
|
||||
$$
|
||||
M = \sqrt{M_x^2 + M_y^2}
|
||||
$$
|
||||
|
||||
判断逻辑:
|
||||
|
||||
```
|
||||
// 在 3×3 Tile 邻域内计算对齐向量的 span
|
||||
if M > M_threshold:
|
||||
// 局部运动或对齐失败 → 更严格的鲁棒性
|
||||
s_final = s
|
||||
else:
|
||||
// 纯相机运动,对齐可靠 → 更宽松的鲁棒性
|
||||
s_final = s * s // s^2,更宽松
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> 仅相机运动时,对齐场应平滑连续。局部运动或遮挡会导致对齐场在局部出现剧烈变化。
|
||||
|
||||
### 6.6 形态学精炼
|
||||
|
||||
在 5×5 窗口内取最小鲁棒性值:
|
||||
|
||||
$$
|
||||
\hat{R} = \min_{j \in N_5} R(j)
|
||||
$$
|
||||
|
||||
这确保了边缘附近的错误对齐区域也被正确拒绝。
|
||||
|
||||
---
|
||||
|
||||
## 7. 输出与后处理
|
||||
|
||||
### 7.1 输出格式
|
||||
|
||||
- 默认输出 **与输入相同分辨率** 的完整 RGB 图像
|
||||
- 可指定 **任意目标放大倍率**,无需额外重采样
|
||||
- 可保存为 Linear DNG 格式(非 CFA raw)
|
||||
|
||||
### 7.2 有效放大倍率
|
||||
|
||||
| 放大倍率 | 效果 | 说明 |
|
||||
|---------|------|------|
|
||||
| 1.0× | 替代 Demosaicing,消除伪影 | 最佳质量提升 |
|
||||
| 1.5× | 显著分辨率提升 | 与大多数手机光学匹配 |
|
||||
| 2.0× | 有限分辨率提升 | 接近光学极限 |
|
||||
| 3.0× | 无额外分辨率增益 | 受镜头 Airy 斑限制 |
|
||||
|
||||
### 7.3 后续 Pipeline
|
||||
|
||||
合并后的全 RGB 图像可直接进入标准处理流:
|
||||
1. 空间降噪
|
||||
2. 色彩校正(CCM)
|
||||
3. Tone Mapping
|
||||
4. 锐化(Unsharp Mask,推荐 σ = 3 像素)
|
||||
|
||||
---
|
||||
|
||||
## 8. 性能参数
|
||||
|
||||
### 8.1 计算性能
|
||||
|
||||
| 平台 | 固定开销 | 每帧每百万像素 | 内存 |
|
||||
|------|---------|--------------|------|
|
||||
| Adreno 630 (Mobile) | 15.4 ms | 7.8 ms/MPix | 22 MB/MPix |
|
||||
| GTX 980 (Desktop) | 0.83 ms | 0.4 ms/MPix | 22 MB/MPix |
|
||||
|
||||
**12MP × 15帧** 典型处理时间 (Adreno 630) ≈ 15.4 + 7.8 × 12 × 15 ≈ **1.4s**
|
||||
|
||||
### 8.2 关键优势
|
||||
|
||||
- 内存使用 **不随帧数增长**(在线处理方式)
|
||||
- 计算复杂度 **线性扩展**(像素数 × 帧数)
|
||||
- 比 DeepJoint + FRVSR 快 **数个数量级**
|
||||
|
||||
---
|
||||
|
||||
## 9. SNR 自适应调参
|
||||
|
||||
核的调参需根据 **基准帧的 SNR** 自动调整:
|
||||
|
||||
| SNR 范围 | 策略 | 核行为 |
|
||||
|----------|------|--------|
|
||||
| 高 SNR(> 30 dB) | 偏重超分辨率 | 小核,增强细节 |
|
||||
| 中 SNR(20-30 dB) | 平衡 | 中等核大小 |
|
||||
| 低 SNR(< 20 dB) | 偏重降噪 | 大核,强时域降噪 |
|
||||
|
||||
SNR 估计方式:
|
||||
|
||||
```
|
||||
avgBrightness = mean(baseFrame)
|
||||
noiseVariance = alpha * avgBrightness + beta // 噪声模型
|
||||
SNR_linear = avgBrightness / sqrt(noiseVariance)
|
||||
SNR_dB = 20 * log10(SNR_linear)
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> 论文指出在高 SNR 条件下,7 帧左右即可达到接近峰值质量(PSNR > 40 dB)。低 SNR 条件下 15 帧仍有持续的质量提升。
|
||||
|
||||
---
|
||||
|
||||
## 10. GPU Shader 实施架构
|
||||
|
||||
### 10.1 建议的 Compute Shader 分工
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
subgraph "每帧处理 (Per Frame)"
|
||||
A["Pass 1: 对齐<br/>(块匹配 + LK)"] --> B["Pass 2: 半分辨率<br/>亮度 + 梯度"]
|
||||
B --> C["Pass 3: 结构张量<br/>+ 核参数"]
|
||||
C --> D["Pass 4: Guide Image<br/>+ 局部统计"]
|
||||
D --> E["Pass 5: 鲁棒性<br/>计算"]
|
||||
E --> F["Pass 6: 加权累积<br/>(RGB 三通道)"]
|
||||
end
|
||||
subgraph "最终处理"
|
||||
F --> G["Pass 7: 归一化"]
|
||||
end
|
||||
```
|
||||
|
||||
### 10.2 GPU Buffer 设计
|
||||
|
||||
| Buffer | 尺寸 | 格式 | 说明 |
|
||||
|--------|------|------|------|
|
||||
| alignmentBuffer | (W/Ts) × (H/Ts) | float2 | 每 Tile 的亚像素对齐向量 |
|
||||
| tensorBuffer | (W/2) × (H/2) | float3 | 结构张量(Ix², IxIy, Iy²) |
|
||||
| kernelCovBuffer | W × H | float3 | 核协方差(k1, k2, angle) |
|
||||
| guideImage | (W/2) × (H/2) | float3 | 半分辨率 RGB Guide |
|
||||
| accumR/G/B | W_out × H_out | float2 | (加权和, 权重和) × 3 通道 |
|
||||
| robustnessBuffer | (W/2) × (H/2) | float | 每像素鲁棒性 |
|
||||
|
||||
### 10.3 核心累积 Shader 伪代码
|
||||
|
||||
```glsl
|
||||
// accumulate.comp — 对每帧执行
|
||||
layout(local_size_x = 16, local_size_y = 16) in;
|
||||
|
||||
void main() {
|
||||
ivec2 outPos = ivec2(gl_GlobalInvocationID.xy);
|
||||
vec2 outCenter = vec2(outPos) + 0.5; // 输出像素中心
|
||||
|
||||
// 获取该输出像素的核参数
|
||||
mat2 kernelCovInv = getKernelCovInverse(outPos);
|
||||
|
||||
// 获取该位置的对齐向量(双线性插值)
|
||||
vec2 alignment = sampleAlignment(outPos);
|
||||
|
||||
// 获取鲁棒性权重
|
||||
float robustness = sampleRobustness(outPos);
|
||||
|
||||
// 在对齐后的输入帧上查找 3×3 最近邻
|
||||
vec2 srcPos = outCenter + alignment;
|
||||
ivec2 srcBase = ivec2(floor(srcPos - 1.0));
|
||||
|
||||
for (int dy = 0; dy < 3; dy++) {
|
||||
for (int dx = 0; dx < 3; dx++) {
|
||||
ivec2 samplePos = srcBase + ivec2(dx, dy);
|
||||
|
||||
// 确定该 Bayer 像素的颜色通道
|
||||
int channel = getBayerChannel(samplePos);
|
||||
|
||||
// 计算偏移
|
||||
vec2 d = vec2(samplePos) + 0.5 - outCenter;
|
||||
|
||||
// 各向异性高斯核权重
|
||||
float w = exp(-0.5 * dot(d, kernelCovInv * d));
|
||||
|
||||
// 读取像素值
|
||||
float value = texelFetch(inputFrame, samplePos).r;
|
||||
|
||||
// 加权累积(按通道分离)
|
||||
accumColor[channel] += value * w * robustness;
|
||||
accumWeight[channel] += w * robustness;
|
||||
}
|
||||
}
|
||||
|
||||
// 写回累积 Buffer
|
||||
imageStore(accumR, outPos, accumR_old + vec4(accumR_new, 0,0,0));
|
||||
imageStore(accumG, outPos, accumG_old + vec4(accumG_new, 0,0,0));
|
||||
imageStore(accumB, outPos, accumB_old + vec4(accumB_new, 0,0,0));
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11. 三脚架/无运动场景处理
|
||||
|
||||
当陀螺仪检测到无运动时(如三脚架拍摄),可通过以下方式提供亚像素偏移:
|
||||
|
||||
1. **OIS 主动抖动**:控制光学防抖系统在拍摄期间做微小移动(已在 Google Pixel 上量产使用)
|
||||
2. **传感器移位**:控制传感器做亚像素级位移(类似 Sony/Pentax/Olympus 方案)
|
||||
|
||||
---
|
||||
|
||||
## 12. 已知局限与处理策略
|
||||
|
||||
| 局限 | 表现 | 处理策略 |
|
||||
|------|------|----------|
|
||||
| 严重局部运动 | 运动区域仅使用基准帧,质量退化为单帧 | 对低鲁棒性区域施加额外空间降噪,强度与合并帧数成反比 |
|
||||
| 孔径问题 | 边缘沿方向的错误对齐 | 各向异性核沿边拉伸 + 鲁棒性的形态学精炼 |
|
||||
| 高频场景变化 | 水面波纹、树叶微动等产生特征性高频伪影 | 可设计专用伪影检测与校正算法 |
|
||||
| 无运动 | 无亚像素覆盖 | OIS 主动抖动或传感器移位 |
|
||||
| 光学限制 | 超过采样率的放大无法获得额外分辨率 | 限制放大倍率 ≤ 1.5-2× |
|
||||
|
||||
---
|
||||
|
||||
## 13. 推荐实施参数汇总
|
||||
|
||||
| 参数 | 推荐值 | 说明 |
|
||||
|------|--------|------|
|
||||
| 连拍帧数 | 7-15 帧 | 高光 7 帧足够,低光用 15 帧 |
|
||||
| Tile 大小 | 16×16 | 对齐的空间粒度 |
|
||||
| 金字塔层数 | 4-5 | 粗到细对齐 |
|
||||
| LK 迭代次数 | 3 | 亚像素精化 |
|
||||
| 邻域大小 | 3×3 | 核回归采样邻域 |
|
||||
| k_stretch | 4.0 | 沿边方向核拉伸 |
|
||||
| k_shrink | 2.0 | 垂直边方向核收缩 |
|
||||
| 鲁棒性 min 窗口 | 5×5 | 形态学精炼 |
|
||||
| 目标放大倍率 | 1.0×-1.5× | 与手机光学系统匹配 |
|
||||
|
||||
---
|
||||
|
||||
## 14. 与现有项目集成建议
|
||||
|
||||
本项目已有多帧堆叠(Multi-frame Stacking)和 Vulkan 计算管线。以下是基于现有架构的集成路径:
|
||||
|
||||
### 14.1 替换现有 Merge 逻辑
|
||||
|
||||
将当前的简单加权平均合并替换为核回归合并:
|
||||
|
||||
1. **对齐模块**:复用或增强现有的帧对齐实现,添加 Lucas-Kanade 亚像素精化
|
||||
2. **结构张量**:新增 Compute Shader,在半分辨率亮度图上计算梯度结构张量
|
||||
3. **核参数**:新增 Compute Shader,执行特征分析并输出核协方差
|
||||
4. **鲁棒性**:新增 Compute Shader,实现统计鲁棒性模型 + 噪声校正
|
||||
5. **累积**:改造现有累积 Shader,添加各向异性核权重和按通道分离累积
|
||||
|
||||
### 14.2 与 RAW Pipeline 的协作
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A["RAW Burst 采集"] --> B["多帧超分辨率合并<br/>(本算法)"]
|
||||
B --> C["输出: Linear RGB"]
|
||||
C --> D["现有 RAW 处理<br/>(LibRaw / native-lib)"]
|
||||
D --> E["色彩校正 + Tone Mapping"]
|
||||
E --> F["最终 JPEG/HEIF"]
|
||||
```
|
||||
|
||||
> [!CAUTION]
|
||||
> 本算法直接从 RAW Bayer 输出完整 RGB,**完全跳过 LibRaw 的 Demosaicing 步骤**。需要确保后续 Pipeline 的输入格式适配为 Linear RGB 而非 CFA RAW。
|
||||
Reference in new issue
Block a user