Fix template matching

This commit is contained in:
iabdalkader 2014-06-19 23:14:11 +02:00
parent e8a44ae066
commit ce3ab63337

View File

@ -3,9 +3,8 @@
#include <arm_math.h>
float imlib_template_match(struct image *f, struct image *t_orig, struct rectangle *r)
{
int x,y,u,v;
int den_b=0;
float corr =0.0;
float factor,scale_factor = 0.5f;
struct image img;
struct image *t=&img;
@ -22,60 +21,52 @@ float imlib_template_match(struct image *f, struct image *t_orig, struct rectan
/* allocate buffer for integral image */
f_imgs->w = f->w;
f_imgs->h = f->h;
/* after the framebuffer */
f_imgs->data = (uint32_t*) (f->data+(f->w * f->h*2));
f_imgs->data = (uint32_t*) (f->data+(f->w * f->h*2));/* after the framebuffer */
/* get integeral image */
imlib_integral_image(f, f_imgs);
for(factor=1.0f; (factor>0.25f); factor*=scale_factor) {
t->w = (int) t_orig->w*factor;
t->h = (int) t_orig->h*factor;
imlib_scale_image(t_orig, t);
/* copy template */
t->w = (int) t_orig->w;
t->h = (int) t_orig->h;
memcpy(t->data, t_orig->data,(sizeof(*t->data)* t_orig->w * t_orig->h));
int i;
long b_den=0;
int t_mean = imlib_image_mean(t);
/* get normalized template sum of squares */
int t_mean = imlib_image_mean(t);
for (int i=0; i < (t->w*t->h); i++) {
int c = (int8_t)t->data[i]-t_mean;
den_b += c*c;
t->data[i]=(int8_t)c;
}
/* get normalized template sum of squares */
for (i=0; i < (t->w*t->h); i++) {
int c = t->data[i]-t_mean;
b_den += c*c;
t->data[i]=(int8_t)c;
}
for (int v=0; v < f->h - t->h; v+=3) {
for (int u=0; u < f->w - t->w; u+=3) {
int num = 0;
int den_a=0;
uint32_t f_sum =imlib_integral_lookup(f_imgs, u, v, t->w, t->h);
int f_mean = f_sum / (t->w*t->h);
for (v=0; v < f->h - t->h; v+=3) {
for (u=0; u < f->w - t->w; u+=3) {
int sum_shift = 0;
int f_sum = imlib_integral_lookup(f_imgs, u, v, t->w, t->h);
int f_mean = f_sum / (t->w*t->h);
//int f_sumsq = imlib_integral_lookup(f_imgsq, u, v, t->w, t->h);
int f_sumsq=0;
for (y=v; y<t->h+v; y++) {
for (x=u; x<t->w+u; x++) {
int a = f->data[y*f->w+x]-f_mean;
int b = (int8_t) t->data[(y-v)*t->w+(x-u)];
sum_shift += a*b;
f_sumsq += f->data[y*f->w+x] * f->data[y*f->w+x];
}
}
int a_den = f_sumsq-(f_sum*(long)f_sum)/(t->w*t->h);
/* this overflows */
//corr = sum_shift/sqrtf(a_den*b_den);
float c = sum_shift/(fast_sqrtf(a_den)*fast_sqrtf(b_den));
if (c > corr) {
corr = c;
r->x = u;
r->y = v;
r->w = t->w;
r->h = t->h;
for (int y=v; y<t->h+v; y++) {
for (int x=u; x<t->w+u; x++) {
int a = (int8_t)f->data[y*f->w+x]-f_mean;
int b = (int8_t)t->data[(y-v)*t->w+(x-u)];
num += a*b;
den_a += a*a;
}
}
/* this overflows */
float c = num/(fast_sqrtf(den_a) *fast_sqrtf(den_b));
if (c > corr) {
corr = c;
r->x = u;
r->y = v;
r->w = t->w;
r->h = t->h;
}
}
}
xfree(t->data);
return corr;