{"record":{"id":"561687a4fd269de8","repo":"tonhowtf/omniget","slug":"a-sa-da-do-modelo-tem-valores-esperava","errorCode":null,"errorMessage":"a saída do modelo tem {} valores, esperava {}","messagePattern":"a saída do modelo tem (.+?) valores, esperava (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"src-tauri/omniget-core/src/core/tools/img_bg.rs","lineNumber":193,"sourceCode":"    let mut t = Array4::<f32>::zeros((1, 3, size, size));\n    for y in 0..size {\n        for x in 0..size {\n            let px = rgb.get_pixel(x as u32, y as u32).0;\n            for c in 0..3 {\n                t[[0, c, y, x]] = (px[c] as f32 * scale - p.mean[c]) / p.std[c];\n            }\n        }\n    }\n    t\n}\n\n/// Saída bruta do modelo → máscara em tons de cinza, normalizada por mín-máx.\n/// Saída constante (imagem toda fundo ou toda objeto) vira máscara zerada em\n/// vez de dividir por zero.\npub fn mask_from_raw(raw: &[f32], w: u32, h: u32) -> anyhow::Result<GrayImage> {\n    let n = (w as usize) * (h as usize);\n    if raw.len() < n {\n        return Err(anyhow!(\n            \"a saída do modelo tem {} valores, esperava {}\",\n            raw.len(),\n            n\n        ));\n    }\n    let slice = &raw[..n];\n    let mut mi = f32::INFINITY;\n    let mut ma = f32::NEG_INFINITY;\n    for v in slice {\n        if v.is_finite() {\n            mi = mi.min(*v);\n            ma = ma.max(*v);\n        }\n    }\n    let span = ma - mi;\n    let buf: Vec<u8> = if !span.is_finite() || span <= f32::EPSILON {\n        vec![0u8; n]\n    } else {","sourceCodeStart":175,"sourceCodeEnd":211,"githubUrl":"https://github.com/tonhowtf/omniget/blob/8600b91f4246848bac346874daa9e61c1fc5677a/src-tauri/omniget-core/src/core/tools/img_bg.rs#L175-L211","documentation":"`mask_from_raw` converts raw model output floats into a grayscale mask of exactly w*h pixels. If the raw buffer has fewer values than width*height, it refuses to build a differently-shaped image and throws 'a saída do modelo tem N valores, esperava M'. This guards against model/output tensor shape mismatches.","triggerScenarios":"Calling `mask_from_raw(raw, w, h)` where raw.len() < w*h — e.g. the segmentation model emitted a downsampled mask (smaller resolution) or a different batch/channel layout than the input image dimensions.","commonSituations":"Model weights expect a fixed input size (e.g. 320x320) but the image wasn't resized; output includes batch dimension making per-image slices shorter; dynamic input shapes with a mismatched mask interpolation step.","solutions":["Resize the model output mask to the image's w×h before calling (bilinear/nearest interpolation), or resize the input image to the model's expected size so output matches w*h.","Slice raw per-image if the output carries a batch dimension, then pass the correct w,h per image.","Verify which ONNX/model weights are loaded and their expected input/output shapes against the preprocessing code."],"exampleFix":"// before\nlet mask = mask_from_raw(&raw, img.width(), img.height())?; // 640x480 img, 320x320 output\n// after\nlet raw_mask = image_from_raw_f32(&raw, 320, 320);\nlet mask_resized = resize_gray(&raw_mask, img.width(), img.height());\nlet mask = mask_from_raw(mask_resized.as_raw(), img.width(), img.height())?;","handlingStrategy":"validation","validationCode":"let n = (w as usize) * (h as usize);\nif raw.len() < n {\n    eprintln!(\"saída do modelo menor que w*h; redimensione a máscara antes\");\n}","typeGuard":"fn mask_shape_matches(raw: &[f32], w: u32, h: u32) -> bool {\n    raw.len() >= (w as usize) * (h as usize)\n}","tryCatchPattern":"match mask_from_raw(&raw, w, h) {\n    Ok(mask) => use(mask),\n    Err(e) if e.to_string().contains(\"esperava\") => {\n        eprintln!(\"formato da saída do modelo incompatível: {e}\");\n        // resize mask to (w, h) and retry\n    }\n    Err(e) => return Err(e),\n}","preventionTips":["Resize inputs to the model's fixed expected size before inference","Slice per-image outputs when the model returns a batch dimension","Assert output tensor shape against w*h in CI with a golden model run"],"tags":["tensor-shape","ml","mask","rust"],"backgroundTag":"tensor-shape-mismatch","analyzedSha":"8600b91f4246848bac346874daa9e61c1fc5677a","analyzedAt":"2026-09-12T14:29:19.317Z","contentChangedAt":"2026-09-12T14:29:19.317Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}