outsu
outsu

Reputation: 32

How to detect specific pixel shapes?

I want to detect some specific shaped pixels such as I attached. How can I do this?

I just searched for solution, but I get resources for only basic shapes like circle, hexagon etc.

enter image description here

Upvotes: 1

Views: 405

Answers (1)

dzang
dzang

Reputation: 2260

You can use cross correlation scipy.signal.correlate to do template matching. e.g. if you have a template (like the llama in this example) and want to find its position in another image (the canvas), you can cross correlate the two images. You will get maxima (can be multiple) where the same template is found. Finding the maxima will tell you the position of your template.

import scipy.signal

xcorr = scipy.signal.correlate(canvas, pic)
xmax, ymax = np.where(xcorr == xcorr.max())

fig, ax = plt.subplots(1, 3, figsize=(10, 6))
ax[0].imshow(pic)
ax[1].imshow(canvas)
ax[2].imshow(xcorr)

circle1 = plt.Circle((xmax, ymax), 50, color='r', fill=False)
ax[2].add_patch(circle1)

titles = ['Template', 'Canvas', '2D Cross Correlation']

for a, t in zip(ax, titles):
    a.set_title(t)

template matching example

Upvotes: 2

Related Questions