MCPcopy Create free account
hub / github.com/0xShug0/audio.cpp / sam_image_preprocess

Function sam_image_preprocess

external/ggml/examples/sam/sam.cpp:443–505  ·  view source on GitHub ↗

ref: https://github.com/facebookresearch/segment-anything/blob/efeab7296ab579d4a261e554eca80faf6b33924a/segment_anything/modeling/sam.py#L164 resize largest dimension to 1024 normalize: x = (x - mean) / std mean = [123.675, 116.28, 103.53] std = [58.395, 57.12, 57.375] TODO: why are these hardcoded !? pad to 1024x1024 TODO: for some reason, this is not numerically identical to pytorch's interpola

Source from the content-addressed store, hash-verified

441// pad to 1024x1024
442// TODO: for some reason, this is not numerically identical to pytorch's interpolation
443bool sam_image_preprocess(const sam_image_u8 & img, sam_image_f32 & res) {
444 const int nx = img.nx;
445 const int ny = img.ny;
446
447 const int nx2 = 1024;
448 const int ny2 = 1024;
449
450 res.nx = nx2;
451 res.ny = ny2;
452 res.data.resize(3*nx2*ny2);
453
454 const float scale = std::max(nx, ny) / 1024.0f;
455
456 fprintf(stderr, "%s: scale = %f\n", __func__, scale);
457
458 const int nx3 = int(nx/scale + 0.5f);
459 const int ny3 = int(ny/scale + 0.5f);
460
461 const float m3[3] = { 123.675f, 116.280f, 103.530f };
462 const float s3[3] = { 58.395f, 57.120f, 57.375f };
463
464 for (int y = 0; y < ny3; y++) {
465 for (int x = 0; x < nx3; x++) {
466 for (int c = 0; c < 3; c++) {
467 // linear interpolation
468 const float sx = (x + 0.5f)*scale - 0.5f;
469 const float sy = (y + 0.5f)*scale - 0.5f;
470
471 const int x0 = std::max(0, (int) std::floor(sx));
472 const int y0 = std::max(0, (int) std::floor(sy));
473
474 const int x1 = std::min(x0 + 1, nx - 1);
475 const int y1 = std::min(y0 + 1, ny - 1);
476
477 const float dx = sx - x0;
478 const float dy = sy - y0;
479
480 const int j00 = 3*(y0*nx + x0) + c;
481 const int j01 = 3*(y0*nx + x1) + c;
482 const int j10 = 3*(y1*nx + x0) + c;
483 const int j11 = 3*(y1*nx + x1) + c;
484
485 const float v00 = img.data[j00];
486 const float v01 = img.data[j01];
487 const float v10 = img.data[j10];
488 const float v11 = img.data[j11];
489
490 const float v0 = v00*(1.0f - dx) + v01*dx;
491 const float v1 = v10*(1.0f - dx) + v11*dx;
492
493 const float v = v0*(1.0f - dy) + v1*dy;
494
495 const uint8_t v2 = std::min(std::max(std::round(v), 0.0f), 255.0f);
496
497 const int i = 3*(y*nx3 + x) + c;
498
499 res.data[i] = (float(v2) - m3[c]) / s3[c];
500 }

Callers 1

mainFunction · 0.85

Calls 3

maxFunction · 0.85
minFunction · 0.85
resizeMethod · 0.45

Tested by

no test coverage detected