-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhold detector.py
More file actions
220 lines (157 loc) · 5.84 KB
/
hold detector.py
File metadata and controls
220 lines (157 loc) · 5.84 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 16 18:45:15 2020
@author: Maggie
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
import math
import util
from util import openFile, showImage
#import colorsys
#from mpl_toolkits.mplot3d import Axes3D
def openImage(path):
# Open Image
file_path = path
img = cv2.imread(file_path,1)
# Image can be resized to a standard size to speed up processing.
c = 1000.0/img.shape[0]
x = int(img.shape[0] * c)
y = int(img.shape[1] * c)
img = cv2.resize(img, (y,x))
return img
""" Object detection """
def buildDetector(minArea = 25):
# Setup SimpleBlobDetector parameters.
params = cv2.SimpleBlobDetector_Params()
# Change thresholds
params.minThreshold = 0
params.maxThreshold = 255
# Filter by Area.
params.filterByArea = True
params.minArea = minArea
# Filter by Circularity
params.filterByCircularity = False
params.minCircularity = 0.1
# Filter by Convexity
params.filterByConvexity = False
params.minConvexity = 0.1
# Filter by Inertia
params.filterByInertia = True
params.minInertiaRatio = 0.05
# Create a detector with the parameters
ver = (cv2.__version__).split('.')
if int(ver[0]) < 3 :
detector = cv2.SimpleBlobDetector(params)
else :
detector = cv2.SimpleBlobDetector_create(params)
return detector
def findHolds(img,detector = None):
# Applying a gaussian blur removes some small impurities that
# could fool the detection algorithm. It also smooths out the
# color of each hold to make it more uniform.
img = cv2.GaussianBlur(img, (5, 5), 0)
# Using Otsu's method, the optimal threshold for the image can be found.
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
otsu, _ = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# Applys edge detection to find the borders between the hold and the wall
# Otsu's threshold is intended to be used as the higher threshold with a
# lower:upper ratio of 1:2. L2gradient is included for more precise results.
edges = cv2.Canny(img,otsu, otsu * 2, L2gradient = True)
print(otsu)
# Finds the contours of the image, without retaining the hierarchy
contours, _ = cv2.findContours(edges,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
# Applies convex hulls to each contour, ensuring each contour
# is a closed polygon.
hulls = map(cv2.convexHull,contours)
# Draws contours onto a blank canvas
mask = np.zeros(img.shape,np.uint8)
cv2.drawContours(mask,hulls,-1,[255,255,255],-1)
showImage(mask)
if detector == None:
# Set up the detector with default parameters.
detector = buildDetector()
keypoints = detector.detect(mask)
return keypoints , hulls
""" Color manipulations """
'''def getColorBin(img, tl, br):
# Creates mask over image focus
mask = np.zeros(img.shape[:2], np.uint8)
mask[tl[1]:br[1], tl[0]:br[0]] = 255
# Effecively quantizes the image when the histogram is made.
# Useful for grouping similar colors.
binLen = 4
numBins = 256 / binLen
#Finds the most common color/in the histogram/for each color channel.
binColor = map(
lambda x: np.argmax(
[cv2.calcHist([img],[x],mask,[numBins],[0,256])])
,[0,1,2])
fullColor = map(lambda x: x * binLen, binColor)
return fullColor
def findColors(img,keypoints):
# If no keypoints return nothing
if (keypoints == []):
return []
# Shift colorspace to HLS
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
# Preallocate space for color array corresponding to keypoints
colors = np.empty([len(keypoints),3])
# Iterates through the keypoints and finds the most common
# color at each keypoint.
for i, key in enumerate(keypoints):
x = int(key.pt[0])
y = int(key.pt[1])
size = int(math.ceil(key.size))
#Finds a rectangular window in which the keypoint fits
br = (x + size, y + size)
tl = (x - size, y - size)
colors[i] = getColorBin(hsv,tl,br)
return colors
""" Visualization """
def draw(img, keypoints):
# Draw detected blobs as red circles.
# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the
# size of the circle corresponds to the size of blob
for i, key in enumerate(keypoints):
x = int(key.pt[0])
y = int(key.pt[1])
size = int(math.ceil(key.size))
#Finds a rectangular window in which the keypoint fits
br = (x + size, y + size)
tl = (x - size, y - size)
cv2.rectangle(img,tl,br,(0,0,255),2)
#OpenCV uses BGR format, so that'll need to be reversed for display
img = img[...,::-1]
# Display the resulting frame
fig = plt.imshow(img)
plt.title("Image with Keypoints")
'def plotColors(colors):
# Build 3D scatterplot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Initialize arrays
hs = []
ls = []
ss = []
# Color data is mapped between 0 and 1
colors = colors/256
for color in colors:
hs.append(color[0])
ls.append(color[1])
ss.append(color[2])
# Regain RGB Values to color each data point
colorsRGB = map(colorsys.hls_to_rgb,hs,ls,ss)
# Plot points in HLS space
ax.scatter(hs, ls, ss, c=colorsRGB, marker='o')
ax.set_xlabel('Hue')
ax.set_ylabel('Lightness')
ax.set_zlabel('Saturation')
ax.set_xlim(0,1)
ax.set_ylim(0,1)
ax.set_zlim(0,1)
plt.title("Color Space of Keypoints")
plt.show()'''
img = openImage(r"C:\Users\Maggie\Pictures\Woody pictures\my woody 1.png")
findHolds(img,detector = None)