Replicate C++ sam3_preprocess_image exactly. C++ does: 1. Bilinear resize to img_size x img_size (half-pixel center mapping) 2. Quantize back to uint8 with rounding 3. Normalize: (pixel/255.0 - 0.5) / 0.5 4. Layout: CHW
(image_path, img_size=1008)
| 12 | |
| 13 | |
| 14 | def cpp_preprocess(image_path, img_size=1008): |
| 15 | """Replicate C++ sam3_preprocess_image exactly. |
| 16 | |
| 17 | C++ does: |
| 18 | 1. Bilinear resize to img_size x img_size (half-pixel center mapping) |
| 19 | 2. Quantize back to uint8 with rounding |
| 20 | 3. Normalize: (pixel/255.0 - 0.5) / 0.5 |
| 21 | 4. Layout: CHW |
| 22 | """ |
| 23 | img = Image.open(image_path).convert("RGB") |
| 24 | src = np.array(img, dtype=np.float32) # [H, W, 3] |
| 25 | src_h, src_w = src.shape[:2] |
| 26 | |
| 27 | # C++ bilinear resize (half-pixel center mapping) |
| 28 | dst = np.zeros((img_size, img_size, 3), dtype=np.uint8) |
| 29 | sx = src_w / img_size |
| 30 | sy = src_h / img_size |
| 31 | |
| 32 | for y in range(img_size): |
| 33 | fy = (y + 0.5) * sy - 0.5 |
| 34 | y0 = max(0, int(fy)) |
| 35 | y1 = min(src_h - 1, y0 + 1) |
| 36 | wy = fy - y0 |
| 37 | for x in range(img_size): |
| 38 | fx = (x + 0.5) * sx - 0.5 |
| 39 | x0 = max(0, int(fx)) |
| 40 | x1 = min(src_w - 1, x0 + 1) |
| 41 | wx = fx - x0 |
| 42 | for c in range(3): |
| 43 | v = ((1 - wy) * ((1 - wx) * src[y0, x0, c] + wx * src[y0, x1, c]) + |
| 44 | wy * ((1 - wx) * src[y1, x0, c] + wx * src[y1, x1, c])) |
| 45 | dst[y, x, c] = min(255, max(0, int(v + 0.5))) |
| 46 | |
| 47 | # Normalize and convert to CHW |
| 48 | result = np.zeros((3, img_size, img_size), dtype=np.float32) |
| 49 | for c in range(3): |
| 50 | for y in range(img_size): |
| 51 | for x in range(img_size): |
| 52 | v = dst[y, x, c] / 255.0 |
| 53 | result[c, y, x] = (v - 0.5) / 0.5 |
| 54 | |
| 55 | return result, dst |
| 56 | |
| 57 | |
| 58 | def python_preprocess(image_path, img_size=1008): |
no outgoing calls
no test coverage detected