okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0479b72e9
main
1// tools/vision/own/image_prep.cpp - see image_prep.h 2// 3// The resize below is a port of llama.cpp's tools/mtmd/mtmd-image.cpp (resize_pillow, calc_size_preserved_ratio, img_tool::resize), 4// itself adapted from Pillow's Resample.c. llama.cpp: MIT, Copyright (c) 2023-2026 The ggml authors. Pillow: HPND. 5#include "image_prep.h" 6 7#include <algorithm> 8#include <cmath> 9#include <cstdio> 10#include <cstring> 11 12#define STBI_NO_STDIO 13#define STB_IMAGE_STATIC // private to this file: the mtmd build of strata-vision has its own copy of stb_image 14#define STB_IMAGE_IMPLEMENTATION 15#include "stb_image.h" 16 17namespace strata_vit { 18 19bool image_decode (const uint8_t * data ,size_t n ,ImageU8 & out , std::string & err ) { 20int nx = 0 ,ny = 0 ,nc = 0 ; 21if (n == 0 || n > 0x7FFFFFFFu ) {err = "the picture is empty or too large" ;return false; } 22unsigned char * px = stbi_load_from_memory (data , (int )n ,& nx ,& ny ,& nc ,3 ); 23if (!px ) {err = std::string ("cannot decode the picture: " )+ stbi_failure_reason ();return false; } 24out .w = nx ; 25out .h = ny ; 26out .rgb .assign (px ,px + (size_t )nx * ny * 3 ); 27stbi_image_free (px ); 28return true; 29} 30 31bool image_load_file (const std::string & path ,ImageU8 & out , std::string & err ) { 32FILE * f = std::fopen (path .c_str (),"rb" ); 33if (!f ) {err = "cannot open " + path ;return false; } 34 std::vector < uint8_t > buf ; 35uint8_t tmp [1 <<16 ]; 36size_t k ; 37while ((k = std::fread (tmp ,1 ,sizeof tmp ,f ))> 0 )buf .insert (buf .end (),tmp ,tmp + k ); 38 std::fclose (f ); 39return image_decode (buf .data (),buf .size (),out ,err ); 40} 41 42Size2 smart_resize (int width ,int height ,int align ,int min_pixels ,int max_pixels ) { 43if (width <=0 || height <=0 || align <=0 )return {0 ,0 }; 44// the same float arithmetic as mtmd (calc_size_preserved_ratio with longest_edge off) 45auto round_by_factor = [align ](float x ) {return static_cast < int > (std::round (x /static_cast < float > (align )))* align ; }; 46auto ceil_by_factor = [align ](float x ) {return static_cast < int > (std::ceil (x /static_cast < float > (align )))* align ; }; 47auto floor_by_factor = [align ](float x ) {return static_cast < int > (std::floor (x /static_cast < float > (align )))* align ; }; 48int w_bar = std::max (align ,round_by_factor ((float )width )); 49int h_bar = std::max (align ,round_by_factor ((float )height )); 50if (max_pixels > 0 && h_bar * w_bar > max_pixels ) { 51const auto beta = std::sqrt (static_cast < float > (height )* width /max_pixels ); 52h_bar = std::max (align ,floor_by_factor (height /beta )); 53w_bar = std::max (align ,floor_by_factor (width /beta )); 54 }else if (min_pixels > 0 && h_bar * w_bar < min_pixels ) { 55const auto beta = std::sqrt (static_cast < float > (min_pixels ) / (static_cast < float > (height )* width )); 56h_bar = ceil_by_factor (height * beta ); 57w_bar = ceil_by_factor (width * beta ); 58 } 59return {w_bar ,h_bar }; 60} 61 62namespace { 63 64const int PRECISION_BITS = 32 - 8 - 2 ;// 22 fractional bits: 32 - 8 (uint8 pixels) - 2 (headroom for the accumulation) 65 66double bicubic (double x ) {// Pillow's a = -0.5 67if (x < 0.0 )x = - x ; 68constexpr double a = -0.5 ; 69if (x < 1.0 )return ((a + 2.0 )* x - (a + 3.0 ))* x * x + 1 ; 70if (x < 2.0 )return (((x - 5 )* x + 8 )* x - 4 )* a ; 71return 0.0 ; 72} 73 74uint8_t clip8 (int v ) {return v < 0 ?0 :v > 255 ?255 : (uint8_t )v ; } 75 76// the filter coefficients of one dimension: bounds[2 i] first input pixel, bounds[2 i + 1] their count; weights in fixed point; returns the kernel size 77int precompute_weights (int in_size ,int out_size , std::vector < int >& bounds , std::vector < int32_t >& weights ) { 78double filterscale ,scale ; 79filterscale = scale = (double )in_size /out_size ; 80if (filterscale < 1.0 )filterscale = 1.0 ; 81const double support = 2.0 * filterscale ; 82const int ksize = (int ) std::ceil (support )* 2 + 1 ; 83 std::vector < double > pre ((size_t )out_size * ksize ); 84bounds .resize ((size_t )out_size * 2 ); 85for (int xx = 0 ;xx < out_size ;++ xx ) { 86const double center = (xx + 0.5 )* scale ; 87double ww = 0.0 ; 88const double ss = 1.0 /filterscale ; 89int xmin = (int ) (center - support + 0.5 ); 90if (xmin < 0 )xmin = 0 ; 91int xmax = (int ) (center + support + 0.5 ); 92if (xmax > in_size )xmax = in_size ; 93xmax -= xmin ; 94int x = 0 ; 95for (;x < xmax ;++ x ) { 96const double w = bicubic ((x + xmin - center + 0.5 )* ss ); 97pre [(size_t )xx * ksize + x ]= w ; 98ww += w ; 99 } 100for (x = 0 ;x < xmax ;++ x ) 101if (ww != 0.0 )pre [(size_t )xx * ksize + x ] /=ww ; 102for (;x < ksize ;++ x )pre [(size_t )xx * ksize + x ]= 0 ; 103bounds [(size_t )xx * 2 + 0 ]= xmin ; 104bounds [(size_t )xx * 2 + 1 ]= xmax ; 105 } 106weights .resize ((size_t )out_size * ksize ); 107const double fxp_scale = std::ldexp (1.0 ,PRECISION_BITS ); 108for (size_t i = 0 ;i < weights .size ();++ i ) { 109const double rounded = pre [i ]* fxp_scale + (pre [i ]< 0 ?-0.5 :0.5 );// Pillow: add 0.5 then truncate toward zero 110weights [i ]= (int32_t )rounded ; 111 } 112return ksize ; 113} 114 115std::vector < uint8_t > resample_horizontal (const uint8_t * src ,int in_nx ,int in_ny ,int out_nx ,int ksize ,const std::vector < int >& bounds , 116const std::vector < int32_t >& weights ) { 117 std::vector < uint8_t > out ((size_t )out_nx * in_ny * 3 ); 118for (int yy = 0 ;yy < in_ny ;++ yy ) { 119const uint8_t * src_row = src + (size_t )yy * in_nx * 3 ; 120uint8_t * dst_row = out .data ()+ (size_t )yy * out_nx * 3 ; 121for (int xx = 0 ;xx < out_nx ;++ xx ) { 122const int xmin = bounds [(size_t )xx * 2 + 0 ],xcnt = bounds [(size_t )xx * 2 + 1 ]; 123const int32_t * k = & weights [(size_t )xx * ksize ]; 124const uint8_t * p = src_row + (size_t )xmin * 3 ; 125int32_t ss0 = 1 << (PRECISION_BITS - 1 ),ss1 = ss0 ,ss2 = ss0 ; 126for (int x = 0 ;x < xcnt ;++ x ) { 127ss0 += p [0 ]* k [x ]; 128ss1 += p [1 ]* k [x ]; 129ss2 += p [2 ]* k [x ]; 130p += 3 ; 131 } 132dst_row [xx * 3 + 0 ]= clip8 (ss0 >>PRECISION_BITS ); 133dst_row [xx * 3 + 1 ]= clip8 (ss1 >>PRECISION_BITS ); 134dst_row [xx * 3 + 2 ]= clip8 (ss2 >>PRECISION_BITS ); 135 } 136 } 137return out ; 138} 139 140std::vector < uint8_t > resample_vertical (const uint8_t * src ,int in_nx ,int out_ny ,int ksize ,const std::vector < int >& bounds , 141const std::vector < int32_t >& weight ) { 142const size_t row_elems = (size_t )in_nx * 3 ; 143 std::vector < uint8_t > out (row_elems * out_ny ); 144 std::vector < int32_t > acc (row_elems ); 145for (int yy = 0 ;yy < out_ny ;++ yy ) { 146const int ymin = bounds [(size_t )yy * 2 + 0 ],ycnt = bounds [(size_t )yy * 2 + 1 ]; 147const int32_t * k = & weight [(size_t )yy * ksize ]; 148 std::fill (acc .begin (),acc .end (),1 << (PRECISION_BITS - 1 )); 149for (int y = 0 ;y < ycnt ;++ y ) { 150const uint8_t * src_row = src + (size_t ) (ymin + y )* row_elems ; 151const int32_t w = k [y ]; 152for (size_t i = 0 ;i < row_elems ;++ i )acc [i ]+= src_row [i ]* w ; 153 } 154uint8_t * dst_row = out .data ()+ (size_t )yy * row_elems ; 155for (size_t i = 0 ;i < row_elems ;++ i )dst_row [i ]= clip8 (acc [i ] >>PRECISION_BITS ); 156 } 157return out ; 158} 159 160}// namespace 161 162void resize_bicubic (const ImageU8 & img ,ImageU8 & dst ,int target_w ,int target_h ) { 163const bool need_h = target_w != img .w ,need_v = target_h != img .h ; 164 std::vector < int > bh ,bv ; 165 std::vector < int32_t > wh ,wv ; 166int kh = 0 ,kv = 0 ; 167if (need_h )kh = precompute_weights (img .w ,target_w ,bh ,wh ); 168if (need_v )kv = precompute_weights (img .h ,target_h ,bv ,wv ); 169 std::vector < uint8_t > res ; 170if (need_h && need_v ) { 171auto tmp = resample_horizontal (img .rgb .data (),img .w ,img .h ,target_w ,kh ,bh ,wh ); 172res = resample_vertical (tmp .data (),target_w ,target_h ,kv ,bv ,wv ); 173 }else if (need_h ) { 174res = resample_horizontal (img .rgb .data (),img .w ,img .h ,target_w ,kh ,bh ,wh ); 175 }else if (need_v ) { 176res = resample_vertical (img .rgb .data (),img .w ,target_h ,kv ,bv ,wv ); 177 }else { 178res = img .rgb ; 179 } 180dst .w = target_w ; 181dst .h = target_h ; 182dst .rgb = std::move (res ); 183} 184 185void resize_pad_ceil (const ImageU8 & src ,ImageU8 & dst ,Size2 target ) { 186if (src .w == target .w && src .h == target .h ) {dst = src ;return ; } 187const float scale_w = static_cast < float > (target .w ) /src .w ; 188const float scale_h = static_cast < float > (target .h ) /src .h ; 189const float scale = std::min (scale_w ,scale_h ); 190const int new_w = std::min (static_cast < int > (std::ceil (src .w * scale )),target .w ); 191const int new_h = std::min (static_cast < int > (std::ceil (src .h * scale )),target .h ); 192ImageU8 resized ; 193resize_bicubic (src ,resized ,new_w ,new_h ); 194ImageU8 out ; 195out .w = target .w ; 196out .h = target .h ; 197out .rgb .assign ((size_t )target .w * target .h * 3 ,0 );// black canvas 198const int ox = (target .w - new_w ) /2 ,oy = (target .h - new_h ) /2 ; 199for (int y = 0 ;y < new_h ;++ y ) { 200 std::memcpy (& out .rgb [((size_t ) (y + oy )* target .w + ox )* 3 ],& resized .rgb [(size_t )y * new_w * 3 ], (size_t )new_w * 3 ); 201 } 202dst = std::move (out ); 203} 204 205Size2 prepared_size (int w ,int h ,const VitGeometry & g ,int min_tokens ,int max_tokens ) { 206const int patch_area = g .patch * g .patch * g .merge * g .merge ; 207const int min_px = (min_tokens > 0 ?min_tokens :g .min_tokens )* patch_area ; 208const int max_px = (max_tokens > 0 ?max_tokens :g .max_tokens )* patch_area ; 209return smart_resize (w ,h ,g .align (),min_px ,max_px ); 210} 211 212bool prepare_image (const ImageU8 & src ,const VitGeometry & g ,int min_tokens ,int max_tokens ,PreparedImage & out , std::string & err ,ImageU8 * resized ) { 213if (src .w <=0 || src .h <=0 || src .rgb .size ()!= (size_t )src .w * src .h * 3 ) {err = "the picture is empty" ;return false; } 214const Size2 t = prepared_size (src .w ,src .h ,g ,min_tokens ,max_tokens ); 215if (t .w <=0 || t .h <=0 ) {err = "the picture has no usable size" ;return false; } 216ImageU8 r ; 217resize_pad_ceil (src ,r ,t ); 218out .w = t .w ; 219out .h = t .h ; 220const size_t n = (size_t )t .w * t .h ; 221out .chw .resize (3 * n ); 222for (size_t i = 0 ;i < n ;++ i ) 223for (int c = 0 ;c < 3 ;++ c )out .chw [c * n + i ]= ((float )r .rgb [i * 3 + c ] /255.0f - g .mean [c ]) /g .stdv [c ]; 224if (resized )* resized = std::move (r ); 225return true; 226} 227 228}// namespace strata_vit