PY-84

Build and Search an Image Score Map

  • Medium–Hard
  • Image Score Maps
  • Python

Task

Write build_image_score_map(image, template, origins, stride, threshold). This is a mechanical array task, not an image-processing theory task.

image and template are finite two-dimensional numeric NumPy arrays. The template has positive height and width and fits inside the image. stride is a pair (row_step, column_step) of positive integers. origins is the complete row-major list of valid top-left origins supplied by an earlier patch-origin step:

The function must require origins to equal that list exactly. For each origin, extract the same-shaped image patch and calculate the mean squared error against template in float64:

score = mean((patch - template) ** 2)

Lower scores are better. Return a dictionary with exactly these keys:

  • "scores": a new float64 array with shape (len(rows), len(columns)), with scores in the row and column order above;
  • "matches": a row-major list of dictionaries {"row": row, "column": column, "score": score} for scores less than or equal to threshold.

The threshold is inclusive. A score map and match list must be independent of the input arrays, and the image, template, and origin inputs must be unchanged. Reject a non-two-dimensional input, a template that does not fit, a non-positive stride, a non-finite threshold, or an origin list that is not the complete valid row-major list by raising ValueError. Use these messages: "image and template must be 2-D", "template must fit inside image", "stride must be positive", "threshold must be finite", and "origins do not match valid row-major grid".

Example

For an image of shape (4, 5), a template of shape (2, 2), and stride (2, 2), the valid rows are [0, 2] and the valid columns are [0, 2], so the score map has shape (2, 2). A template that exactly matches the patch at (2, 2) gives a zero there; with threshold 0.0, that origin is a match.

Your implementation

You may import NumPy as np. Do not modify an input, print, or ask for input.