6
6
"""
7
7
import numpy as np
8
8
import matplotlib .pyplot as plt
9
+ import warnings
10
+ from matplotlib .lines import Line2D
9
11
from skimage import feature
10
12
from .NMS import NMS
11
13
from .Detection import BoundingBox
@@ -111,7 +113,7 @@ def findMatches(image,
111
113
112
114
def matchTemplates (image ,
113
115
listTemplates ,
114
- listLabels = [] ,
116
+ listLabels = None ,
115
117
score_threshold = 0.5 ,
116
118
maxOverlap = 0.25 ,
117
119
nObjects = float ("inf" ),
@@ -151,7 +153,7 @@ def matchTemplates(image,
151
153
return bestHits
152
154
153
155
154
- def plotDetections (image , listDetections , thickness = 2 ):
156
+ def plotDetections (image , listDetections , thickness = 2 , showLegend = False ):
155
157
"""
156
158
Plot the detections overlaid on the image.
157
159
@@ -171,9 +173,10 @@ def plotDetections(image, listDetections, thickness=2):
171
173
- thickness (optional, default=2): int
172
174
thickness of plotted contour in pixels
173
175
174
- - showLabel: Boolean
175
- Display label of the bounding box (field TemplateName)
176
- Not implemented
176
+ - showLegend (optional, default=False): Boolean
177
+ Display a legend panel with the category labels for each color.
178
+ This works if the Detections have a label
179
+ (not just "", in which case the legend is not shown).
177
180
"""
178
181
plt .figure ()
179
182
plt .imshow (image , cmap = "gray" ) # cmap gray only impacts gray images
@@ -184,9 +187,41 @@ def plotDetections(image, listDetections, thickness=2):
184
187
palette = plt .cm .Set3 .colors
185
188
nColors = len (palette )
186
189
190
+ if showLegend :
191
+ mapLabelColor = {}
192
+
187
193
for detection in listDetections :
194
+
195
+ # Get color for this category
188
196
colorIndex = detection .get_template_index () % nColors # will return an integer in the range of palette
197
+ color = palette [colorIndex ]
189
198
190
199
plt .plot (* detection .get_lists_xy (),
191
200
linewidth = thickness ,
192
- color = palette [colorIndex ])
201
+ color = color )
202
+
203
+ # If show legend, get detection label and current color
204
+ if showLegend :
205
+
206
+ label = detection .get_label ()
207
+
208
+ if label != "" :
209
+ mapLabelColor [label ] = color
210
+
211
+ # Finally add the legend if mapLabelColor is not empty
212
+ if showLegend :
213
+
214
+ if not mapLabelColor : # Empty label mapping
215
+ warnings .warn ("No label associated to the templates." +
216
+ "Skipping legend." )
217
+
218
+ else : # meaning mapLabelColor is not empty
219
+
220
+ legendLabels = []
221
+ legendEntries = []
222
+
223
+ for label , color in mapLabelColor .items ():
224
+ legendLabels .append (label )
225
+ legendEntries .append (Line2D ([0 ], [0 ], color = color , lw = 4 ))
226
+
227
+ plt .legend (legendEntries , legendLabels )
0 commit comments