position overlay precisely in matplotlib

Question:

I am trying to overlay precisely one image patch to a larger patch of the image
I have the coordinates where I’d like to put the patch and overlay the image but I don’t know how to do with matplotlib.

I know it’s possible with PILLOW (as explained here)but since I am using matplotlib for everything I’d be happy to stick to it.

enter image description here

For this example it would be moving the ‘red patch’ into the rectangle where ‘it’s supposed’ to be.

Here is the code that I used for that:

temp_k = img_arr[0][
    np.min(kernel[:, 1]) : np.max(kernel[:, 1]),
    np.min(kernel[:, 0]) : np.max(kernel[:, 0]),
]
temp_w = img_arr[1][
    np.min(window[:, 1]) : np.max(window[:, 1]),
    np.min(window[:, 0]) : np.max(window[:, 0]),
]
w, h = temp_k.shape[::-1]
res = cv2.matchTemplate(temp_w, temp_k, cv2.TM_CCORR_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
cv2.rectangle(temp_w, top_left, bottom_right, 255, 1)
plt.imshow(temp_w, cmap="bone")
plt.imshow(temp_k, cmap="magma", alpha=0.6)
plt.plot(max_loc[0], max_loc[1], "yo")
plt.savefig("../images/test.png")
plt.tight_layout()

Does anyone has an idea how to do that ?

Thanks in advance.

Asked By: Unic0

||

Answers:

Just as with Pillow, you need to tell Matplotlib where to place data. If you omit that, it will assume a default extent of [0,xs,ys,0], basically plotting it in the top-left corner as shown on your image.

Generating some example data:

import matplotlib.pyplot as plt
import numpy as np

n = 32
m = n // 2
o = n // 4

a = np.random.randn(n,n)
b = np.random.randn(m,m)

a_extent = [0,n,n,0]
b_extent = [o, o+m, o+m, o]

# a_extent = [0, 32, 32, 0]
# b_extent = [8, 24, 24, 8]

Plotting with:

fig, ax = plt.subplots(figsize=(5,5), constrained_layout=False, dpi=86, facecolor="w")

ax.imshow(a, cmap="bone", extent=a_extent)
ax.autoscale(False)

ax.imshow(b, cmap="magma", extent=b_extent)

Will result in:
enter image description here

Answered By: Rutger Kassies
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.