random_augment_image()
image random_augment_image(image im, float angle, float aspect, int low, int high, int size)
{
aspect = rand_scale(aspect);
int r = rand_int(low, high);
int min = (im.h < im.w*aspect) ? im.h : im.w*aspect;
float scale = (float)r / min;
float rad = rand_uniform(-angle, angle) * 2.0 * M_PI / 360.;
float dx = (im.w*scale/aspect - size) / 2.;
float dy = (im.h*scale - size) / 2.;
if(dx < 0) dx = 0;
if(dy < 0) dy = 0;
dx = rand_uniform(-dx, dx);
dy = rand_uniform(-dy, dy);
printf("random_augment_image rad: %f, scale: %f, size: %d,dx:%f,dy:%f,aspect:%f\n", rad, scale, size, dx, dy,aspect);
image crop = rotate_crop_image(im, rad, scale, size, size, dx, dy, aspect);
return crop;
}
1.random_gen
实现如下:
unsigned int random_gen()
{
unsigned int rnd = 0;
#ifdef WIN32
rand_s(&rnd);
#else // WIN32
rnd = rand();
#if (RAND_MAX < 65536)
rnd = rand()*(RAND_MAX + 1) + rnd;
#endif //(RAND_MAX < 65536)
#endif // WIN32
return rnd;
}
其中:
errno_t rand_s( unsigned int* randomValue );
函数的参数是一个整型的指针,指向一个用于接收随机数的整数类型;生成的随机数范围是 0-UINT_MAX。
函数成功的话,返回值是 0;否则的话返回错误代码。
因此,random_gen()生成并返回一个int型的随机数。
2.rand_uniform_strong
rand_uniform_strong()产生min到max之间一个随机值
float rand_uniform_strong(float min, float max)
{
if (max < min) {
float swap = min;
min = max;
max = swap;
}
return (random_float() * (max - min)) + min;
}
random_float()产生一个float类型随机值。
3.rand_scale()
float rand_scale(float s)
{
float scale = rand_uniform_strong(1, s);
if(random_gen()%2) return scale;
return 1./scale;
}
rotate_crop_image
字面意思理解:旋转裁剪图片
image rotate_crop_image(image im, float rad, float s, int w, int h, float dx, float dy, float aspect)
{
int x, y, c;
float cx = im.w/2.;
float cy = im.h/2.;
image rot = make_image(w, h, im.c);
for(c = 0; c < im.c; ++c){
for(y = 0; y < h; ++y){
for(x = 0; x < w; ++x){
float rx = cos(rad)*((x - w/2.)/s*aspect + dx/s*aspect) - sin(rad)*((y - h/2.)/s + dy/s) + cx;
float ry = sin(rad)*((x - w/2.)/s*aspect + dx/s*aspect) + cos(rad)*((y - h/2.)/s + dy/s) + cy;
float val = bilinear_interpolate(im, rx, ry, c);
set_pixel(rot, x, y, c, val);
}
}
}
return rot;
}
计算rx,ry啥意思?
bilinear_interpolate
双线性插值
float bilinear_interpolate(image im, float x, float y, int c)
{
int ix = (int) floorf(x);
int iy = (int) floorf(y);
float dx = x - ix;
float dy = y - iy;
float val = (1-dy) * (1-dx) * get_pixel_extend(im, ix, iy, c) +
dy * (1-dx) * get_pixel_extend(im, ix, iy+1, c) +
(1-dy) * dx * get_pixel_extend(im, ix+1, iy, c) +
dy * dx * get_pixel_extend(im, ix+1, iy+1, c);
return val;
}
get_pixel_extend()
static float get_pixel_extend(image m, int x, int y, int c)
{
if (x < 0 || x >= m.w || y < 0 || y >= m.h) return 0;
if (c < 0 || c >= m.c) return 0;
return get_pixel(m, x, y, c);
}
get_pixel()
static float get_pixel(image m, int x, int y, int c)
{
assert(x < m.w && y < m.h && c < m.c);
return m.data[c*m.h*m.w + y*m.w + x];
}