-
Notifications
You must be signed in to change notification settings - Fork 271
Expand file tree
/
Copy pathmain.py
More file actions
53 lines (43 loc) · 1.96 KB
/
main.py
File metadata and controls
53 lines (43 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import cv2 as cv
import numpy as np
import os
# Change the working directory to the folder this script is in.
# Doing this because I'll be putting the files from each video in their own folder on GitHub
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# Can use IMREAD flags to do different pre-processing of image files,
# like making them grayscale or reducing the size.
# https://docs.opencv.org/4.2.0/d4/da8/group__imgcodecs.html
haystack_img = cv.imread('albion_farm.jpg', cv.IMREAD_UNCHANGED)
needle_img = cv.imread('albion_cabbage.jpg', cv.IMREAD_UNCHANGED)
# There are 6 comparison methods to choose from:
# TM_CCOEFF, TM_CCOEFF_NORMED, TM_CCORR, TM_CCORR_NORMED, TM_SQDIFF, TM_SQDIFF_NORMED
# You can see the differences at a glance here:
# https://docs.opencv.org/master/d4/dc6/tutorial_py_template_matching.html
# Note that the values are inverted for TM_SQDIFF and TM_SQDIFF_NORMED
result = cv.matchTemplate(haystack_img, needle_img, cv.TM_SQDIFF_NORMED)
# I've inverted the threshold and where comparison to work with TM_SQDIFF_NORMED
threshold = 0.17
# The np.where() return value will look like this:
# (array([482, 483, 483, 483, 484], dtype=int32), array([514, 513, 514, 515, 514], dtype=int32))
locations = np.where(result <= threshold)
# We can zip those up into a list of (x, y) position tuples
locations = list(zip(*locations[::-1]))
print(locations)
if locations:
print('Found needle.')
needle_w = needle_img.shape[1]
needle_h = needle_img.shape[0]
line_color = (0, 255, 0)
line_type = cv.LINE_4
# Loop over all the locations and draw their rectangle
for loc in locations:
# Determine the box positions
top_left = loc
bottom_right = (top_left[0] + needle_w, top_left[1] + needle_h)
# Draw the box
cv.rectangle(haystack_img, top_left, bottom_right, line_color, line_type)
cv.imshow('Matches', haystack_img)
cv.waitKey()
#cv.imwrite('result.jpg', haystack_img)
else:
print('Needle not found.')