         float image_sqsum_ = (float)(
                 (image_sqsum.ptr(y + h)[(x + w) * cn] - image_sqsum.ptr(y)[(x + w) * cn]) -
                 (image_sqsum.ptr(y + h)[x * cn] - image_sqsum.ptr(y)[x * cn]));
-        result.ptr(y)[x] = min(1.f, result.ptr(y)[x] * rsqrtf((image_sqsum_ + 1.f) * templ_sqsum));
+        result.ptr(y)[x] = min(1.f, result.ptr(y)[x] * rsqrtf(max(1.f, image_sqsum_) * templ_sqsum));
     }
 }
 

                (image_sqsum_g.ptr(y + h)[x + w] - image_sqsum_g.ptr(y)[x + w]) -
                (image_sqsum_g.ptr(y + h)[x] - image_sqsum_g.ptr(y)[x]));
        float ccorr = result.ptr(y)[x];
        float rdenom = rsqrtf(templ_sqsum_scale * (image_sqsum_r_ - weight * image_sum_r_ * image_sum_r_ 
                                                   + image_sqsum_g_ - weight * image_sum_g_ * image_sum_g_ + 1.f));
        result.ptr(y)[x] = min(1.f, (ccorr - image_sum_r_ * templ_sum_scale_r
                                     - image_sum_g_ * templ_sum_scale_g) * rdenom);
    }

                (image_sqsum_a.ptr(y + h)[x + w] - image_sqsum_a.ptr(y)[x + w]) -
                (image_sqsum_a.ptr(y + h)[x] - image_sqsum_a.ptr(y)[x]));
        float ccorr = result.ptr(y)[x];
        float rdenom = rsqrtf(templ_sqsum_scale * max(1.f, image_sqsum_r_ - weight * image_sum_r_ * image_sum_r_
                                                           + image_sqsum_g_ - weight * image_sum_g_ * image_sum_g_
                                                           + image_sqsum_b_ - weight * image_sum_b_ * image_sum_b_
                                                           + image_sqsum_a_ - weight * image_sum_a_ * image_sum_a_));
        result.ptr(y)[x] = min(1.f, (ccorr - image_sum_r_ * templ_sum_scale_r
                                     - image_sum_g_ * templ_sum_scale_g
                                     - image_sum_b_ * templ_sum_scale_b
