feat: support Depth Anything V3 model and enhance bokeh rendering

This commit is contained in:
zhoubinjia committed 2026-04-30 14:21:30 +08:00
1 parent ae326f5dde
commit 922a45c198
6 files changed
+457 -94

No files matched your search

+6
View File
@@ -35,6 +35,12 @@ Photon Camera 是一款专注于静态摄影的开源 Android 相机应用,旨
* **AI 驱动**:集成基于高通优化的 **midas-v2** 深度检测本地 AI 模型。
* **精准测距**:提供较为准确的深度信息检测,实现自然的虚化过渡效果(持续优化中)。
新增支持Deep Anything V3
使用方法:
1. 访问https://huggingface.co/qualcomm/Depth-Anything-V3 下载 tflite版本,放入 assets中
2. DepthBokehProcessor中depthEstimator初始化改为使用DepthEstimator(appContext, DepthEstimator.MODEL_DEPTH_ANYTHING)
### 7. 幻影模式 (Phantom Mode)
* **画质飞跃**:直接调用系统相机进行采集,通过挂载 Photon Camera 的 LUT 引擎,完美绕过第三方相机 API 画面质量差、锐化过度的问题。
@@ -1085,16 +1085,58 @@ object Shaders {
const float PI = 3.14159265359;
const float GOLDEN_ANGLE = 2.39996323;
const int SAMPLES = 160;
const float LENS_GAMMA = 2.2;
float backgroundGap(float depth) {
return max(uFocusDepth - depth - 0.028, 0.0);
}
float computeCoc(float depth) {
// Align with BokehMe: Symmetric defocus for both foreground and background
float gap = max(abs(uFocusDepth - depth) - 0.028, 0.0);
float defocus = pow(gap, 1.45);
return clamp(defocus * uMaxBlurRadius * (1.0 / max(uAperture, 0.5)), 0.0, uMaxBlurRadius);
}
float apertureWeight(vec2 offsetPixels, float coc) {
vec2 p = offsetPixels / max(coc, 0.001);
float lenP = length(p);
if (lenP > 1.12) {
return 0.0;
}
// Six-blade aperture approximation. It keeps the bokeh from looking
// like a generic Gaussian/circular blur while retaining soft edges.
float blades = 6.0;
float sector = 2.0 * PI / blades;
float angle = atan(p.y, p.x) + PI / 6.0;
float polygonRadius = cos(sector * 0.5) / cos(mod(angle, sector) - sector * 0.5);
float inside = smoothstep(polygonRadius + 0.055, polygonRadius - 0.035, lenP);
float rim = smoothstep(0.58, 1.0, lenP);
return inside * (1.0 + rim * 0.22);
}
vec3 toLinear(vec3 color) {
return pow(clamp(color, 0.0, 1.0), vec3(LENS_GAMMA));
}
vec3 toDisplay(vec3 color) {
return pow(max(color, vec3(0.0)), vec3(1.0 / LENS_GAMMA));
}
void main() {
vec2 depthUV = clamp((uDepthMatrix * vec4(vTexCoord, 0.0, 1.0)).xy, 0.0, 1.0);
vec4 centerColor = texture(uInputTexture, vTexCoord);
float centerDepth = texture(uDepthTexture, depthUV).r;
float centerCoc = abs(centerDepth - uFocusDepth) * uMaxBlurRadius * (1.0 / uAperture);
centerCoc = clamp(centerCoc, 0.0, uMaxBlurRadius);
float centerBackgroundGap = backgroundGap(centerDepth);
// 1. 强力保护机制:对于清晰主体,保持 100% 锐度
float centerCoc = computeCoc(centerDepth);
// Match BokehMe's focus protection: keep only the narrow focus band
// sharp. Do not protect every foreground-side pixel by default, or
// background regions with imperfect depth will stop blurring.
if (centerCoc < 0.2) {
fragColor = centerColor;
return;
@@ -1102,7 +1144,7 @@ object Shaders {
// 2. 初始权重:赋予较高的权重以定性,防止背景渗色
float centerWeight = 6.0 / (centerCoc * 0.4 + 1.0);
vec3 accColor = centerColor.rgb * centerWeight;
vec3 accColor = toLinear(centerColor.rgb) * centerWeight;
float accWeight = centerWeight;
float softBase = max(3.0, uMaxBlurRadius * 0.1);
@@ -1114,6 +1156,7 @@ object Shaders {
vec2 offset = vec2(cos(theta), sin(theta)) * r * uTexelSize;
vec2 sampleUV = clamp(vTexCoord + offset, 0.0, 1.0);
vec2 offsetPixels = offset / uTexelSize;
float lod = log2(r * 0.3 + 1.5);
vec3 sColor = textureLod(uInputTexture, sampleUV, lod).rgb;
@@ -1126,36 +1169,48 @@ object Shaders {
float colorDist = distance(centerColor.rgb, sColor);
float colorSimilarity = smoothstep(0.15, 0.01, colorDist);
float rawCoc = abs(sDepth - uFocusDepth) * uMaxBlurRadius * (1.0 / uAperture);
float rawCoc = computeCoc(sDepth);
// 关键:如果颜色相似度高,则强制将采样点的 CoC 压低,视为主体保护区
float sCoc = mix(rawCoc, min(rawCoc, centerCoc), colorSimilarity);
sCoc = clamp(sCoc, 0.0, uMaxBlurRadius);
// 4. 重构权重逻辑
// 4. 重构权重逻辑 (Strict Occlusion Weighting)
// If sCoc > r, the sample's blur circle covers the center, so fW > 0.
float fW = smoothstep(r - softBase, r + softBase * 0.5, sCoc);
// If centerCoc > r, the center's blur circle covers the sample, so bW > 0.
float bW = smoothstep(r - softBase, r + softBase * 0.5, centerCoc);
float depthDiff = sDepth - centerDepth;
float isNearer = smoothstep(-0.1, 0.1, depthDiff);
// Tight transition: if it's 0.02 to 0.06 nearer, it's definitively foreground.
float isNearer = smoothstep(0.015, 0.055, depthDiff);
// 引入相似度加成,让主体边缘的像素更倾向于互相保护而不是混入背景
float weight = mix(bW * (1.1 - isNearer), fW, isNearer);
// If sample is nearer, it can ONLY contribute if its OWN blur circle reaches us (fW).
// If it's same depth or further, it contributes based on OUR blur circle reaching it (bW).
float weight = mix(bW, fW, isNearer);
// Enhance separation: boost weight if colors match (likely same object)
weight *= (1.0 + colorSimilarity * 0.8);
weight *= apertureWeight(offsetPixels, max(sCoc, centerCoc));
// Strict sharp edge protection: if the sample is foreground AND sharp,
// absolutely reject it to prevent ghosts.
float isSharpForeground = isNearer * (1.0 - smoothstep(0.5, 2.5, sCoc));
weight *= (1.0 - isSharpForeground);
if (weight > 0.0001) {
float luma = dot(sColor, vec3(0.2126, 0.7152, 0.0722));
float hdrBoost = 1.0 + pow(max(0.0, luma - 0.75), 2.0) * 4.0 * smoothstep(1.0, 5.0, sCoc);
vec3 sLinear = toLinear(sColor);
float luma = dot(sLinear, vec3(0.2126, 0.7152, 0.0722));
float hdrBoost = 1.0 + pow(max(0.0, luma - 0.52), 2.0) * 3.2 * smoothstep(1.0, 5.0, sCoc);
float edge = smoothstep(0.7, 1.05, r / max(sCoc, 0.1));
float ring = 1.0 + edge * 0.4 * smoothstep(1.5, 5.0, sCoc);
float ring = 1.0 + edge * 0.28 * smoothstep(1.5, 5.0, sCoc);
float fw = weight * ring;
accColor += sColor * hdrBoost * fw;
accColor += sLinear * hdrBoost * fw;
accWeight += fw;
}
}
vec3 finalColor = accWeight > 0.001 ? (accColor / accWeight) : centerColor.rgb;
vec3 finalColor = accWeight > 0.001 ? toDisplay(accColor / accWeight) : centerColor.rgb;
finalColor = clamp(finalColor, 0.0, 1.0);
fragColor = vec4(finalColor, centerColor.a);
@@ -8,57 +8,68 @@ import org.tensorflow.lite.DataType
import org.tensorflow.lite.Interpreter
import org.tensorflow.lite.gpu.CompatibilityList
import org.tensorflow.lite.gpu.GpuDelegate
import org.tensorflow.lite.nnapi.NnApiDelegate
import org.tensorflow.lite.support.common.FileUtil
import org.tensorflow.lite.support.common.ops.NormalizeOp
import org.tensorflow.lite.support.image.ImageProcessor
import org.tensorflow.lite.support.image.TensorImage
import org.tensorflow.lite.support.image.ops.ResizeOp
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer
import org.tensorflow.lite.nnapi.NnApiDelegate
import java.nio.ByteBuffer
import java.nio.ByteOrder
class DepthEstimator(context: Context) {
class DepthEstimator(
context: Context,
private val modelAssetName: String = MODEL_MIDAS
) {
private var interpreter: Interpreter? = null
private var gpuDelegate: GpuDelegate? = null
private var nnApiDelegate: NnApiDelegate? = null
private var isInitialized = false
// Input shape for Midas-v2 is typically [1, 256, 256, 3]
private val inputSize = 256
// Output shape is [1, 256, 256, 1] for depth map
private val outputSize = 256
private var inputWidth = 256
private var inputHeight = 256
private var outputWidth = 256
private var outputHeight = 256
private var inputChannelsFirst = false
init {
try {
val modelFile = StartupTrace.measure("DepthEstimator.loadMappedFile") {
FileUtil.loadMappedFile(context, "midas.tflite")
val modelFile = StartupTrace.measure("DepthEstimator.loadMappedFile.$modelAssetName") {
FileUtil.loadMappedFile(context, modelAssetName)
}
// Try GPU
val gpuOptions = Interpreter.Options()
val compatList = StartupTrace.measure("DepthEstimator.CompatibilityList()") {
CompatibilityList()
}
gpuDelegate = StartupTrace.measure("DepthEstimator.GpuDelegate()") {
if (compatList.isDelegateSupportedOnThisDevice) {
val delegateOptions = compatList.bestOptionsForThisDevice
GpuDelegate(delegateOptions)
} else {
GpuDelegate()
if (modelAssetName != MODEL_DEPTH_ANYTHING) {
// Try GPU. Depth Anything V2 is skipped here because the TFLite
// GPU delegate can compile it but return a constant depth map on
// some Qualcomm devices.
val gpuOptions = Interpreter.Options()
val compatList = StartupTrace.measure("DepthEstimator.CompatibilityList()") {
CompatibilityList()
}
}
StartupTrace.measure("DepthEstimator.gpuOptions.addDelegate") {
gpuOptions.addDelegate(gpuDelegate)
}
try {
interpreter = StartupTrace.measure("DepthEstimator.Interpreter(GPU)") {
Interpreter(modelFile, gpuOptions)
gpuDelegate = StartupTrace.measure("DepthEstimator.GpuDelegate()") {
if (compatList.isDelegateSupportedOnThisDevice) {
val delegateOptions = compatList.bestOptionsForThisDevice
GpuDelegate(delegateOptions)
} else {
GpuDelegate()
}
}
isInitialized = true
PLog.d(TAG, "Using GPU Delegate for Depth Estimator")
} catch (e: Exception) {
PLog.w(TAG, "Failed to initialize GPU delegate, falling back to NNAPI", e)
gpuDelegate?.close()
gpuDelegate = null
StartupTrace.measure("DepthEstimator.gpuOptions.addDelegate") {
gpuOptions.addDelegate(gpuDelegate)
}
try {
interpreter = StartupTrace.measure("DepthEstimator.Interpreter(GPU)") {
Interpreter(modelFile, gpuOptions)
}
isInitialized = true
PLog.d(TAG, "Using GPU Delegate for Depth Estimator: $modelAssetName")
} catch (e: Exception) {
PLog.w(TAG, "Failed to initialize GPU delegate, falling back to NNAPI", e)
gpuDelegate?.close()
gpuDelegate = null
}
} else {
PLog.d(TAG, "Skipping GPU Delegate for Depth Anything V2; trying NNAPI first")
}
// Try NNAPI (NPU) if GPU failed or not supported
@@ -75,7 +86,7 @@ class DepthEstimator(context: Context) {
Interpreter(modelFile, nnApiOptions)
}
isInitialized = true
PLog.d(TAG, "Using NNAPI (NPU) for Depth Estimator")
PLog.d(TAG, "Using NNAPI (NPU) for Depth Estimator: $modelAssetName")
} catch (e: Exception) {
PLog.w(TAG, "Failed to initialize NNAPI delegate, falling back to CPU", e)
nnApiDelegate?.close()
@@ -91,21 +102,25 @@ class DepthEstimator(context: Context) {
Interpreter(modelFile, cpuOptions)
}
isInitialized = true
PLog.d(TAG, "Using CPU for Depth Estimator")
PLog.d(TAG, "Using CPU for Depth Estimator: $modelAssetName")
}
interpreter?.let {
updateTensorDimensions(it)
}
} catch (e: Exception) {
PLog.e(TAG, "Error initializing DepthEstimator", e)
PLog.e(TAG, "Error initializing DepthEstimator: $modelAssetName", e)
}
}
/**
* Estimates depth for the given bitmap.
* @param inputBitmap Original image bitmap.
* @return Depth map bitmap of size 256x256, or null if failed.
* @return Depth map bitmap at the model output resolution, or null if failed.
*/
fun estimateDepth(inputBitmap: Bitmap): Bitmap? {
if (!isInitialized || interpreter == null) {
PLog.e(TAG, "DepthEstimator is not initialized.")
PLog.e(TAG, "DepthEstimator is not initialized: $modelAssetName")
return null
}
@@ -117,73 +132,204 @@ class DepthEstimator(context: Context) {
val outputDataType = outputTensor.dataType()
// 2. Preprocess the input image
val imageProcessor = ImageProcessor.Builder()
.add(ResizeOp(inputSize, inputSize, ResizeOp.ResizeMethod.BILINEAR))
.build()
var tensorImage = TensorImage(inputDataType)
tensorImage.load(inputBitmap)
tensorImage = imageProcessor.process(tensorImage)
val inputBuffer = if (modelAssetName == MODEL_DEPTH_ANYTHING) {
createDepthAnythingInputBuffer(inputBitmap, inputDataType)
} else {
val imageProcessor = buildImageProcessor()
var tensorImage = TensorImage(inputDataType)
tensorImage.load(inputBitmap)
tensorImage = imageProcessor.process(tensorImage)
tensorImage.buffer
}
// 3. Prepare the output buffer
val outputBuffer = TensorBuffer.createFixedSize(outputTensor.shape(), outputDataType)
// 4. Run inference
interpreter?.run(tensorImage.buffer, outputBuffer.buffer)
interpreter?.run(inputBuffer, outputBuffer.buffer)
// 5. Post-process to Bitmap (Grayscale)
return if (outputDataType == DataType.FLOAT32) {
convertOutputToBitmap(outputBuffer.floatArray)
convertOutputToBitmap(outputBuffer.floatArray, outputWidth, outputHeight)
} else {
// If quantized output, convert to float first or handle UINT8 directly
val floatArray = FloatArray(outputBuffer.flatSize)
if (outputDataType == DataType.UINT8) {
if (outputDataType == DataType.UINT8 || outputDataType == DataType.INT8) {
val byteBuffer = outputBuffer.buffer
byteBuffer.rewind()
val bytes = ByteArray(outputBuffer.flatSize)
byteBuffer.get(bytes)
for (i in bytes.indices) {
floatArray[i] = (bytes[i].toInt() and 0xFF).toFloat()
floatArray[i] = if (outputDataType == DataType.UINT8) {
(bytes[i].toInt() and 0xFF).toFloat()
} else {
bytes[i].toFloat()
}
}
}
convertOutputToBitmap(floatArray)
convertOutputToBitmap(floatArray, outputWidth, outputHeight)
}
} catch (e: Exception) {
PLog.e(TAG, "Error during depth estimation", e)
PLog.e(TAG, "Error during depth estimation: $modelAssetName", e)
return null
}
}
private fun buildImageProcessor(): ImageProcessor {
val builder = ImageProcessor.Builder()
.add(ResizeOp(inputHeight, inputWidth, ResizeOp.ResizeMethod.BILINEAR))
if (modelAssetName == MODEL_DEPTH_ANYTHING) {
builder
.add(NormalizeOp(0.0f, 255.0f))
.add(
NormalizeOp(
floatArrayOf(0.485f, 0.456f, 0.406f),
floatArrayOf(0.229f, 0.224f, 0.225f)
)
)
}
return builder.build()
}
private fun createDepthAnythingInputBuffer(inputBitmap: Bitmap, inputDataType: DataType): ByteBuffer {
if (inputDataType != DataType.FLOAT32) {
throw IllegalArgumentException("Depth Anything V2 input type is not FLOAT32: $inputDataType")
}
val resized = if (inputBitmap.width == inputWidth && inputBitmap.height == inputHeight) {
inputBitmap
} else {
Bitmap.createScaledBitmap(inputBitmap, inputWidth, inputHeight, true)
}
val pixels = IntArray(inputWidth * inputHeight)
resized.getPixels(pixels, 0, inputWidth, 0, 0, inputWidth, inputHeight)
if (resized !== inputBitmap) {
resized.recycle()
}
val buffer = ByteBuffer.allocateDirect(inputWidth * inputHeight * 3 * 4)
.order(ByteOrder.nativeOrder())
val mean = floatArrayOf(0.485f, 0.456f, 0.406f)
val std = floatArrayOf(0.229f, 0.224f, 0.225f)
val skipNormalization = modelAssetName == MODEL_DEPTH_ANYTHING
fun normalized(pixel: Int, channel: Int): Float {
val value = when (channel) {
0 -> (pixel shr 16) and 0xFF
1 -> (pixel shr 8) and 0xFF
else -> pixel and 0xFF
} / 255.0f
if (skipNormalization) {
return value
}
return (value - mean[channel]) / std[channel]
}
if (inputChannelsFirst) {
for (channel in 0 until 3) {
for (pixel in pixels) {
buffer.putFloat(normalized(pixel, channel))
}
}
} else {
for (pixel in pixels) {
buffer.putFloat(normalized(pixel, 0))
buffer.putFloat(normalized(pixel, 1))
buffer.putFloat(normalized(pixel, 2))
}
}
buffer.rewind()
return buffer
}
/**
* Converts a float array output [256*256] to a Grayscale Bitmap.
* Converts a float array output to a Grayscale Bitmap.
*/
private fun convertOutputToBitmap(outputArray: FloatArray): Bitmap {
// Find min and max for normalization
var min = Float.MAX_VALUE
var max = Float.MIN_VALUE
private fun convertOutputToBitmap(outputArray: FloatArray, width: Int, height: Int): Bitmap {
if (outputArray.isEmpty()) return Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val validValues = FloatArray(outputArray.size)
var validCount = 0
for (value in outputArray) {
if (value < min) min = value
if (value > max) max = value
if (value.isFinite()) {
validValues[validCount++] = value
}
}
if (validCount == 0) {
PLog.e(TAG, "Depth output has no finite values: $modelAssetName")
return Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
}
validValues.sort(0, validCount)
val clipPercentile = 0.02f
val loIndex = (validCount * clipPercentile).toInt().coerceIn(0, validCount - 1)
val hiIndex = (validCount * (1.0f - clipPercentile)).toInt().coerceIn(0, validCount - 1)
var min = validValues[loIndex]
var max = validValues[hiIndex]
if (min >= max) {
min = validValues[0]
max = validValues[validCount - 1]
}
val range = max - min
val finalRange = if (range == 0f) 1f else range // avoid division by zero
val finalRange = if (range <= 0f) 1f else range // avoid division by zero
PLog.d(TAG, "Depth output range: asset=$modelAssetName min=$min max=$max range=$range valid=$validCount")
val pixels = IntArray(outputSize * outputSize)
val pixels = IntArray(width * height)
val limit = minOf(outputArray.size, pixels.size)
for (i in 0 until limit) {
// Normalize to [0, 255]
val normalized = ((outputArray[i] - min) / finalRange * 255f).toInt().coerceIn(0, 255)
val value = if (outputArray[i].isFinite()) outputArray[i] else min
val normalized = ((value - min) / finalRange * 255f).toInt().coerceIn(0, 255)
// Create a grayscale color (ARGB)
pixels[i] = (0xFF shl 24) or (normalized shl 16) or (normalized shl 8) or normalized
}
val bitmap = Bitmap.createBitmap(outputSize, outputSize, Bitmap.Config.ARGB_8888)
bitmap.setPixels(pixels, 0, outputSize, 0, 0, outputSize, outputSize)
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
bitmap.setPixels(pixels, 0, width, 0, 0, width, height)
return bitmap
}
private fun updateTensorDimensions(interpreter: Interpreter) {
val inputShape = interpreter.getInputTensor(0).shape()
val outputShape = interpreter.getOutputTensor(0).shape()
inputChannelsFirst = inputShape.size == 4 && inputShape[1] == 3
if (inputShape.size == 4 && inputShape[3] == 3) {
inputHeight = inputShape[1]
inputWidth = inputShape[2]
} else if (inputChannelsFirst) {
inputHeight = inputShape[2]
inputWidth = inputShape[3]
} else {
PLog.w(TAG, "Unexpected depth input shape for $modelAssetName: ${inputShape.contentToString()}")
}
val outputDims = outputShape.filter { it > 1 }
if (outputDims.size >= 2) {
outputHeight = outputDims[outputDims.size - 2]
outputWidth = outputDims[outputDims.size - 1]
} else if (outputDims.size == 1) {
val side = kotlin.math.sqrt(outputDims[0].toDouble()).toInt()
if (side * side == outputDims[0]) {
outputHeight = side
outputWidth = side
}
}
PLog.d(
TAG,
"Depth model ready: asset=$modelAssetName input=${inputWidth}x$inputHeight output=${outputWidth}x$outputHeight inputLayout=${if (inputChannelsFirst) "NCHW" else "NHWC"} inputType=${interpreter.getInputTensor(0).dataType()} outputType=${interpreter.getOutputTensor(0).dataType()} inputShape=${inputShape.contentToString()} outputShape=${outputShape.contentToString()}"
)
}
fun close() {
interpreter?.close()
interpreter = null
@@ -196,5 +342,7 @@ class DepthEstimator(context: Context) {
companion object {
private const val TAG = "DepthEstimator"
const val MODEL_MIDAS = "midas.tflite"
const val MODEL_DEPTH_ANYTHING = "MGC/depth_anything_v3.tflite"
}
}
@@ -0,0 +1,120 @@
package com.hinnka.mycamera.processor
import android.graphics.Bitmap
import com.hinnka.mycamera.utils.PLog
import kotlin.math.max
import kotlin.math.pow
/**
* Adapts relative monocular depth for the background-first bokeh renderer.
*
* The renderer assumes a disparity-style map where larger values are closer to
* camera and background is lower than the focused subject. Monocular depth
* models can flip that polarity image-by-image, so score both directions before
* rendering.
*/
internal object DepthBokehDepthPreprocessor {
private const val TAG = "DepthBokehDepthPreprocessor"
private const val FOCUS_POINT_RADIUS = 0.045f
private const val FOCUS_PROTECT_WIDTH = 0.028f
private const val BACKGROUND_BLUR_GAMMA = 1.45f
private const val INVERT_SCORE_MARGIN = 1.18f
data class Result(
val depthMap: Bitmap,
val focusDepth: Float,
val inverted: Boolean,
val normalScore: Float,
val invertedScore: Float
)
fun prepare(depthMap: Bitmap, focusX: Float, focusY: Float): Result {
val width = depthMap.width
val height = depthMap.height
val pixels = IntArray(width * height)
depthMap.getPixels(pixels, 0, width, 0, 0, width, height)
val values = FloatArray(pixels.size)
val invertedValues = FloatArray(pixels.size)
for (i in pixels.indices) {
val value = ((pixels[i] shr 16) and 0xFF) / 255.0f
values[i] = value
invertedValues[i] = 1.0f - value
}
val normalFocus = estimateFocusDepth(values, width, height, focusX, focusY)
val invertedFocus = estimateFocusDepth(invertedValues, width, height, focusX, focusY)
val normalScore = scoreBackgroundPotential(values, normalFocus)
val invertedScore = scoreBackgroundPotential(invertedValues, invertedFocus)
val shouldInvert = invertedScore > normalScore * INVERT_SCORE_MARGIN
if (!shouldInvert) {
return Result(
depthMap = depthMap,
focusDepth = normalFocus,
inverted = false,
normalScore = normalScore,
invertedScore = invertedScore
)
}
val invertedPixels = IntArray(pixels.size)
for (i in invertedPixels.indices) {
val gray = (invertedValues[i] * 255.0f).toInt().coerceIn(0, 255)
invertedPixels[i] = (0xFF shl 24) or (gray shl 16) or (gray shl 8) or gray
}
val invertedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
invertedBitmap.setPixels(invertedPixels, 0, width, 0, 0, width, height)
PLog.d(
TAG,
"Depth polarity inverted for background bokeh: normalScore=$normalScore invertedScore=$invertedScore"
)
return Result(
depthMap = invertedBitmap,
focusDepth = invertedFocus,
inverted = true,
normalScore = normalScore,
invertedScore = invertedScore
)
}
private fun estimateFocusDepth(
values: FloatArray,
width: Int,
height: Int,
focusX: Float,
focusY: Float
): Float {
val centerX = (focusX.coerceIn(0f, 1f) * (width - 1)).toInt()
val centerY = (focusY.coerceIn(0f, 1f) * (height - 1)).toInt()
val radius = max((minOf(width, height) * FOCUS_POINT_RADIUS).toInt(), 3)
val samples = ArrayList<Float>((radius * 2 + 1) * (radius * 2 + 1))
val xStart = max(centerX - radius, 0)
val xEnd = minOf(centerX + radius, width - 1)
val yStart = max(centerY - radius, 0)
val yEnd = minOf(centerY + radius, height - 1)
for (y in yStart..yEnd) {
val rowOffset = y * width
for (x in xStart..xEnd) {
samples.add(values[rowOffset + x])
}
}
if (samples.isEmpty()) {
return 0.5f
}
samples.sort()
return samples[samples.size / 2]
}
private fun scoreBackgroundPotential(values: FloatArray, focusDepth: Float): Float {
var sum = 0.0
for (value in values) {
val backgroundGap = max(focusDepth - value - FOCUS_PROTECT_WIDTH, 0.0f)
sum += backgroundGap.pow(BACKGROUND_BLUR_GAMMA).toDouble()
}
return (sum / values.size).toFloat()
}
}
@@ -5,6 +5,7 @@ import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.hinnka.mycamera.gallery.GalleryManager
import com.hinnka.mycamera.ml.DepthEstimator
import com.hinnka.mycamera.utils.PLog
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
@@ -14,10 +15,15 @@ import kotlinx.coroutines.sync.withLock
* and realistic bokeh convolution.
*/
class DepthBokehProcessor(context: Context) {
companion object {
private const val TAG = "DepthBokehProcessor"
}
private val appContext = context.applicationContext
private val processor = OglBokehProcessor()
private val depthEstimator by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
DepthEstimator(appContext)
// DepthEstimator(appContext, DepthEstimator.MODEL_DEPTH_ANYTHING)
DepthEstimator(appContext, DepthEstimator.MODEL_MIDAS)
}
private val mutex = Mutex()
@@ -66,9 +72,18 @@ class DepthBokehProcessor(context: Context) {
var result: Bitmap? = null
if (depthMap != null) {
val preparedDepth = DepthBokehDepthPreprocessor.prepare(
depthMap,
focusX ?: 0.5f,
focusY ?: 0.5f
)
PLog.d(
TAG,
"Prepared bokeh depth: inverted=${preparedDepth.inverted} focusDepth=${preparedDepth.focusDepth} normalScore=${preparedDepth.normalScore} invertedScore=${preparedDepth.invertedScore}"
)
result = processor.applyBokeh(
originalImage,
depthMap,
preparedDepth.depthMap,
focusX ?: 0.5f,
focusY ?: 0.5f,
aperture
@@ -38,10 +38,16 @@ class OglBokehProcessor {
initGL()
val inputTex = createTexture(originalImage, mipmap = true)
val lowResDepthTex = createTexture(lowResDepthMap)
val lowResDepthTex = createTexture(lowResDepthMap, filterNearest = false, mipmap = true)
var finalDepthTex = lowResDepthTex
val fbo = IntArray(1)
GLES30.glGenFramebuffers(1, fbo, 0)
var lowResCoeffTex = IntArray(1)
var highResDepthTex = IntArray(1)
// Step 1: FGF Coefficients (Run at low resolution)
val lowResCoeffTex = IntArray(1)
GLES30.glGenTextures(1, lowResCoeffTex, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, lowResCoeffTex[0])
// Use RGB16F to store (a, b, mean_I)
@@ -49,8 +55,6 @@ class OglBokehProcessor {
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
val fbo = IntArray(1)
GLES30.glGenFramebuffers(1, fbo, 0)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, fbo[0])
GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, lowResCoeffTex[0], 0)
@@ -71,7 +75,6 @@ class OglBokehProcessor {
drawQuad(fgfCoeffProgramId)
// Step 2: FGF Apply (Generate High-Res Refined Depth)
val highResDepthTex = IntArray(1)
GLES30.glGenTextures(1, highResDepthTex, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, highResDepthTex[0])
GLES30.glTexImage2D(GLES30.GL_TEXTURE_2D, 0, GLES30.GL_R8, originalImage.width, originalImage.height, 0, GLES30.GL_RED, GLES30.GL_UNSIGNED_BYTE, null)
@@ -90,12 +93,14 @@ class OglBokehProcessor {
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, lowResCoeffTex[0])
GLES30.glUniform1i(GLES30.glGetUniformLocation(fgfApplyProgramId, "uLowResCoeffs"), 1)
// Pass the texel size of the low-res coefficient texture for guidance-aware upsampling
GLES30.glUniform2f(GLES30.glGetUniformLocation(fgfApplyProgramId, "uLowResTexelSize"), 1.0f / lowResDepthMap.width, 1.0f / lowResDepthMap.height)
drawQuad(fgfApplyProgramId)
finalDepthTex = highResDepthTex[0]
// Step 3: Apply Bokeh
val outputTex = IntArray(1)
GLES30.glGenTextures(1, outputTex, 0)
@@ -115,7 +120,7 @@ class OglBokehProcessor {
GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehProgramId, "uInputTexture"), 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE1)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, highResDepthTex[0])
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, finalDepthTex)
GLES30.glUniform1i(GLES30.glGetUniformLocation(bokehProgramId, "uDepthTexture"), 1)
GLES30.glUniform1f(GLES30.glGetUniformLocation(bokehProgramId, "uMaxBlurRadius"), originalImage.width.toFloat() / 24.0f)
@@ -155,11 +160,25 @@ class OglBokehProcessor {
}
private fun sampleDepth(depthMap: Bitmap, x: Float, y: Float): Float {
val px = (x * depthMap.width).toInt().coerceIn(0, depthMap.width - 1)
val py = (y * depthMap.height).toInt().coerceIn(0, depthMap.height - 1)
val color = depthMap.getPixel(px, py)
// Assume depth is in R channel
return (color shr 16 and 0xFF) / 255.0f
val px = (x * (depthMap.width - 1)).toInt().coerceIn(0, depthMap.width - 1)
val py = (y * (depthMap.height - 1)).toInt().coerceIn(0, depthMap.height - 1)
val radius = maxOf((minOf(depthMap.width, depthMap.height) * 0.045f).toInt(), 3)
val samples = ArrayList<Float>((radius * 2 + 1) * (radius * 2 + 1))
val xStart = maxOf(px - radius, 0)
val xEnd = minOf(px + radius, depthMap.width - 1)
val yStart = maxOf(py - radius, 0)
val yEnd = minOf(py + radius, depthMap.height - 1)
for (sampleY in yStart..yEnd) {
for (sampleX in xStart..xEnd) {
val color = depthMap.getPixel(sampleX, sampleY)
samples.add(((color shr 16) and 0xFF) / 255.0f)
}
}
if (samples.isEmpty()) return 0.5f
samples.sort()
return samples[samples.size / 2]
}
private fun createTexture(bitmap: Bitmap, filterNearest: Boolean = false, mipmap: Boolean = false): Int {