Repository: opencv
Issue: MatchTemplate with mask throws for oddly specific template image sizes / method combination
Labels: bug,category: imgproc

### System Information

OpenCV version 4.8.1 
OS: Windows 11
python version: 3.11.6

### Detailed description

When using the masked version of matchTemplate, having ALL of the following conditions at the same time
- providing a mask
- using method cv.TM_CCOEFF  or cv.TM_CCOEFF_NORM
- the template size is exactly (im_height - 3, im_width)

causes the following exception:
````
cv2.error: OpenCV(4.8.1) C:\Work\lib_sources\x64\opencv\modules\core\src\arithm.cpp:674: error: (-5:Bad argument) When the input arrays in add/subtract/multiply/divide functions have different types, the output array type must be explicitly specified in function 'cv::arithm_op'
````

Seems unrelated to the image /template/mask content (tested with random images, see below, but also occured in actual template matching scenario where other metrics/image size combinations work fine.)

Tested with various image/template sizes, all available methods, no mask/ with mask. See code below. Also tested with np.uint8/no.float32 dtypes (not shown).

### Steps to reproduce

````
import itertools
from collections import Counter
from enum import Enum, member
from typing import NamedTuple

import cv2 as cv
import numpy as np


class TemplateMatchModes(Enum):
    TM_SQDIFF = cv.TM_SQDIFF
    TM_SQDIFF_NORMED = cv.TM_SQDIFF_NORMED
    TM_CCORR = cv.TM_CCORR
    TM_CCORR_NORMED = cv.TM_CCORR_NORMED
    TM_CCOEFF = cv.TM_CCOEFF
    TM_CCOEFF_NORMED = cv.TM_CCOEFF_NORMED


def _random_im(shape: tuple[int, ...]) -> np.ndarray:
    return np.random.randint(low=0, high=255, size=shape, dtype=np.uint8)


def _random_mask_like(im: np.ndarray) -> np.ndarray:
    return np.random.randint(low=0, high=1, size=im.shape, dtype=np.uint8)


class MaskGenerator(Enum):
    ONES = member(np.ones_like)
    RANDOM = member(_random_mask_like)
    NONE = member(lambda x: None)


class FailureCause(NamedTuple):
    delta_size: tuple[int, int]
    mask_gen: str
    method: str


if __name__ == "__main__":

    failure_counter = Counter()
    n_image_sizes = 0
    for w, h in itertools.product(range(10, 100, 10), repeat=2):
        n_image_sizes += 1

        im_size = (h, w)
        im = _random_im(im_size)

        for dw, dh in itertools.product(range(-5, 1, 1), repeat=2):
            template_size = (h + dh, w + dw)
            template = _random_im(template_size)

            for mask_generator in MaskGenerator:
                mask = mask_generator.value(template)

                for method in TemplateMatchModes:
                    try:
                        res = cv.matchTemplate(
                            image=im,
                            templ=template,
                            method=method.value,
                            mask=mask,
                        )
                    except Exception:
                        failure_cause = FailureCause(
                            delta_size=(dh, dw), mask_gen=mask_generator.name, method=method.name
                        )
                        failure_counter[failure_cause] += 1

    print(f"{n_image_sizes=}")
    for item in failure_counter.items():
        print(item)

````

Reuslts in the following output
```
n_repeated_cases=81
(FailureCause(delta_size=(-3, 0), mask_gen='ONES', method='TM_CCOEFF'), 81)
(FailureCause(delta_size=(-3, 0), mask_gen='ONES', method='TM_CCOEFF_NORMED'), 81)
(FailureCause(delta_size=(-3, 0), mask_gen='RANDOM', method='TM_CCOEFF'), 81)
(FailureCause(delta_size=(-3, 0), mask_gen='RANDOM', method='TM_CCOEFF_NORMED'), 81)
```

### Issue submission checklist

- [X] I report the issue, it's not a question
- [X] I checked the problem with documentation, FAQ, open issues, forum.opencv.org, Stack Overflow, etc and have not found any solution
- [ ] I updated to the latest OpenCV version and the issue is still there
- [X] There is reproducer code and related data files (videos, images, onnx, etc)