├── .gitignore ├── CHANGELOG.md ├── Fiji.app ├── jars │ └── Lib │ │ ├── ImageConverter.py │ │ ├── ImageRotator.py │ │ ├── Template_Matching │ │ ├── MatchTemplate_Module.py │ │ ├── NonMaximaSupression_Py2.py │ │ ├── Version.py │ │ └── __init__.py │ │ └── utils.py └── scripts │ └── Plugins │ └── Multi-Template-Matching │ ├── 2step-TemplateMatching.ijm │ ├── Compute_ScoreMap.py │ ├── Crop_Roi_ToStack.py │ ├── Template_Matching_Folder.py │ ├── Template_Matching_Image.py │ ├── Template_Matching_ListImage.py │ └── Template_Matching_ListTemplate.py ├── Images ├── Acquifer_Logo_60k_cmyk_300dpi.png ├── EggDetected.png ├── FishRoi.JPG ├── GUI_Fiji_Annotated.png ├── HeadRoi.JPG ├── ImageInlife.png ├── MarieCurie.jpg ├── MontageEgg.png ├── Montage_Head.png ├── NMS.png ├── RoiManager.JPG ├── Screen_MatchImage.JPG ├── Screen_MatchListImage.JPG ├── TemplateMatching.png ├── TemplateMatchingFolder.JPG └── TemplateMatching_Montage.png ├── LICENSE ├── README.md └── Tuto └── 2-step-TemplateMatching ├── 2step-TemplateMatching.html ├── 2step-TemplateMatching.ijm ├── Fish.png └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | Images/TemplateMatching.pptx 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [1.1.6] - 2024-01-17 4 | 5 | ### Changed 6 | - Warning if template has same dimensions than the image 7 | -------------------------------------------------------------------------------- /Fiji.app/jars/Lib/ImageConverter.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This module contains functions to converts from an ImagePlus (RGB, 32-bit, 16-bit...) to an opencv matrix and vice-versa 3 | The default BitType of the opencv matricx is 8-bit 4 | ''' 5 | from ijopencv.ij import ImagePlusMatConverter 6 | from ijopencv.opencv import MatImagePlusConverter 7 | 8 | ip2mat = ImagePlusMatConverter() 9 | mat2ip = MatImagePlusConverter() 10 | 11 | def ImProcToMat(ImProc, Bit=8): 12 | ''' 13 | Convert an ImageProcessor to an opencv matrix with optionnal BitDepth conversion 14 | ''' 15 | # I - Convert the image Processor to a different BitType (if necessary) 16 | if ImProc.getBitDepth() != Bit: 17 | 18 | # For the conversion from higher to lower bitType the value are scaled 19 | # Similarly RGB to Gray result in a one channel gray image thanks to the ImageProcessor method 20 | if Bit == 8: 21 | ImProc = ImProc.convertToByteProcessor() # Boolean argument doScaling = True by default ? 22 | 23 | elif Bit == 16: 24 | ImProc = ImProc.convertToShortProcessor() 25 | 26 | elif Bit == 32: 27 | ImProc = ImProc.convertToFloatProcessor() 28 | 29 | else: 30 | # left as is 31 | pass 32 | 33 | 34 | # II - Convert the image processor to an opencv matrix 35 | ImCV = ip2mat.toMat(ImProc) 36 | 37 | return ImCV 38 | 39 | 40 | 41 | def MatToImProc(Mat): 42 | '''Convert an opencv matrix to an ImageProcessor of sane BitType''' 43 | IP = mat2ip.toImageProcessor(Mat) 44 | return IP -------------------------------------------------------------------------------- /Fiji.app/jars/Lib/ImageRotator.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Perform rotation of an image expanding the canvas and filling the background with the modal value of the initial value 3 | without calling IJ.run 4 | For that we create an empty canvas of the size of the final matrix (or larger : dimension of the initial image), paste the centered image and rotate it 5 | This is due to the fact that the canvas must be big enough to contain the all the rotated state of the image 6 | ''' 7 | from ij.gui import Roi 8 | from ij.plugin import RoiRotator 9 | from fiji.selection import Select_Bounding_Box 10 | from java.awt import Rectangle 11 | #from ij.plugin import CanvasResizer # does not allow to set a background value in gray level neither only rgb 12 | 13 | 14 | def Rotate(ImProc, angle): 15 | ''' 16 | This return a rotated version of the input ImageProcessor, filling the background with the modal value of the initial image 17 | For square rotation, prefer the rotateLeft/rotateRight method in ImageProcessor 18 | ''' 19 | 20 | ### Calculate width and height of rotated image ### 21 | # For this we simply use a ROI of the same size than the initial image, rotate it by the same angle and ask for the bounding box of this rotated rectangle 22 | 23 | # Get size of the initial image 24 | w = ImProc.width 25 | h = ImProc.height 26 | 27 | # Generate a ROI of this size 28 | Rect = Roi(0,0,w,h) 29 | 30 | # Rotate this ROI 31 | RectRot = RoiRotator().rotate(Rect,angle) 32 | 33 | # Compute size of the new Image 34 | # For its dimensions we take for each dimension the largest length between the initial image size and the size of the rotated bounding rectangle 35 | # otherwise the image gets cropped while rotated 36 | nw = max(w, int( RectRot.getFloatWidth() ) ) 37 | nh = max(h, int( RectRot.getFloatHeight() ) ) 38 | 39 | ''' 40 | # Previous way to compute new dimensions 41 | rangle = math.radians(angle) 42 | nw = abs(math.sin(rangle)*h) + abs(math.cos(rangle)*w) 43 | nh = abs(math.cos(rangle)*h) + abs(math.sin(rangle)*w) 44 | nw = int(round(nw)) 45 | nh = int(round(nh)) 46 | ''' 47 | 48 | # Compute offset/translation vector to center initial image in the new canvas 49 | Xoff = (nw-w)//2 50 | Yoff = (nh-h)//2 51 | 52 | # Adjust canvas of the image 53 | IPnew = ImProc.createProcessor(nw, nh) 54 | 55 | # Compute modal value of initial image 56 | Gray = ImProc.getStats().dmode 57 | #print Gray 58 | 59 | # Fill background with define gray level 60 | IPnew.setValue(Gray) # for fill 61 | IPnew.fill() 62 | 63 | # Insert previous image centered 64 | IPnew.insert(ImProc, Xoff, Yoff) 65 | IPnew.setBackgroundValue(Gray) # for rotate 66 | IPnew.rotate(angle) 67 | 68 | ### Remove the extra border that can still be there after rotation. Not always working : background might not be recognised ### 69 | Rect0 = Rectangle(nw,nh) # intialise ROI of size of the image (where to compute the background) 70 | 71 | # Get ROI 72 | BoxFinder = Select_Bounding_Box() 73 | bg = BoxFinder.guessBackground(IPnew) 74 | NewRect = BoxFinder.getBoundingBox(IPnew, Rect0, bg) 75 | #print NewRect 76 | 77 | # Crop 78 | IPnew.setRoi(NewRect) 79 | IPnew = IPnew.crop() 80 | 81 | return IPnew 82 | 83 | 84 | ''' 85 | # MAIN - Rotate the input image 86 | Rotated = Rotate(Image.getProcessor(), 60) 87 | 88 | # Display 89 | NewImage = ImagePlus("Rotated", Rotated) 90 | NewImage.show() 91 | ''' -------------------------------------------------------------------------------- /Fiji.app/jars/Lib/Template_Matching/MatchTemplate_Module.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This module contains a set of functions for multi-template-matching between a template and an image/stack. 3 | The detected area will be displayed as a rectangular ROI on the image, and this ROI will be added to the ROI manager 4 | 5 | Requirements : 6 | - IJ-OpenCV (from the updater) 7 | 8 | TO DO : 9 | - Images with overlay in Stack : change to the easier ij.plugin.ImagesToStack that use a list to make the stack. No need to precise the size.. 10 | ''' 11 | # Python 12 | from __future__ import division 13 | 14 | # ImageJ 15 | from ij import IJ,ImagePlus, ImageStack 16 | from ij.plugin.filter import MaximumFinder 17 | #from ij.gui import Roi, PointRoi 18 | 19 | if IJ.getFullVersion()<"1.52o": 20 | IJ.error("Please update ImageJ to min v1.52o. Help>Update ImageJ...") 21 | 22 | # OpenCV 23 | try: 24 | from org.bytedeco.javacpp.opencv_imgproc import matchTemplate, threshold, CV_THRESH_TOZERO 25 | from org.bytedeco.javacpp.opencv_core import Mat, Scalar, Point, minMaxLoc, subtract # UNUSED normalize, NORM_MINMAX, CV_8UC1, CV_32FC1 26 | from org.bytedeco.javacpp import DoublePointer 27 | 28 | except: 29 | IJ.error("Missing OpenCV dependencies. Make sure to activate 'IJ-OpenCV plugins' update site.") 30 | 31 | 32 | # Java 33 | from java.lang import Float #used to convert BytesToFloat 34 | 35 | # Home-made module in jars/Lib sent with Acquifer update site 36 | from ImageConverter import ImProcToMat, MatToImProc 37 | from ImageRotator import Rotate 38 | 39 | 40 | def MatchTemplate(imProc_template, imProc_target, method): 41 | ''' 42 | Function that performs the matching between one template and an image 43 | imProc_template : ImageProcessor object of the template image 44 | imProc_target : ImageProcessor object of the image in which we search the template 45 | method : Integer for the template matching method (openCV) 46 | return the correlation map 47 | ''' 48 | 49 | # Check if template larger than image 50 | if imProc_template.getWidth() > imProc_target.getWidth() or imProc_template.getHeight() > imProc_target.getHeight(): 51 | raise Exception("Template is larger than the searched image (width and/or height)") 52 | 53 | # Check if template has exact same dimensions than the image 54 | if imProc_template.getWidth() == imProc_target.getWidth() and imProc_template.getHeight() == imProc_target.getHeight(): 55 | raise Exception("Template has identical dimensions (width and height) than the searched image") 56 | 57 | # Convert to image matrix, 8-bit (if both are 8-bit) or 32-bit 58 | if imProc_template.getBitDepth()==8 and imProc_target.getBitDepth()==8: 59 | imTemplate = ImProcToMat(imProc_template, Bit=8) 60 | imTargetCV = ImProcToMat(imProc_target, Bit=8) 61 | else: 62 | imTemplate = ImProcToMat(imProc_template, Bit=32) 63 | imTargetCV = ImProcToMat(imProc_target, Bit=32) 64 | 65 | # Create a correlation map object and do the matching 66 | corrMapCV = Mat() 67 | matchTemplate(imTargetCV, imTemplate, corrMapCV, method) # result directly stored in CorrMap 68 | 69 | return corrMapCV 70 | 71 | 72 | 73 | def FindMinMax(CorrMapCV, Unique=True, MinMax="Max", Score_Threshold=0.5, Tolerance=0): 74 | ''' 75 | Detect Minima(s) or Maxima(s) in the correlation map 76 | The function uses for that the MinMaxLoc from opencv for unique detection 77 | or the MaximumFinder from ImageJ for multi-detection (in this case, for min detection the correlation map is inverted) 78 | 79 | - Unique : True if we look for one global min/max, False if we want local ones 80 | - MinMax : "Min" if we look for Minima, "Max" if we look for maxima 81 | - Score_Threshold : in range [0;1] (correlation maps are normalised) 82 | - Tolerance : Parameters for flood-fill. Not used here so should be set to 0 83 | 84 | Returns List of Min/Max : [(X, Y, Coefficient), ... ] 85 | ''' 86 | #### Detect min/maxima of correlation map #### 87 | Extrema = [] 88 | 89 | ## if 1 hit expected 90 | if Unique: # Look for THE global min/max 91 | minVal = DoublePointer(1) 92 | maxVal = DoublePointer(1) 93 | minLoc = Point() 94 | maxLoc = Point() 95 | minMaxLoc(CorrMapCV, minVal, maxVal, minLoc, maxLoc, Mat()) 96 | 97 | if MinMax=="Min": # For method based on difference we look at the min value 98 | X = minLoc.x() 99 | Y = minLoc.y() 100 | Coeff = minVal.get() 101 | 102 | elif MinMax=="Max": 103 | X = maxLoc.x() 104 | Y = maxLoc.y() 105 | Coeff = maxVal.get() 106 | 107 | # Append to the output list 108 | Extrema.append( (X, Y, Coeff) ) 109 | 110 | 111 | 112 | ## if more hit expected 113 | else: # expect more than 1 template/image. Do a multi minima/maxima detection 114 | 115 | ## OLD CODE LEFT BUT DONT DO IT, NOT GOOD PREACTICE !! Normalise the correlation map to 0-1 (easier to apply the threshold) 116 | ## Rather use normalised method only for the computation of the correlation map (by default normalised method are 0-1 bound) 117 | # The normalised method are already normalised to 0-1 but it is more work to take it into account in this function 118 | # WARNING : this normalisation normalise regarding to the maxima of the given correlation map 119 | # Not good because it means the thresholding is define relative to a correlation map : a score of 1 might not correspond to a correlation of 1 120 | # But only means that the pixel was the maximum of this particular correlation map 121 | 122 | #CorrMapNormCV = Mat() 123 | #normalize(CorrMapCV, CorrMapNormCV, 0, 1, NORM_MINMAX, CV_32FC1, None) 124 | 125 | # Visualisation for debugging 126 | #CorrMapNorm = MatToImProc(CorrMapNormCV) 127 | #CorrMapNorm = ImagePlus("Normalised", CorrMapNorm) 128 | #CorrMapNorm.show() 129 | 130 | 131 | 132 | ### Maxima/Minima detection on the correlation map 133 | 134 | ## Difference-based method : we look for min value. For that we detect maxima on an inverted correlation map 135 | if MinMax=="Min": 136 | 137 | # Invert the correlation map : min becomes maxima 138 | One = Scalar(1.0) 139 | CorrMapInvCV = subtract(One, CorrMapCV).asMat() 140 | #CorrMapInv = MatToImProc(CorrMapInvCV) 141 | #CorrMapInv = ImagePlus("Inverted", CorrMapInv) 142 | #CorrMapInv.show() 143 | 144 | 145 | # Apply a "TO ZERO" threshold on the correlation map : to compensate the fact that maxima finder does not have a threshold argument 146 | # TO ZERO : below the threshold set to 0, above left untouched 147 | # NB : 1-score_threshold since we have inverted the image : we want to look for minima of value 1-x in the inverted image 148 | CorrMapThreshCV = Mat() 149 | threshold(CorrMapInvCV, CorrMapThreshCV, 1-Score_Threshold, 0, CV_THRESH_TOZERO) 150 | CorrMapThresh = MatToImProc(CorrMapThreshCV) # Keep this conversion, not only for visualisation 151 | #CorrMapThreshImp = ImagePlus("Thresholded", CorrMapThresh) 152 | #CorrMapThreshImp.show() 153 | 154 | 155 | 156 | ## Correlation-based method : we look for maxima 157 | elif MinMax=="Max": 158 | # Apply a "TO ZERO" threshold on the correlation map : to compensate the fact that maxima finder does not have a threshold argument 159 | # TO ZERO : below the threshold set to 0, above left untouched 160 | # NB : 1-score_threshold since we have inverted the image : we want to look for minima of value 1-x in the inverted image 161 | CorrMapThreshCV = Mat() 162 | threshold(CorrMapCV, CorrMapThreshCV, Score_Threshold, 0, CV_THRESH_TOZERO) 163 | CorrMapThresh = MatToImProc(CorrMapThreshCV) # Keep this conversion, not only for visualisation 164 | #CorrMapThreshImp = ImagePlus("Thresholded", CorrMapThresh) 165 | #CorrMapThreshImp.show() 166 | 167 | 168 | 169 | ## For both cases (Multi-Min/Max-detection) detect maxima on the thresholded map 170 | # Detect local maxima 171 | excludeOnEdge = False # otherwise miss quite a lot of them 172 | Polygon = MaximumFinder().getMaxima(CorrMapThresh, Tolerance, excludeOnEdge) 173 | 174 | # Maxima as list of points 175 | #roi = PointRoi(Polygon) 176 | 177 | # Generate Hit from max coordinates 178 | #print Polygon.npoints," maxima detected in this score map" 179 | if Polygon.npoints!=0: # Check that there are some points indeed. Otherwise Polygon.xpoints and ypoints are anyway initialised with [0,0,0,0] even if Npoints=0 ! 180 | 181 | for i in range(Polygon.npoints): # dont directly loop on xpoints and ypoint since initialised with [0,0,0,0] ie less than 4 points we get some 0,0 coordinates 182 | 183 | # Get point coordinates 184 | X, Y = Polygon.xpoints[i], Polygon.ypoints[i] 185 | 186 | # Get Coeff 187 | Coeff = CorrMapThresh.getPixel(X, Y) 188 | Coeff = Float.intBitsToFloat(Coeff) # require java.lang.Float 189 | 190 | # Revert the score again if we were detecting minima initially (since found as maxima of a reverted correlation map) 191 | if MinMax=="Min": 192 | Coeff = 1-Coeff 193 | 194 | # Wrap into corresponding hit 195 | Extrema.append( (X, Y, Coeff) ) 196 | 197 | return Extrema 198 | 199 | 200 | 201 | 202 | def getHit_Template(ImpTemplate, ImpImage, FlipV=False, FlipH=False, Angles='', Method=5, N_Hit=1, Score_Threshold=0.5, Tolerance=0): 203 | ''' 204 | This function performs : 205 | 1) Preprocessing of the template (flipping and/or rotation) 206 | 2) Template matching for each of those template 207 | 4) Then for each correlation map, Min/Max detection and Non-Maxima Suppression (NMS) 208 | NB : It does not do the NMS between correlation map, only for a given correlation map (intra-NMS) 209 | The inter-NMS still remains to be done, it is not included in the function because other templates/hits might be used 210 | 211 | 212 | - ImProc_Template : ImageProcessor object of the template image 213 | - ImProc_Image : ImageProcessor object of the image in which we search the template 214 | - FlipV/H : Boolean, search for additional vertical/horizontal flipped version of the template 215 | - Angles : String like "10,20,50" - angles to search for additional rotated version of the template (both initial and flipped template are rotated) 216 | - Method : Integer for the template matching method (openCV) 217 | - N_Hit : Expected number of templates in the image 218 | - Score_Threshold : respectively Min/Max value for the detection of Maxima/Minima in the correlation map 219 | - Tolerance : peak height relative to neighbourhood for min/max detection (only used if N_hit>1). Set to 0 so that no effect (this is design for flood fill) 220 | - Max_Overlap : Max overlap (Intersection over Union, IoU) between bounding boxes used for NMS 221 | 222 | It returns a list of hit [ {TemplateName, BBox, Score}, ..., ] 223 | ''' 224 | # Get ImageProcessor for template and image 225 | ImProc_Template = ImpTemplate.getProcessor() 226 | ImProc_Image = ImpImage.getProcessor() 227 | 228 | # Get Image names for template and image 229 | TemplateName = ImpTemplate.getTitle() 230 | ImageName = ImpImage.getTitle() 231 | 232 | ListTemplate = [ {"Name":TemplateName, "ImProc":ImProc_Template} ] # initialise list with initial template 233 | 234 | ## Pre-Process template (Flip and/or Rotation) 235 | # Flip vertical 236 | if FlipV: 237 | TemplateFlipV = ImProc_Template.duplicate() 238 | TemplateFlipV.flipVertical() # duplicate previously to prevent in-place change 239 | ListTemplate.append( {"Name":TemplateName+"_Vertical_Flip", "ImProc":TemplateFlipV} ) 240 | 241 | # Flip horizontal 242 | if FlipH: 243 | TemplateFlipH = ImProc_Template.duplicate() 244 | TemplateFlipH.flipHorizontal() # duplicate previously to prevent in-place change 245 | ListTemplate.append( {"Name":TemplateName+"_Horizontal_Flip", "ImProc":TemplateFlipH}) 246 | 247 | 248 | # Rotation (initial and flipped templates) 249 | if Angles: # if different than an empty string 250 | 251 | # Recover individual angle values 252 | Angles = Angles.split(",") 253 | Angles = list(map(int, Angles)) # # convert to int. map returns a list in Py2 but an iterator in Py3 hence the list conversion for max compatibility 254 | #print Angles 255 | 256 | # copy before appending any rotated ones. ie only contains initial + flipped ones 257 | ListToRotate = ListTemplate[:] 258 | 259 | # Loop over list of angles 260 | for angle in Angles: 261 | 262 | # Loop over initial and flipped template and rotate each template in input list 263 | for template in ListToRotate: # template is a dictionnary here 264 | 265 | TemplateName = template['Name'] # it can be original or with "_flipX" 266 | 267 | # Perform the rotation 268 | Rotated = Rotate(template['ImProc'], angle) # a rotated template might be out of the search region 269 | 270 | # Append to the list of templates 271 | ListTemplate.append( {"Name": TemplateName + "_" + str(angle) + 'degrees', "ImProc":Rotated} ) 272 | 273 | 274 | ### Loop over template to do the matching #### 275 | List_Hit = [] 276 | for template in ListTemplate: # template is a dico here 277 | 278 | ## Search the current template in the image -> Correlation Map ### 279 | try : 280 | CorrMapCV = MatchTemplate(template["ImProc"], ImProc_Image, Method) 281 | except Exception as error: # template larger than image for instance 282 | IJ.log("Issue with template " + template["Name"] + " (was skipped)\n" + str(error)) 283 | continue 284 | # View map for debugging 285 | #CorrMap = MatToImProc(CorrMapCV) 286 | #CorrMap = ImagePlus("CorrMap", CorrMap) 287 | #CorrMap.show() 288 | 289 | 290 | #### Detect min/maxima of correlation map #### 291 | if N_Hit==1: 292 | Unique = True 293 | else: 294 | Unique = False 295 | 296 | if Method in [0,1]: 297 | MinMax="Min" 298 | else: 299 | MinMax="Max" 300 | 301 | List_XYCoeff = FindMinMax(CorrMapCV, Unique, MinMax, Score_Threshold, Tolerance) 302 | List_NewHit = [ { "ImageName":ImageName, 303 | "TemplateName":template["Name"], 304 | "BBox":(x, y, template['ImProc'].width, template['ImProc'].height), 305 | "Score":Coeff} for x,y,Coeff in List_XYCoeff ] 306 | 307 | # Append Hit for this particular template to the list of output hit 308 | List_Hit.extend(List_NewHit) 309 | 310 | # Return list of Hits 311 | return List_Hit 312 | 313 | 314 | 315 | def CornerToCenter(Xcorner, Ycorner, TemplateWidth, TemplateHeight): 316 | ''' Convert from top left pixel to center pixel of detected ROI''' 317 | 318 | Xcenter = Xcorner + TemplateWidth//2 319 | Ycenter = Ycorner + TemplateHeight//2 320 | 321 | return Xcenter,Ycenter -------------------------------------------------------------------------------- /Fiji.app/jars/Lib/Template_Matching/NonMaximaSupression_Py2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | -Python2- 4 | 5 | Non maxima supression for match template 6 | 7 | Let say we have a correlation map and we want to detect the N best location in this map, while we want to make sure the detected location do not overlap too much 8 | The threshold for the overlap used is a maximal value of Intersection over Union (IoU). Large overlap will have large IoU. 9 | The IoU is conveneient as it is normalised between 0 and 1 and is a value normalised by the intial area. 10 | 11 | To keep the N best hit/bounding-boxes without overlap, we first collect all hits that pass the score threshold. If we used several tempaltes and thus have several correlation map we perform the NMS on the full set of hit 12 | Then we order all those hit by score to have the best score first 13 | We initialise the list of finally collected hit with the first best hit 14 | Then we loop over the remaining hit, and compute the IoU between the bounding box of this hit and the previously collected hit. 15 | If one of the IoU is above the threshold, then the current hit is discarded 16 | Otherwise thie means the current hit is not overlapping with any previously collected hit, therefore we can add it to the lsit of finally collected hit. 17 | The iteration continues with the next hit, until we collect the N expected hits, or until there are no more hits to test 18 | 19 | if N_Hit = 1, the NMS will not compute any IoU actually, only returns the first oen with the highest score 20 | 21 | ListOfHit contains N dictionnaries, 1 per hit : {'TemplateIdx':i, 'BBox':(x,y,width,hieght), 'Score':float} 22 | 23 | NB : remove print statements that were dramatically slowing down the execution when used as a plugin (not observed from the script interpreter) 24 | 25 | @author: Laurent Thomas 26 | """ 27 | from __future__ import division 28 | from ij.gui import Roi 29 | 30 | def computeIoU(BBox1,BBox2): 31 | ''' 32 | Compute the IoU (Intersection over Union) between 2 rectangular bounding boxes defined by the top left (Xtop,Ytop) and bottom right (Xbot, Ybot) pixel coordinates 33 | Code adapted from https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/ 34 | ''' 35 | #print 'BBox1 : ', BBox1 36 | #print 'BBox2 : ', BBox2 37 | 38 | # Unpack input (python3 - tuple input are no more supported) 39 | Xleft1, Ytop1, Width1, Height1 = BBox1 40 | Xleft2, Ytop2, Width2, Height2 = BBox2 41 | 42 | # Compute bottom coordinates 43 | Xright1 = Xleft1 + Width1 -1 # we remove -1 from the width since we start with 1 pixel already (the top one) 44 | Ybot1 = Ytop1 + Height1 -1 # idem for the height 45 | 46 | Xright2 = Xleft2 + Width2 -1 47 | Ybot2 = Ytop2 + Height2 -1 48 | 49 | # determine the (x, y)-coordinates of the top left and bottom right points of the intersection rectangle 50 | Xleft = max(Xleft1, Xleft2) 51 | Ytop = max(Ytop1, Ytop2) 52 | Xright = min(Xright1, Xright2) 53 | Ybot = min(Ybot1, Ybot2) 54 | 55 | # Generate a Roi for the BBox just to be able to check that the BBox are not contained within another 56 | Roi1 = Roi(Xleft1, Ytop1, Width1, Height1) 57 | Roi2 = Roi(Xleft2, Ytop2, Width2, Height2) 58 | 59 | # Get boolean if BBox within another one (simply test contain with each corner point) 60 | Roi1_in_Roi2 = Roi2.contains(Xleft1, Ytop1) and Roi2.contains(Xright1, Ytop1) and Roi2.contains(Xleft1, Ybot1) and Roi2.contains(Xright1, Ybot1) 61 | Roi2_in_Roi1 = Roi1.contains(Xleft2, Ytop2) and Roi1.contains(Xright2, Ytop2) and Roi1.contains(Xleft2, Ybot2) and Roi1.contains(Xright2, Ybot2) 62 | 63 | if Roi1_in_Roi2 or Roi2_in_Roi1: 64 | #print '1 BBox is included within the other' 65 | IoU = 1 # otherwise using the formula below we have value below 1 eventhough the bbox are included 66 | 67 | elif Xright=scoreThreshold] 129 | 130 | elif not sortDescending : # We keep hit below the threshold 131 | List_ThreshHit = [dico for dico in List_Hit if dico['Score']<=scoreThreshold] 132 | 133 | 134 | # Sort score to have best predictions first (important as we loop testing the best boxes against the other boxes) 135 | if sortDescending: 136 | List_ThreshHit.sort(key=lambda dico: dico['Score'], reverse=True) # Hit = [list of (x,y),score] - sort according to descending (best = high correlation) 137 | else: 138 | List_ThreshHit.sort(key=lambda dico: dico['Score']) # sort according to ascending score (best = small difference) 139 | #print "Sorted List", List_ThreshHit 140 | 141 | # Split the inital pool into Final Hit that are kept and restHit that can be tested 142 | # Initialisation : 1st keep is kept for sure, restHit is the rest of the list 143 | #print "\nInitialise final hit list with first best hit" 144 | FinalHit = [List_ThreshHit[0]] 145 | restHit = List_ThreshHit[1:] 146 | 147 | #print "-> Final hit list" 148 | #for hit in FinalHit: print hit 149 | 150 | #print "\n-> Remaining hit list" 151 | #for hit in restHit: print hit 152 | 153 | 154 | 155 | # Loop to compute overlap 156 | while len(FinalHit) Final hit list" 162 | #for hit in FinalHit: print hit 163 | 164 | #print "\n-> Remaining hit list" 165 | #for hit in restHit: print hit 166 | 167 | # pick the next best peak in the rest of peak 168 | test_hit = restHit[0] 169 | test_bbox = test_hit['BBox'] 170 | #print "\nTest BBox:{} for overlap against higher score bboxes".format(test_bbox) 171 | 172 | # Loop over hit in FinalHit to compute successively overlap with test_peak 173 | for hit in FinalHit: 174 | 175 | # Recover Bbox from hit 176 | bbox2 = hit['BBox'] 177 | 178 | # Compute the Intersection over Union between test_peak and current peak 179 | IoU = computeIoU(test_bbox, bbox2) 180 | 181 | # Initialise the boolean value to true before test of overlap 182 | ToAppend = True 183 | 184 | if IoU>maxOverlap: 185 | ToAppend = False 186 | #print "IoU above threshold\n" 187 | break # no need to test overlap with the other peaks 188 | 189 | else: 190 | #print "IoU below threshold\n" 191 | # no overlap for this particular (test_peak,peak) pair, keep looping to test the other (test_peak,peak) 192 | continue 193 | 194 | 195 | # After testing against all peaks (for loop is over), append or not the peak to final 196 | if ToAppend: 197 | # Move the test_hit from restHit to FinalHit 198 | #print "Append {} to list of final hits and remove it from Remaining hit list".format(test_hit) 199 | FinalHit.append(test_hit) 200 | restHit.remove(test_hit) 201 | 202 | else: 203 | # only remove the test_peak from restHit 204 | #print "Remove {} from Remaining hit list".format(test_hit) 205 | restHit.remove(test_hit) 206 | 207 | 208 | # Once function execution is done, return list of hit without overlap 209 | #print "\nCollected N expected hit, or no hit left to test" 210 | 211 | 212 | #print "NMS over\n" 213 | return FinalHit 214 | 215 | 216 | 217 | 218 | if __name__ == "__main__": 219 | Hit1 = {'TemplateName':"Initial",'BBox':(780, 350, 700, 480), 'Score':0.8} 220 | Hit2 = {'TemplateName':"Initial",'BBox':(806, 416, 716, 442), 'Score':0.6} 221 | Hit3 = {'TemplateName':"Initial",'BBox':(1074, 530, 680, 390), 'Score':0.4} 222 | 223 | ListHit = [Hit1, Hit2, Hit3] 224 | 225 | ListFinalHit = NMS(ListHit) 226 | 227 | print ListFinalHit 228 | -------------------------------------------------------------------------------- /Fiji.app/jars/Lib/Template_Matching/Version.py: -------------------------------------------------------------------------------- 1 | version = "Version 1.1.6" -------------------------------------------------------------------------------- /Fiji.app/jars/Lib/Template_Matching/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Fiji.app/jars/Lib/Template_Matching/__init__.py -------------------------------------------------------------------------------- /Fiji.app/jars/Lib/utils.py: -------------------------------------------------------------------------------- 1 | def AddToTable(Table, Dico, Order=None, Label=""): 2 | ''' 3 | Append a row to an existing result table 4 | Dico : {'column1':value1, 'column2':value2...} - NB: The column header of the dictionnary should match the one of the existing table 5 | Order : ('column1', 'column2',...), if one wants to specify an order for the column 6 | Label : (optional) String to use as row index, if empty then only columns in the table 7 | ''' 8 | # add new row 9 | Table.incrementCounter() 10 | 11 | # Define the Label for that row = row index 12 | if Label: Table.addLabel(Label) # otherwise there are only columns 13 | 14 | if Order and set(Order)==set(Dico.keys()): # check that the content of order is indeed equal to the content of dico keys 15 | for key in Order: # we loop over order to have the keys ordonned 16 | Table.addValue(key, Dico[key]) 17 | 18 | else: # When the content of order is not equal to the content of the dico. Then just iterate over the dictionnary without a specific order 19 | for key, value in Dico.iteritems(): 20 | Table.addValue(key, value) 21 | 22 | 23 | 24 | if __name__ in ['__main__', '__builtin__']: 25 | from ij.measure import ResultsTable 26 | 27 | Table = ResultsTable() 28 | 29 | AddToTable(Table, {'Column1':5, 'Column2':41}, Order=("Column2", "Column1"), Label='Line1') 30 | AddToTable(Table, {'Column1':5, 'Column2':41}, Order=("Column2", "Column1"), Label='Line2') 31 | 32 | Table.show("Results") -------------------------------------------------------------------------------- /Fiji.app/scripts/Plugins/Multi-Template-Matching/2step-TemplateMatching.ijm: -------------------------------------------------------------------------------- 1 | /* 2 | * This macro allows to do a 2-step template matching 3 | * The first template allows to find an object and the second template finds a sub-object within the previously found object 4 | * Therefore the second template must be smaller than the first one 5 | * Both template images and the image to search should be open in fiji. 6 | * Both detection (1st and 2nd template) are returned in the ROI manager. 7 | * 8 | * NB : Make sure the ROI Manager is empty before running this macro 9 | * 10 | */ 11 | #@ImagePlus (Label="Template1") temp1 12 | #@ImagePlus (Label="Template2") temp2 13 | #@ImagePlus (Label="Image") image 14 | 15 | // Show all ROI and associate with Slices 16 | //roiManager("Show All"); 17 | //roiManager("Associate", "true"); 18 | 19 | // Get image names 20 | selectImage(temp1); 21 | Temp1_title = getTitle(); 22 | //print(Temp1_title); 23 | 24 | selectImage(temp2); 25 | Temp2_title = getTitle(); 26 | //print(Temp2_title); 27 | 28 | selectImage(image); 29 | Image_title = getTitle(); 30 | //print(Image_title); 31 | 32 | // Call 1st template matching 33 | //Start_Temp1 = getTime(); 34 | run("Template Matching Image", "template=" + Temp1_title + " image=" + Image_title + " rotate=[] matching_method=[Normalised 0-mean cross-correlation] number_of_objects=1 score_threshold=0.50 maximal_overlap=0.25 add_roi"); 35 | //Stop_Temp1 = getTime(); 36 | //AverageTimeTemp1 = (Stop_Temp1 - Start_Temp1)/96; 37 | // Because we want to have the average time per image, and the first template matching is a batch-operation (one call for all slices) we divide by the number of images 38 | 39 | // Loop over stack 40 | //print("Average time per image(ms)"); 41 | setBatchMode(true); // do not open extracted slices 42 | selectImage(image); 43 | Roi.remove; 44 | n = nSlices; 45 | nRoi_old = roiManager("count"); // Roi of the 1st template matching 46 | for (i=1; i<=n; i++) { 47 | 48 | 49 | //Start_Temp2 = getTime(); 50 | 51 | // Isolate slice from stack (to perform the second template matching with a custom search ROI for that slice) 52 | selectImage(image); //important here to select back the image when entering a new iteration, during looping the slice is selected 53 | setSlice(i); 54 | Roi.remove; 55 | run("Duplicate...", "title=Slice_"+i); // The isolated slice has for title "Slice_i" 56 | 57 | // Set search ROI on isolated slice 58 | roiManager("select", i-1); // i-1 since ROI manager starts at 0 59 | Roi.getBounds(x, y, width, height); 60 | makeRectangle(x, y, width, height); 61 | //print(x,y,width,height); 62 | 63 | // Run template matching on slice with search ROI 64 | run("Template Matching Image", "template=" + Temp2_title + " image=Slice_" + i +" flip_template_vertically rotate=[] matching_method=[Normalised 0-mean cross-correlation] number_of_objects=2 score_threshold=0.50 maximal_overlap=0.25 add_roi show_result"); 65 | 66 | // Close hidden Slice image 67 | //selectImage("Slice_"+i); 68 | //close(); 69 | 70 | // Rename and Set Z-position of the last found ROI 71 | nRoi_new = roiManager("count"); 72 | 73 | for (j=1; j<=nRoi_new-nRoi_old; j++) { 74 | 75 | roiManager("select", nRoi_new-j); 76 | run("Properties... ", "position="+i); // Set slice position 77 | InitName = call("ij.plugin.frame.RoiManager.getName", nRoi_new-j); 78 | roiManager("rename", i + substring(InitName, 1)); 79 | } 80 | 81 | // Update the count 82 | nRoi_old = nRoi_new; 83 | 84 | //Stop_Temp2 = getTime(); 85 | //AverageTimeTemp2 = Stop_Temp2 - Start_Temp2; 86 | //print(AverageTimeTemp1+AverageTimeTemp2); 87 | } 88 | 89 | // Again make sure that all ROI are displayed and associated to the slices 90 | roiManager("Show All"); 91 | roiManager("Associate", "true"); 92 | -------------------------------------------------------------------------------- /Fiji.app/scripts/Plugins/Multi-Template-Matching/Compute_ScoreMap.py: -------------------------------------------------------------------------------- 1 | #@ ImagePlus ("Label=Template") template 2 | #@ ImagePlus ("Label=Image") image 3 | #@ String (Label="Matching method",choices={"Normalised Square Difference", "Normalised cross-correlation", "Normalised 0-mean cross-correlation"}, value="Normalised 0-mean cross-correlation") method 4 | #@ Float ("Score Threshold", style="slider", min=0, max=1, stepSize=0.05) score_threshold 5 | ''' 6 | Compute correlation map between a template and an image 7 | currently only the normalsied corss correlation used 8 | ''' 9 | from Template_Matching.MatchTemplate_Module import MatchTemplate 10 | from org.bytedeco.javacpp.opencv_imgproc import threshold, CV_THRESH_TOZERO 11 | from org.bytedeco.javacpp.opencv_core import Mat, Scalar, subtract 12 | from ImageConverter import MatToImProc 13 | from ij import ImagePlus 14 | from ij.plugin.filter import MaximumFinder 15 | from ij.gui import Roi, PointRoi 16 | 17 | # Convert method string to the opencv corresponding index 18 | Dico_Method = {"Square difference":0,"Normalised Square Difference":1,"Cross-Correlation":2,"Normalised cross-correlation":3,"0-mean cross-correlation":4,"Normalised 0-mean cross-correlation":5} 19 | Method = Dico_Method[method] 20 | 21 | # Convert to ImageProcessor 22 | TempProc = template.getProcessor() 23 | ImProc = image.getProcessor() 24 | 25 | # Do matching 26 | CorrMapCV = MatchTemplate(TempProc, ImProc, Method) 27 | CorrMap = MatToImProc(CorrMapCV) 28 | CorrMapImp = ImagePlus("Score Map", CorrMap) 29 | CorrMapImp.show() 30 | 31 | 32 | # Threshold the corrmap (below threshold 0, above left untouched) 33 | if Method==1: 34 | # Invert the correlation map : min becomes maxima 35 | One = Scalar(1.0) 36 | CorrMapInvCV = subtract(One, CorrMapCV).asMat() 37 | #CorrMapInv = MatToImProc(CorrMapInvCV) 38 | #CorrMapInv = ImagePlus("Inverted", CorrMapInv) 39 | #CorrMapInv.show() 40 | 41 | 42 | # Apply a "TO ZERO" threshold on the correlation map : to compensate the fact that maxima finder does not have a threshold argument 43 | # TO ZERO : below the threshold set to 0, above left untouched 44 | # NB : 1-score_threshold since we have inverted the image : we want to look for minima of value 1-x in the inverted image 45 | CorrMapThreshCV = Mat() 46 | threshold(CorrMapInvCV, CorrMapThreshCV, 1-score_threshold, 0, CV_THRESH_TOZERO) 47 | #CorrMapThreshImp = ImagePlus("Thresholded", CorrMapThresh) 48 | #CorrMapThreshImp.show() 49 | 50 | else: 51 | CorrMapThreshCV = Mat() 52 | threshold(CorrMapCV, CorrMapThreshCV, score_threshold, 0, CV_THRESH_TOZERO) 53 | 54 | 55 | # Display 56 | CorrMapThresh = MatToImProc(CorrMapThreshCV) # Keep this conversion, not only for visualisation 57 | CorrMapThreshImp = ImagePlus("Score Map - thresholded", CorrMapThresh) 58 | CorrMapThreshImp.show() 59 | 60 | ## For both cases (Multi-Min/Max-detection) detect maxima on the thresholded map 61 | excludeOnEdge = False # otherwise miss quite a lot of them 62 | tolerance = 0 63 | Polygon = MaximumFinder().getMaxima(CorrMapThresh, tolerance, excludeOnEdge) 64 | roi = PointRoi(Polygon) 65 | CorrMapThreshImp.setRoi(roi) -------------------------------------------------------------------------------- /Fiji.app/scripts/Plugins/Multi-Template-Matching/Crop_Roi_ToStack.py: -------------------------------------------------------------------------------- 1 | #@ImagePlus imp 2 | ''' 3 | From a list of rectangular ROI associated to some slices of a stack in Fiji 4 | Crop each Roi from the image slice and append them to a stack 5 | The size of the stack is read from the first ROI 6 | 7 | NB : if using with MultiTemplate Matching, using a non square template, the rotation yield different dimensiosn that do not fit in the stack 8 | ''' 9 | from ij.plugin.frame import RoiManager 10 | from ij import ImageStack, ImagePlus 11 | 12 | RM = RoiManager.getRoiManager() 13 | n = RM.getCount() 14 | 15 | # get ROI dimension by reading first one 16 | Roi1 = RM.getRoi(0) 17 | Width = int(Roi1.getFloatWidth()) 18 | Height = int(Roi1.getFloatHeight()) 19 | Stack = ImageStack(Width, Height) 20 | 21 | for i in range(n): 22 | roi = RM.getRoi(i) 23 | ImIndex = roi.getPosition() 24 | #print ImIndex 25 | 26 | imp.setSlice(ImIndex) 27 | imp.setRoi(roi) 28 | Crop = imp.crop() 29 | Stack.addSlice( Crop.getProcessor() ) 30 | 31 | StackImp = ImagePlus("Stack",Stack) 32 | StackImp.show() 33 | 34 | -------------------------------------------------------------------------------- /Fiji.app/scripts/Plugins/Multi-Template-Matching/Template_Matching_Folder.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Object recognition using one or multiple template images 3 | this plugin searches for some templates (with eventual flipped/rotated versions) into some target image(s). 4 | 5 | input : 6 | - template : Path to template image or folder of template images 7 | - image : Path to image or folder of images in which to look for the template 8 | 9 | First, additionnal versions of the template are generated (flip+rotation) if selected 10 | Then each template is searched in the target image. This yield as set of correlation maps 11 | 12 | Minima/maxima in the correlation maps are detected, followed by Non-Maxima Supression when several object are explected in the target image 13 | - matchTemplate Method limited to normalised method to have correlation map in range 0-1 : easier to apply a treshold. 14 | 15 | The search region can be limited to a rectangular ROI, that is provided as a .roi file 16 | 17 | Requirements: 18 | - IJ-OpenCV update site 19 | ''' 20 | 21 | ## Import modules 22 | #@PrefService prefs 23 | from fiji.util.gui import GenericDialogPlus 24 | from ij import IJ 25 | from ij.io import Opener 26 | from ij.gui import Roi 27 | from os import listdir 28 | from os.path import join, isfile, isdir, basename 29 | from org.scijava.io.location import FileLocation 30 | 31 | #import time 32 | 33 | ## Home-Made module 34 | from Template_Matching.MatchTemplate_Module import getHit_Template, CornerToCenter 35 | from Template_Matching.Version import version 36 | from Template_Matching.NonMaximaSupression_Py2 import NMS 37 | 38 | 39 | def isImageFile(filePath): 40 | """Return false for filepath corresponding to directories or to non-image file.""" 41 | 42 | if basename(filePath).startswith(".") : 43 | return False 44 | 45 | opener = Opener() 46 | type = opener.getFileType(filePath) 47 | 48 | if type in [Opener.UNKNOWN, Opener.JAVA_OR_TEXT, Opener.ROI, Opener.TEXT] : 49 | return False 50 | 51 | return True 52 | 53 | 54 | 55 | ## Create GUI 56 | Win = GenericDialogPlus("Multiple Template Matching") 57 | Win.addDirectoryOrFileField("Template file or templates folder", prefs.get("TemplatePath", "template(s)")) 58 | Win.addDirectoryOrFileField("Image file or images folder", prefs.get("ImagePath", "image(s)")) 59 | Win.addFileField("Rectangular_search_ROI (optional)", prefs.get("RoiPath","searchRoi")) 60 | 61 | # Template pre-processing 62 | Win.addMessage("# Template(s) pre-processing") 63 | Win.addCheckbox("Flip_template_vertically", prefs.getInt("FlipV", False)) 64 | Win.addCheckbox("Flip_template_horizontally", prefs.getInt("FlipH", False)) 65 | Win.addStringField("Rotate template by ..(comma-separated)", prefs.get("Angles", "")) 66 | 67 | # Template matching parameters 68 | Win.addMessage("# Detection parameters") 69 | Win.addChoice("Matching_method", ["Normalised Square Difference","Normalised cross-correlation","Normalised 0-mean cross-correlation"], prefs.get("Method","Normalised 0-mean cross-correlation")) 70 | Win.addNumericField("Number_of_objects expected", prefs.getInt("N_hit",1),0) 71 | 72 | # Non-Maxima Suppression 73 | Win.addMessage("# Non-Maxima Suppression (if Nobjects > 1)") 74 | Win.addSlider("Score_Threshold", 0, 1, prefs.getFloat("Score_Threshold",0.5), 0.1) 75 | #Win.addNumericField("Min_peak_height relative to neighborhood ([0-1], decrease to get more hits)", prefs.getFloat("Tolerance",0.1), 2) 76 | Win.addSlider("Maximal_overlap between Bounding boxes", 0, 1, prefs.getFloat("MaxOverlap",0.4), 0.1) 77 | 78 | # Outputs 79 | Win.addMessage("# Outputs") 80 | Win.addCheckbox("Open_images as a stack (must have identical sizes)", prefs.getInt("ShowImages", True)) 81 | Win.addCheckbox("Add_ROI detected to ROI Manager", prefs.getInt("AddRoi", True)) 82 | Win.addCheckbox("Show_result table", prefs.getInt("ShowTable", False)) 83 | Win.addMessage(version) 84 | Win.addMessage("""If you use this plugin please cite : 85 | Thomas, L.S.V., Gehrig, J. 86 | Multi-template matching: a versatile tool for object-localization in microscopy images. 87 | BMC Bioinformatics 21, 44 (2020). https://doi.org/10.1186/s12859-020-3363-7""") 88 | Win.addHelp("https://github.com/multi-template-matching/MultiTemplateMatching-Fiji/wiki") 89 | 90 | Win.showDialog() 91 | 92 | if Win.wasOKed(): 93 | TemplatePath = Win.getNextString() 94 | ImagePath = Win.getNextString() 95 | RoiPath = Win.getNextString() 96 | flipv = Win.getNextBoolean() 97 | fliph = Win.getNextBoolean() 98 | angles = Win.getNextString() 99 | method = Win.getNextChoice() 100 | n_hit = int(Win.getNextNumber()) 101 | score_threshold = Win.getNextNumber() 102 | #tolerance = Win.getNextNumber() 103 | tolerance = 0 104 | max_overlap = Win.getNextNumber() 105 | show_images = Win.getNextBoolean() 106 | add_roi = Win.getNextBoolean() 107 | show_table = Win.getNextBoolean() 108 | 109 | # Save for persistence 110 | prefs.put("TemplatePath", TemplatePath) 111 | prefs.put("ImagePath", ImagePath) 112 | prefs.put("RoiPath", RoiPath) 113 | prefs.put("FlipV",flipv) 114 | prefs.put("FlipH",fliph) 115 | prefs.put("Angles", angles) 116 | prefs.put("Method", method) 117 | prefs.put("N_hit", n_hit) 118 | prefs.put("Score_Threshold", score_threshold) 119 | #prefs.put("Tolerance", tolerance) 120 | prefs.put("MaxOverlap", max_overlap) 121 | prefs.put("ShowImages", show_images) 122 | prefs.put("AddRoi", add_roi) 123 | prefs.put("ShowTable", show_table) 124 | 125 | # Convert method string to the opencv corresponding index 126 | Dico_Method = {"Square difference":0,"Normalised Square Difference":1,"Cross-Correlation":2,"Normalised cross-correlation":3,"0-mean cross-correlation":4,"Normalised 0-mean cross-correlation":5} 127 | Method = Dico_Method[method] 128 | 129 | if show_images: 130 | from ij import ImagePlus, ImageStack 131 | Stack_Image = ImageStack() 132 | Stack_Image_ImP = ImagePlus() 133 | 134 | if add_roi: 135 | from ij.plugin.frame import RoiManager 136 | from ij.gui import Roi 137 | RM = RoiManager() 138 | rm = RM.getInstance() 139 | 140 | if show_table: 141 | from ij.measure import ResultsTable 142 | from utils import AddToTable 143 | Table = ResultsTable().getResultsTable() # allows to append to an existing table 144 | 145 | 146 | ## Check if input are valid 147 | if n_hit<=0: 148 | raise Exception('The expected number of object should be at least 1') 149 | 150 | if score_threshold<0 or score_threshold>1: 151 | raise Exception('The score threshold should be in range [0,1]') 152 | 153 | #if tolerance<0 or tolerance>1: 154 | # raise Exception('Tolerance should be in range [0,1]') 155 | 156 | if max_overlap<0 or max_overlap>1: 157 | raise Exception('The max overlap should be in range [0,1]') 158 | 159 | 160 | ### Search ROI ? ### 161 | # Check if there is a searchRoi 162 | if RoiPath: 163 | from ij.io import RoiDecoder 164 | searchRoi = RoiDecoder.open(RoiPath) 165 | else: 166 | searchRoi = None 167 | 168 | # Check if it is a rectangular one 169 | if searchRoi and searchRoi.getTypeAsString()=="Rectangle": 170 | Bool_SearchRoi = True 171 | dX = int(searchRoi.getXBase()) 172 | dY = int(searchRoi.getYBase()) 173 | 174 | else: 175 | Bool_SearchRoi = False 176 | dX = dY = 0 177 | 178 | 179 | 180 | ## File or Folder 181 | # Template(s) 182 | if isfile(TemplatePath): # single template file 183 | 184 | if isImageFile(TemplatePath): 185 | ListPathTemplate = [TemplatePath] 186 | 187 | else: 188 | ListPathTemplate = [] 189 | IJ.error("No image found for template.") 190 | 191 | elif isdir(TemplatePath): # template folder 192 | ListPathTemplate = [] 193 | 194 | # Check extension 195 | for name in listdir(TemplatePath): 196 | 197 | FullPathTem = join(TemplatePath, name) 198 | 199 | if isImageFile(FullPathTem) : 200 | ListPathTemplate.append(FullPathTem) 201 | 202 | else: 203 | raise Exception("Template path does not exist") 204 | 205 | #print ListPathTemplate 206 | 207 | # Initialise list of templates (rather than opening them for every image iteration) 208 | List_Template = [ IJ.openImage(PathTemp) for PathTemp in ListPathTemplate ] 209 | 210 | 211 | 212 | 213 | # Image(s) 214 | if isfile(ImagePath): # single image path 215 | 216 | if isImageFile(ImagePath): 217 | ListPathImage = [ImagePath] 218 | 219 | else: 220 | ListPathImage = [] 221 | IJ.error("Selected file for image is not a recognized image file.") 222 | 223 | 224 | elif isdir(ImagePath): # image folder 225 | 226 | ListPathImage = [] # initialise 227 | 228 | for name in listdir(ImagePath): 229 | 230 | FullPathIm = join(ImagePath,name) 231 | 232 | if isImageFile(FullPathIm) : 233 | ListPathImage.append(FullPathIm) 234 | 235 | else: # neither a file path nor a folder path (ie non existing) 236 | raise Exception("Image path does not exist") 237 | 238 | ## Initialise Result table for time 239 | #TimeTable = ResultsTable() 240 | 241 | ## Loop over images for template matching and maxima detection 242 | for i, PathIm in enumerate(ListPathImage): 243 | 244 | if IJ.escapePressed(): 245 | IJ.resetEscape() # for next call 246 | raise KeyboardInterrupt("Escape was pressed") 247 | 248 | # Get the current image 249 | ImpImage = IJ.openImage(PathIm) 250 | if not ImpImage: continue # skip for certain file formats such as xml which are scijava compatible but not images 251 | ImName = ImpImage.getTitle() 252 | ImProc = ImpImage.getProcessor().duplicate() 253 | 254 | # Crop Image if searchRoi 255 | if Bool_SearchRoi: 256 | ImpImage.setRoi(searchRoi) 257 | ImpImage = ImpImage.crop() 258 | 259 | ## Start Timer here (dont count opening of the image) 260 | #Start = time.clock() 261 | 262 | # Initialise list before looping over templates 263 | Hits_BeforeNMS = [] 264 | 265 | ## Loop over template for matching against current image 266 | for ImpTemplate in List_Template: 267 | 268 | # Check that template is smaller than the searched image or ROI 269 | if Bool_SearchRoi and (ImpTemplate.height>searchRoi.getFloatHeight() or ImpTemplate.width>searchRoi.getFloatWidth()): 270 | IJ.log("The template "+ ImpTemplate.getTitle() +" is larger in width and/or height than the search region -> skipped") 271 | continue # go directly to the next for iteration 272 | 273 | elif ImpTemplate.width>ImpImage.width or ImpTemplate.height>ImpImage.height: 274 | IJ.log("The template "+ ImpTemplate.getTitle() + " is larger in width and/or height than the searched image-> skipped") 275 | continue # go directly to the next for iteration 276 | 277 | # Get hits for the current template (and his flipped and/or rotated versions) 278 | List_Hit = getHit_Template(ImpTemplate, ImpImage, flipv, fliph, angles, Method, n_hit, score_threshold, tolerance) # raher use ImagePlus as input to get the name of the template used 279 | 280 | # Store the hits 281 | Hits_BeforeNMS.extend(List_Hit) 282 | 283 | 284 | 285 | ### NMS ### 286 | #print "\n-- Hits before NMS --\n", 287 | #for hit in Hits_BeforeNMS: print hit 288 | 289 | # InterHit NMS if more than one hit 290 | if Method in [0,1]: 291 | Hits_AfterNMS = NMS(Hits_BeforeNMS, N=n_hit, maxOverlap=max_overlap, sortDescending=False) # only difference is the sorting 292 | 293 | else: 294 | Hits_AfterNMS = NMS(Hits_BeforeNMS, N=n_hit, maxOverlap=max_overlap, sortDescending=True) 295 | 296 | #print "\n-- Hits after NMS --\n" 297 | #for hit in Hits_AfterNMS : print hit 298 | 299 | 300 | 301 | 302 | ## Loop over final hits to generate ROI ## 303 | for hit in Hits_AfterNMS: 304 | 305 | #print hit 306 | 307 | if Bool_SearchRoi: # Add offset of search ROI 308 | hit['BBox'] = (hit['BBox'][0]+dX, hit['BBox'][1]+dY, hit['BBox'][2], hit['BBox'][3]) 309 | 310 | # Create detected ROI 311 | roi = Roi(*hit['BBox']) 312 | roi.setName(hit['TemplateName']) 313 | roi.setProperty("Score", str(hit["Score"]) ) 314 | roi.setPosition(i+1) # set ROI Z-position 315 | 316 | if add_roi: 317 | rm.add(None, roi, i+1) # Trick to be able to set Z-position when less images than the number of ROI. Here i is an digit index before the Roi Name 318 | 319 | if show_table: 320 | Xcorner, Ycorner = hit['BBox'][0], hit['BBox'][1] 321 | Xcenter, Ycenter = CornerToCenter(Xcorner, Ycorner, hit['BBox'][2], hit['BBox'][3]) 322 | 323 | Dico = {'Image':ImName, 'Template':hit['TemplateName'] ,'Xcorner':Xcorner, 'Ycorner':Ycorner, 'Xcenter':Xcenter, 'Ycenter':Ycenter, 'Score':hit['Score']} 324 | if add_roi: 325 | Dico['Roi Index'] = rm.getCount() 326 | AddToTable(Table, Dico, Order=("Image", "Template", "Score", "Roi Index", "Xcorner", "Ycorner", "Xcenter", "Ycenter")) 327 | else: 328 | AddToTable(Table, Dico, Order=('Image', 'Template', 'Score', 'Xcorner', 'Ycorner', 'Xcenter', 'Ycenter')) 329 | 330 | 331 | ## Display outputs 332 | if show_images: 333 | 334 | # Initialise a stack of proper size if not the case before 335 | if Stack_Image.getSize()==0: 336 | Stack_Image = ImageStack(ImProc.width, ImProc.height) # instead of using ImagePlus.getStack otherwise we loose the slice title for the 1st image 337 | 338 | # Add images to Stack 339 | Stack_Image.addSlice(ImName, ImProc) 340 | Stack_Image_ImP.setStack("Result", Stack_Image) 341 | 342 | # Update display 343 | Stack_Image_ImP.setSlice(i) 344 | Stack_Image_ImP.show() 345 | 346 | if add_roi: # Show All ROI + Associate ROI to slices 347 | rm.runCommand("Associate", "true") 348 | rm.runCommand("Show All with labels") 349 | 350 | 351 | ## Stop time here 352 | #Stop = time.clock() 353 | #Elapsed = Stop - Start # in seconds 354 | #TimeTable.incrementCounter() 355 | #TimeTable.addValue('Time(s)', Elapsed) 356 | 357 | 358 | # At the end, display result table 359 | if show_table: 360 | Table.show("Results") 361 | 362 | #TimeTable.show("BenchmarkTime") -------------------------------------------------------------------------------- /Fiji.app/scripts/Plugins/Multi-Template-Matching/Template_Matching_Image.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Object recognition using one or multiple template images 3 | this plugin search for one template (with eventual flipped/rotated version) into one target image. 4 | The 2 images should be already opened in Fiji. 5 | 6 | input : 7 | - template : ImagePlus of the object to search in the target image 8 | - image : ImagePlus or Stack 9 | 10 | First, additionnal versions of the template are generated (flip+rotation) if selected 11 | Then each template is searched in the target image. This yield as set of correlation maps 12 | 13 | Minima/maxima in the correlation maps are detected, followed by Non-Maxima Supression when several object are explected in the target image 14 | - matchTemplate Method limited to normalised method to have correlation map in range 0-1 : easier to apply a treshold. 15 | 16 | The search region can be limited to a rectangular ROI, that is drawn on the image/stack before execution of the plugin. 17 | 18 | Requirements: 19 | - IJ-OpenCV update site 20 | ''' 21 | #import time 22 | #from timeit import default_timer as timer 23 | 24 | #@PrefService prefs 25 | from Template_Matching.Version import version 26 | from fiji.util.gui import GenericDialogPlus 27 | # rest of imports below on purpose (otherwise searchRoi lost) 28 | 29 | ## Create GUI 30 | Win = GenericDialogPlus("Multiple Template Matching") 31 | Win.addImageChoice("Template", prefs.get("Template","Choice")) 32 | Win.addImageChoice("Image", prefs.get("Image", "Choice")) 33 | Win.addMessage("# Template pre-processing") 34 | Win.addCheckbox("Flip_template_vertically", prefs.getInt("FlipV", False)) 35 | Win.addCheckbox("Flip_template_horizontally", prefs.getInt("FlipH", False)) 36 | Win.addStringField("Rotate template by ..(comma-separated)", prefs.get("Angles", "")) 37 | Win.addMessage("# Detection parameters") 38 | Win.addChoice("Matching_method", ["Normalised Square Difference","Normalised cross-correlation","Normalised 0-mean cross-correlation"], prefs.get("Method","Normalised 0-mean cross-correlation")) 39 | Win.addNumericField("Number_of_objects expected", prefs.getInt("N_hit",1),0) 40 | Win.addMessage("# Non-Maxima Suppression (if N_object > 1)") 41 | Win.addSlider("Score_Threshold", 0, 1, prefs.getFloat("Score_Threshold",0.5), 0.1) 42 | #Win.addNumericField("Min_peak_height relative to neighborhood ([0-1], decrease to get more hits)", prefs.getFloat("Tolerance",0.1), 2) 43 | Win.addSlider("Maximal_overlap between Bounding boxes", 0, 1, prefs.getFloat("MaxOverlap",0.4), 0.1) 44 | Win.addMessage("# Outputs") 45 | Win.addCheckbox("Add_ROI detected to ROI manager", prefs.getInt("AddRoi", True)) 46 | Win.addCheckbox("Show_result table", prefs.getInt("ShowTable", False)) 47 | Win.addMessage(version) 48 | Win.addMessage("""If you use this plugin please cite : 49 | Thomas, L.S.V., Gehrig, J. 50 | Multi-template matching: a versatile tool for object-localization in microscopy images. 51 | BMC Bioinformatics 21, 44 (2020). https://doi.org/10.1186/s12859-020-3363-7""") 52 | Win.addHelp("https://github.com/multi-template-matching/MultiTemplateMatching-Fiji/wiki") 53 | 54 | Win.showDialog() 55 | 56 | if Win.wasOKed(): 57 | template = Win.getNextImage() 58 | image = Win.getNextImage() 59 | flipv = Win.getNextBoolean() 60 | fliph = Win.getNextBoolean() 61 | angles = Win.getNextString() 62 | method = Win.getNextChoice() 63 | n_hit = int(Win.getNextNumber()) 64 | score_threshold = Win.getNextNumber() 65 | #tolerance = Win.getNextNumber() 66 | tolerance = 0 67 | max_overlap = Win.getNextNumber() 68 | add_roi = Win.getNextBoolean() 69 | show_table = Win.getNextBoolean() 70 | 71 | # Save for persistence 72 | ImageName = image.getTitle() 73 | prefs.put("Template", template.getTitle()) 74 | prefs.put("Image", ImageName) 75 | prefs.put("FlipV",flipv) 76 | prefs.put("FlipH",fliph) 77 | prefs.put("Angles", angles) 78 | prefs.put("Method", method) 79 | prefs.put("N_hit", n_hit) 80 | prefs.put("Score_Threshold", score_threshold) 81 | #prefs.put("Tolerance", tolerance) 82 | prefs.put("MaxOverlap", max_overlap) 83 | prefs.put("AddRoi", add_roi) 84 | prefs.put("ShowTable", show_table) 85 | 86 | # Check if input are valid 87 | if n_hit<=0: 88 | raise Exception('The expected number of object should be at least 1') 89 | 90 | if score_threshold<0 or score_threshold>1: 91 | raise Exception('The score threshold should be in range [0,1]') 92 | 93 | #if tolerance<0 or tolerance>1: 94 | # raise Exception('Tolerance should be in range [0,1]') 95 | 96 | if max_overlap<0 or max_overlap>1: 97 | raise Exception('The max overlap should be in range [0,1]') 98 | 99 | 100 | ## Initialise variables before import (otherwise the ROI is lost) 101 | searchRoi = image.getRoi() 102 | 103 | ## Rectangle ROI ? 104 | if searchRoi and searchRoi.getTypeAsString()=="Rectangle": 105 | Bool_SearchRoi = True 106 | else: 107 | Bool_SearchRoi = False 108 | 109 | # Define offset 110 | if Bool_SearchRoi: 111 | dX = int(searchRoi.getXBase()) 112 | dY = int(searchRoi.getYBase()) 113 | else: 114 | dX = dY = 0 115 | 116 | 117 | ## Import modules 118 | from ij import IJ, ImagePlus 119 | from ij.gui import Roi 120 | 121 | ## Import HomeMade modules 122 | from Template_Matching.NonMaximaSupression_Py2 import NMS 123 | from Template_Matching.MatchTemplate_Module import getHit_Template, CornerToCenter 124 | 125 | 126 | ## Check that the template is smaller than the (possibly cropped) image 127 | if Bool_SearchRoi and (template.height>searchRoi.getFloatHeight() or template.width>searchRoi.getFloatWidth()): 128 | raise Exception('The template is larger in width and/or height than the searched Roi') 129 | 130 | elif template.height>image.height or template.width>image.width: 131 | raise Exception('The template is larger in width and/or height than the searched image') 132 | 133 | ### Initialize outputs ### 134 | if show_table: 135 | from ij.measure import ResultsTable 136 | from utils import AddToTable 137 | Table = ResultsTable().getResultsTable() # allows to append to an existing table 138 | 139 | if add_roi: 140 | from ij.plugin.frame import RoiManager 141 | RM = RoiManager() 142 | rm = RM.getInstance() 143 | 144 | 145 | # Convert method string to the opencv corresponding index 146 | Dico_Method = {"Square difference":0,"Normalised Square Difference":1,"Cross-Correlation":2,"Normalised cross-correlation":3,"0-mean cross-correlation":4,"Normalised 0-mean cross-correlation":5} 147 | Method = Dico_Method[method] 148 | 149 | 150 | # Loop over the images in the stack (or directly process if unique) 151 | imageStack = image.getStack() 152 | nSlice = image.getStackSize() 153 | 154 | for i in xrange(1,nSlice+1): 155 | 156 | if IJ.escapePressed(): 157 | IJ.resetEscape() # for next call 158 | raise KeyboardInterrupt("Escape was pressed") 159 | 160 | searchedImage = imageStack.getProcessor(i) # of slice i 161 | 162 | if Bool_SearchRoi: 163 | searchedImage.setRoi(searchRoi) 164 | searchedImage = searchedImage.crop() 165 | 166 | 167 | # Fix the name for searchImage 168 | if nSlice>1: 169 | SliceLabel = imageStack.getSliceLabel(i) 170 | 171 | if SliceLabel: # sometimes the slicelabel is none 172 | Title = SliceLabel.split('\n',1)[0] # split otherwise we get some unecessary information 173 | else: 174 | Title = image.getTitle() 175 | 176 | else: 177 | Title = image.getTitle() 178 | 179 | # Do the template(s) matching 180 | #Start = time.clock() 181 | #start = timer() 182 | Hits_BeforeNMS = getHit_Template(template, 183 | ImagePlus(Title, searchedImage), 184 | flipv, fliph, 185 | angles, 186 | Method, 187 | n_hit, 188 | score_threshold, 189 | tolerance) # template and image as ImagePlus (to get the name together with the image matrix) 190 | #Stop = time.clock() 191 | #IJ.log("getHit_Template took " + str(Stop-Start) + " seconds") 192 | 193 | ### NMS ### 194 | #IJ.log(str(len(Hits_BeforeNMS)) + " hit before NMS") 195 | 196 | #print "\n-- Hits before NMS --\n", 197 | #for hit in Hits_BeforeNMS : print hit 198 | 199 | # NMS if more than one hit before NMS. For n_hit=1 the NMS does not actually compute the IoU it will just take the best score 200 | #start_NMS = time.clock() 201 | if len(Hits_BeforeNMS)==1: 202 | Hits_AfterNMS = Hits_BeforeNMS 203 | 204 | elif Method in [0,1]: 205 | Hits_AfterNMS = NMS(Hits_BeforeNMS, N=n_hit, maxOverlap=max_overlap, sortDescending=False) # only difference is the sorting 206 | 207 | else: 208 | Hits_AfterNMS = NMS(Hits_BeforeNMS, N=n_hit, maxOverlap=max_overlap, sortDescending=True) 209 | 210 | 211 | #stop = timer() 212 | #print stop-start 213 | 214 | #stop_NMS = time.clock() 215 | #IJ.log("NMS duration(s): " + str(stop_NMS-start_NMS)) 216 | #print "\n-- Hits after NMS --\n" 217 | #for hit in Hits_AfterNMS : print hit 218 | 219 | # NB : Hits coordinates have not been corrected for cropping here ! Done in the next for loop 220 | 221 | 222 | # Loop over final hits to generate ROI 223 | for hit in Hits_AfterNMS: 224 | 225 | #print hit 226 | 227 | if Bool_SearchRoi: # Add offset of search ROI 228 | hit['BBox'] = (hit['BBox'][0]+dX, hit['BBox'][1]+dY, hit['BBox'][2], hit['BBox'][3]) 229 | 230 | # Create detected ROI 231 | roi = Roi(*hit['BBox']) 232 | roi.setName(hit['TemplateName']) 233 | roi.setProperty("Score", str(hit["Score"]) ) 234 | roi.setPosition(i) # set ROI Z-position 235 | #roi.setProperty("class", hit["TemplateName"]) 236 | 237 | image.setSlice(i) 238 | image.setRoi(roi) 239 | 240 | if add_roi: 241 | rm.add(None, roi, i) # Trick to be able to set Z-position when less images than the number of ROI. Here i is an digit index before the Roi Name 242 | 243 | # Show All ROI + Associate ROI to slices 244 | rm.runCommand("Associate", "true") 245 | rm.runCommand("Show All with labels") 246 | IJ.selectWindow(ImageName) # does not work always 247 | 248 | if show_table: 249 | Xcorner, Ycorner = hit['BBox'][0], hit['BBox'][1] 250 | Xcenter, Ycenter = CornerToCenter(Xcorner, Ycorner, hit['BBox'][2], hit['BBox'][3]) 251 | 252 | Dico = {'Image':hit['ImageName'],'Slice':i, 'Template':hit['TemplateName'] ,'Xcorner':Xcorner, 'Ycorner':Ycorner, 'Xcenter':Xcenter, 'Ycenter':Ycenter, 'Score':hit['Score']} # column order is defined below 253 | 254 | if add_roi: 255 | # Add ROI index to the result table 256 | Dico['Roi Index'] = rm.getCount() 257 | AddToTable(Table, Dico, Order=("Image", "Slice", "Template", "Score", "Roi Index", "Xcorner", "Ycorner", "Xcenter", "Ycenter")) 258 | else: 259 | AddToTable(Table, Dico, Order=("Image", "Slice", "Template", "Score", "Xcorner", "Ycorner", "Xcenter", "Ycenter")) 260 | 261 | 262 | 263 | # Display result table 264 | if show_table: 265 | Table.show("Results") -------------------------------------------------------------------------------- /Fiji.app/scripts/Plugins/Multi-Template-Matching/Template_Matching_ListImage.py: -------------------------------------------------------------------------------- 1 | #@ File[] (Label="Templates", style="file") template_files 2 | #@ File[] (label="Image for which to look for the template") image_files 3 | #@ File (label="Region of Interest (ROI) for search (optional)", required=false) roi_file 4 | #@ Boolean (Label="Flip template vertically") flipv 5 | #@ Boolean (Label="Flip template horizontally") fliph 6 | #@ String (Label="Additional rotation angles separated by ," ,required=False) angles 7 | #@ String (Label="Matching method",choices={"Normalised Square Difference", "Normalised cross-correlation", "Normalised 0-mean cross-correlation"}, value="Normalised 0-mean cross-correlation") method 8 | #@ Integer (Label="Expected number of objects", min=1) n_hit 9 | #@ String (visibility="MESSAGE", value="The parameters below are used only if more than 1 template are expected in the image") doc 10 | #@ Float (Label="Score Threshold", min=0, max=1, value=0.5, stepSize=0.1, style="slider") score_threshold 11 | #@ Float (Label="Maximal overlap between Bounding boxes", min=0, max=1, value=0.4, stepSize=0.1, style="slider") max_overlap 12 | #@ String (visibility="MESSAGE", value="Output") out 13 | #@ Boolean (Label="Open images (as stack ie images must have identical dimensions)") show_images 14 | #@ Boolean (Label="Add ROI to ROI Manager") add_roi 15 | #@ Boolean (Label="Show result table") show_table 16 | #@ String (visibility="MESSAGE", value="
If you use this plugin please cite:Multi-template matching: a versatile tool for object-localization in microscopy images.
BMC Bioinformatics 21, 44 (2020)
https://doi.org/10.1186/s12859-020-3363-7
") disclaimer 17 | ''' 18 | previous field : 19 | Float (Label="Min peak height relative to neighborhood (0-1, decrease to get more hits)", min=0, max=1, value=0.1, stepSize=0.1) tolerance 20 | Boolean (Label="Display correlation map(s)") show_map 21 | 22 | Object recognition using one or multiple template images 23 | ie this macro search for N templates (with eventual flipped/rotated version) into L target images. 24 | 25 | input : 26 | - template_files : list of template path 27 | - image_files : list of image path for which we want to search a template 28 | 29 | First, additionnal versions of the template are generated (flip+rotation) if selected 30 | Then each template is searched in the target image. This yield as set of correlation maps 31 | 32 | Minima/maxima in the correlation maps are detected, followed by Non-Maxima Supression when several object are explected in the target image 33 | - matchTemplate Method limited to normalised method to have correlation map in range 0-1 : easier to apply a treshold. 34 | 35 | The search region can be limited to a rectangular ROI, that is provided as a .roi file. 36 | 37 | Requirements: 38 | - IJ-OpenCV update site 39 | 40 | 41 | ## TO DO : 42 | - order of the column in result table 43 | 44 | ## NB : 45 | - If show_images is true, the images must have the same dimensions 46 | 47 | - The multifile input is not yet macro recordable. An alternative is to use the folder input version 48 | 49 | - Method limited to normalised method to have correlation map in range 0-1 : easier to apply a treshold. 50 | Otherwise normalising relative to maxima of each correlation map is not good since this result in having the global maxima to always be one, 51 | eventhough its correlation value was not one. 52 | ''' 53 | ### IMPORT ### 54 | import time # for benchmark 55 | from ij import IJ # ImageJ1 import 56 | 57 | ## Home-Made module 58 | from Template_Matching.MatchTemplate_Module import getHit_Template, CornerToCenter 59 | from Template_Matching.NonMaximaSupression_Py2 import NMS 60 | 61 | if show_images: 62 | from ij import ImagePlus, ImageStack 63 | Stack_Image = ImageStack() 64 | Stack_Image_ImP = ImagePlus() 65 | 66 | if add_roi: 67 | from ij.plugin.frame import RoiManager 68 | from ij.gui import Roi 69 | RM = RoiManager() 70 | rm = RM.getInstance() 71 | 72 | if show_table: 73 | from ij.measure import ResultsTable 74 | from utils import AddToTable 75 | Table = ResultsTable().getResultsTable() # allows to append to an existing table 76 | 77 | 78 | # Convert method string to the opencv corresponding index 79 | Dico_Method = {"Square difference":0,"Normalised Square Difference":1,"Cross-Correlation":2,"Normalised cross-correlation":3,"0-mean cross-correlation":4,"Normalised 0-mean cross-correlation":5} 80 | Method = Dico_Method[method] 81 | 82 | # Initialise time 83 | ListTime = [] 84 | 85 | # Initialise list of templates (rather than opening them for every image iteration) 86 | List_Template = [ IJ.openImage( templ_file.getPath() ) for templ_file in template_files ] 87 | 88 | 89 | 90 | ### Search ROI ? ### 91 | # Check if there is a searchRoi 92 | if roi_file: 93 | from ij.io import RoiDecoder 94 | searchRoi = RoiDecoder.open(roi_file.getPath()) 95 | else: 96 | searchRoi = None 97 | 98 | # Check if it is a rectangular one 99 | if searchRoi and searchRoi.getTypeAsString()=="Rectangle": 100 | Bool_SearchRoi = True 101 | else: 102 | Bool_SearchRoi = False 103 | 104 | # Define Offset for BBox if proper searchRoi 105 | if Bool_SearchRoi: 106 | dX = searchRoi.getXBase() 107 | dY = searchRoi.getYBase() 108 | else: 109 | dX = dY = 0 110 | 111 | 112 | 113 | 114 | ## Loop over templates for template matching and maxima detection 115 | tolerance = 0 # deactivate the flood fill of the max detector 116 | for i, im_file in enumerate(image_files): 117 | 118 | if IJ.escapePressed(): 119 | IJ.resetEscape() # for next call 120 | raise KeyboardInterrupt("Escape was pressed") 121 | 122 | # Get the current image 123 | PathIm = im_file.getPath() 124 | ImpImage = IJ.openImage(PathIm) 125 | ImName = ImpImage.getTitle() 126 | ImProc = ImpImage.getProcessor().duplicate() 127 | 128 | # Crop Image if searchRoi 129 | if Bool_SearchRoi: 130 | ImpImage.setRoi(searchRoi) 131 | ImpImage = ImpImage.crop() 132 | 133 | ## Start Timer here (dont count opening of the image) 134 | #Start = time.clock() 135 | 136 | # Initialise list before looping over templates 137 | Hits_BeforeNMS = [] 138 | 139 | ## Loop over template for matching against current image 140 | for ImpTemplate in List_Template: 141 | 142 | # Check that template is smaller than the searched image 143 | if Bool_SearchRoi and (ImpTemplate.height>searchRoi.getFloatHeight() or ImpTemplate.width>searchRoi.getFloatWidth()): 144 | IJ.log("The template "+ ImpTemplate.getTitle() +" is larger in width and/or height than the search region -> skipped") 145 | continue # go directly to the next for iteration 146 | 147 | elif ImpTemplate.width>ImpImage.width or ImpTemplate.height>ImpImage.height: 148 | IJ.log("The template "+ ImpTemplate.getTitle() + " is larger in width and/or height than the searched image-> skipped") 149 | continue # go directly to the next for iteration 150 | 151 | # Get hits for the current template (and his flipped and/or rotated versions) 152 | List_Hit = getHit_Template(ImpTemplate, ImpImage, flipv, fliph, angles, Method, n_hit, score_threshold, tolerance) # raher use ImagePlus as input to get the name of the template used 153 | 154 | # Store the hits 155 | Hits_BeforeNMS.extend(List_Hit) 156 | 157 | 158 | 159 | ### NMS ### 160 | #print "\n-- Hits before NMS --\n", 161 | #for hit in Hits_BeforeNMS: print hit 162 | 163 | # InterHit NMS if more than one hit 164 | if Method in [0,1]: 165 | Hits_AfterNMS = NMS(Hits_BeforeNMS, N=n_hit, maxOverlap=max_overlap, sortDescending=False) # only difference is the sorting 166 | 167 | else: 168 | Hits_AfterNMS = NMS(Hits_BeforeNMS, N=n_hit, maxOverlap=max_overlap, sortDescending=True) 169 | 170 | #print "\n-- Hits after NMS --\n" 171 | #for hit in Hits_AfterNMS : print hit 172 | 173 | 174 | 175 | ## Stop time here (we dont benchmark display time) 176 | #Stop = time.clock() 177 | #Elapsed = Stop - Start # in seconds 178 | #ListTime.append(Elapsed) 179 | 180 | 181 | 182 | ## Loop over final hits to generate ROI, result table... ### 183 | for hit in Hits_AfterNMS: 184 | 185 | if Bool_SearchRoi: # Add the offset of the search ROI 186 | hit['BBox'] = (hit['BBox'][0]+dX, hit['BBox'][1]+dY, hit['BBox'][2], hit['BBox'][3]) 187 | 188 | if add_roi: 189 | roi = Roi(*hit['BBox']) 190 | roi.setName(hit['TemplateName']) 191 | roi.setProperty("Score", str(hit["Score"]) ) 192 | roi.setPosition(i+1) # set slice position 193 | rm.add(None, roi, i+1) # Trick to be able to set slice when less images than ROI. Here i is an digit index before the Roi Name 194 | 195 | if show_table: 196 | Xcorner, Ycorner = hit['BBox'][0], hit['BBox'][1] 197 | Xcenter, Ycenter = CornerToCenter(Xcorner, Ycorner, hit['BBox'][2], hit['BBox'][3]) 198 | 199 | Dico = {'Image':ImName, 'Template':hit['TemplateName'] ,'Xcorner':Xcorner, 'Ycorner':Ycorner, 'Xcenter':Xcenter, 'Ycenter':Ycenter, 'Score':hit['Score']} 200 | if add_roi: 201 | Dico['Roi Index'] = rm.getCount() 202 | AddToTable(Table, Dico, Order=("Image", "Template", "Score", "Roi Index", "Xcorner", "Ycorner", "Xcenter", "Ycenter")) 203 | else: 204 | AddToTable(Table, Dico, Order=('Image', 'Template', 'Score', 'Xcorner', 'Ycorner', 'Xcenter', 'Ycenter')) 205 | 206 | Table.show("Results") 207 | 208 | 209 | 210 | ## Display outputs 211 | if show_images: 212 | 213 | # Initialise a stack of proper size if not the case before 214 | if Stack_Image.getSize()==0: 215 | Stack_Image = ImageStack(ImProc.width, ImProc.height) # instead of using ImagePlus.getStack otherwise we loose the slice title for the 1st image 216 | 217 | # Add images to Stack 218 | Stack_Image.addSlice(ImName, ImProc) 219 | Stack_Image_ImP.setStack("Result", Stack_Image) 220 | 221 | # Update display 222 | Stack_Image_ImP.setSlice(i) 223 | Stack_Image_ImP.show() 224 | 225 | if add_roi: 226 | # Show All ROI + Associate ROI to slices 227 | rm.runCommand("Associate", "true") 228 | rm.runCommand("Show All with labels") 229 | 230 | #for i in ListTime: 231 | #print i -------------------------------------------------------------------------------- /Fiji.app/scripts/Plugins/Multi-Template-Matching/Template_Matching_ListTemplate.py: -------------------------------------------------------------------------------- 1 | #@ File[] (Label="Templates", style="file") template_files 2 | #@ ImagePlus (label="Image for which to look for the template") image 3 | #@ Boolean (Label="Flip template vertically") flipv 4 | #@ Boolean (Label="Flip template horizontally") fliph 5 | #@ String (Label="Additional rotation angles separated by ," ,required=False) angles 6 | #@ String (Label="Matching method",choices={"Normalised Square Difference", "Normalised cross-correlation", "Normalised 0-mean cross-correlation"}, value="Normalised 0-mean cross-correlation") method 7 | #@ int (Label="Expected number of templates", min=1) n_hit 8 | #@ String (visibility="MESSAGE", value="The parameters below are used only if more than 1 template are expected in the image") doc 9 | #@ Float (Label="Score Threshold (0-1)", min=0, max=1, value=0.5, stepSize=0.1) score_threshold 10 | #@ Float (Label="Min peak height relative to neighborhood (0-1, decrease to get more hits)", min=0, max=1, value=0.1, stepSize=0.1) tolerance 11 | #@ Float (Label="Maximal overlap between Bounding boxes (0-1)",min=0, max=1, value=0.4, stepSize=0.1) max_overlap 12 | #@ String (visibility="MESSAGE", value="Output") out 13 | #@ Boolean (Label="Add ROI to ROI manager") show_roi 14 | #@ Boolean (Label="Show result table") show_table 15 | ''' 16 | previous field : Boolean (Label="Display correlation map(s)") show_map 17 | 18 | Requires ImageJ 1.52i to have the possibility to fill the background while rotating for 16-bit images 19 | 20 | FIJI macro to do template matching 21 | input : 22 | - template_files : list of template path 23 | - image : ImagePlus for the target image 24 | ie this macro search for one template (with eventual flipped/rotated version)into one target image. 25 | The target image should be already open in Fiji. 26 | 27 | First of all, additionnal versions of the template are generated (flip+rotation) 28 | For the resulting list of templates the search is carried out and results in a list of correlation maps 29 | 30 | Minima/maxima in the correlation map are detected, followed by Non-Maxima Supression in case of multiple correlation map/templates 31 | 32 | 33 | TO DO : 34 | - order of the column in result table 35 | - use steerable tempalte matching see steerable detector BIG Lausanne 36 | 37 | NB : 38 | - The multifile input is not yet macro recordable. An alternative is to use a folder input and to process the content of the folder (but not as flexible) 39 | 40 | - (currently no search ROi so not applicable) Delete the previous ROI for every new Run otherwise 1st ROI is used to limit the search 41 | 42 | - Method limited to normalised method to have correlation map in range 0-1 : easier to apply a treshold. 43 | Otherwise normalising relative to maxima of each correlation map is not good since this result in having the global maxima to always be one, 44 | eventhough its correlation value was not one. 45 | Another possibility would be to have an absolute threshold (realtive to the correlation score) and a relative threshold (relative to the maxima of this particular map) 46 | 47 | The multifile input is not yet macro recordable. An alternative is to use a folder input and to process the content of the folder (but not as flexible) 48 | ''' 49 | ## Initialise variables before import (otherwise the ROI is lost) 50 | ImageName = image.getTitle() 51 | searchRoi = image.getRoi() 52 | 53 | ## Rectangle ROI ? 54 | if searchRoi and searchRoi.getTypeAsString()=="Rectangle": 55 | Bool_SearchRoi = True 56 | else: 57 | Bool_SearchRoi = False 58 | 59 | # Define offset 60 | if Bool_SearchRoi: 61 | image = image.crop() 62 | dX = int(searchRoi.getXBase()) 63 | dY = int(searchRoi.getYBase()) 64 | else: 65 | dX = dY = 0 66 | 67 | 68 | ### IMPORT MODULES (after retrieving ROI) ### 69 | from ij import IJ 70 | 71 | # Home-Made module 72 | from Template_Matching.MatchTemplate_module import getHit_Template, CornerToCenter 73 | from Template_Matching.NonMaximaSupression_Py2 import NMS 74 | 75 | 76 | # Convert method string to the index 77 | Dico_Method = {"Square difference":0,"Normalised Square Difference":1,"Cross-Correlation":2,"Normalised cross-correlation":3,"0-mean cross-correlation":4,"Normalised 0-mean cross-correlation":5} 78 | Method = Dico_Method[method] 79 | 80 | 81 | # Initialise list of hit before looping 82 | Hits_BeforeNMS = [] 83 | 84 | ## Loop over templates for template matching and maxima detection 85 | for temp_file in template_files: 86 | 87 | # Get ImageProcessor for the current template 88 | PathTemp = temp_file.getPath() 89 | ImpTemplate = IJ.openImage(PathTemp) 90 | 91 | # Check that template is smaller than the searched image 92 | if ImpTemplate.width>image.width or ImpTemplate.height>image.height: 93 | raise Exception('The current template is larger in width and/or height than the searched image') 94 | 95 | # Get hits for the current template (and his flipped and/or rotated versions) 96 | List_Hit = getHit_Template(ImpTemplate, image, flipv, fliph, angles, Method, n_hit, score_threshold, tolerance) 97 | 98 | # Store the hits 99 | Hits_BeforeNMS.extend(List_Hit) 100 | 101 | 102 | 103 | ### NMS inter template ### 104 | print "\n-- Hits before NMS --\n" 105 | for hit in Hits_BeforeNMS: print hit 106 | 107 | # NMS if more than one hit 108 | if Method in [0,1]: 109 | Hits_AfterNMS = NMS(Hits_BeforeNMS, N=n_hit, maxOverlap=max_overlap, sortDescending=False) # only difference is the sorting 110 | 111 | else: 112 | Hits_AfterNMS = NMS(Hits_BeforeNMS, N=n_hit, maxOverlap=max_overlap, sortDescending=True) 113 | 114 | print "\n-- Hits after NMS --\n" 115 | for hit in Hits_AfterNMS: print hit 116 | 117 | 118 | 119 | 120 | ### Outputs ### 121 | if show_table: 122 | from ij.measure import ResultsTable 123 | from utils import AddToTable 124 | 125 | Table = ResultsTable().getResultsTable() # allows to append to an existing table 126 | 127 | if show_roi: 128 | from ij.plugin.frame import RoiManager 129 | from ij.gui import Roi 130 | 131 | # Initialise RoiManager 132 | RM = RoiManager() 133 | rm = RM.getInstance() 134 | 135 | # Show All ROI + Associate ROI to slices 136 | rm.runCommand("Associate", "true") 137 | rm.runCommand("Show All with labels") 138 | 139 | 140 | # Loop over final hits to generate ROI, result table... 141 | for hit in Hits_AfterNMS: 142 | 143 | if Bool_SearchRoi: # Add offset of searchRoi 144 | hit['BBox'] = (hit['BBox'][0]+dX, hit['BBox'][1]+dY, hit['BBox'][2], hit['BBox'][3]) 145 | 146 | if show_roi: 147 | roi = Roi(*hit['BBox']) 148 | roi.setName(hit['TemplateName']) 149 | rm.addRoi(roi) 150 | 151 | if show_table: 152 | Xcorner, Ycorner = hit['BBox'][0], hit['BBox'][1] 153 | Xcenter, Ycenter = CornerToCenter(Xcorner, Ycorner, hit['BBox'][2], hit['BBox'][3]) 154 | Dico = {"Image":ImageName, 'Template':hit['TemplateName'] ,'Xcorner':Xcorner, 'Ycorner':Ycorner, 'Xcenter':Xcenter, 'Ycenter':Ycenter, 'Score':hit['Score']} 155 | AddToTable(Table, Dico, Order=("Image", "Template", "Score", "Xcorner", "Ycorner", "Xcenter", "Ycenter")) 156 | 157 | 158 | ## Finally update display 159 | if show_roi: IJ.selectWindow(ImageName) 160 | if show_table: Table.show("Results") 161 | -------------------------------------------------------------------------------- /Images/Acquifer_Logo_60k_cmyk_300dpi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Images/Acquifer_Logo_60k_cmyk_300dpi.png -------------------------------------------------------------------------------- /Images/EggDetected.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Images/EggDetected.png -------------------------------------------------------------------------------- /Images/FishRoi.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Images/FishRoi.JPG -------------------------------------------------------------------------------- /Images/GUI_Fiji_Annotated.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Images/GUI_Fiji_Annotated.png -------------------------------------------------------------------------------- /Images/HeadRoi.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Images/HeadRoi.JPG -------------------------------------------------------------------------------- /Images/ImageInlife.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Images/ImageInlife.png -------------------------------------------------------------------------------- /Images/MarieCurie.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Images/MarieCurie.jpg -------------------------------------------------------------------------------- /Images/MontageEgg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Images/MontageEgg.png -------------------------------------------------------------------------------- /Images/Montage_Head.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Images/Montage_Head.png -------------------------------------------------------------------------------- /Images/NMS.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Images/NMS.png -------------------------------------------------------------------------------- /Images/RoiManager.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Images/RoiManager.JPG -------------------------------------------------------------------------------- /Images/Screen_MatchImage.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Images/Screen_MatchImage.JPG -------------------------------------------------------------------------------- /Images/Screen_MatchListImage.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Images/Screen_MatchListImage.JPG -------------------------------------------------------------------------------- /Images/TemplateMatching.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Images/TemplateMatching.png -------------------------------------------------------------------------------- /Images/TemplateMatchingFolder.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Images/TemplateMatchingFolder.JPG -------------------------------------------------------------------------------- /Images/TemplateMatching_Montage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Images/TemplateMatching_Montage.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![DOI](https://zenodo.org/badge/DOI/10.1186/s12859-020-3363-7.svg)](https://doi.org/10.1186/s12859-020-3363-7) 2 | ![Twitter Follow](https://img.shields.io/twitter/follow/LauLauThom?style=social) 3 | 4 | # Installation 5 | 6 | ## Via the Fiji updater 7 | Tick the __Multi-Template-Matching__ AND __IJ-OpenCV__ update site of the Fiji udpater. 8 | A new entry will show up in the Plugin Menu (all the way down) after restarting Fiji. 9 | See how to [activate an update site](https://imagej.net/How_to_follow_a_3rd_party_update_site). 10 | 11 | ## Manual installation 12 | You can also do a manual installation by copying the files in the right place. 13 | This can be useful if you would like to use a previous version that is not available via the update site, but which is archived in the releases tab. 14 | You still need to tick the IJ-OpenCV update site in the Fiji updater to install the dependencies. 15 | 16 | Then you can download the files either on the main page above this readme, by clicking the green button with the arrow pointing down *Code* then *Download ZIP*. 17 | You can download the zip of previous versions on the [release tab](https://github.com/multi-template-matching/MultiTemplateMatching-Fiji/releases), below asset select *Source code (zip)*. 18 | Unzip the zip file, and on Windows, drag the folder Fiji.app from the unzipped directory, and drop it on the directory Fiji.app of your existing Fiji installation. 19 | The idea is to merge both Fiji.app directories, in Windows this drag and dropping will automatically copy the files in the corresponding subdirectories. 20 | Restart Fiji then. 21 | If the drag and dropping does not work for you, you just have to copy the files from the unzziped directory to the corresponding directories in your Fiji installation. 22 | If some directories (ex: Lib in Fiji.app/jars) does not exist, just create them. 23 | 24 | # Documentation 25 | Template matching is an algorithm that can be used for object-detections in images. 26 | The algorithm computes the probability to find one (or several) template images provided by the user. 27 | See the [wiki section](https://github.com/multi-template-matching/MultiTemplateMatching-Fiji/wiki/) for the documentation, or the [website](https://multi-template-matching.github.io/Multi-Template-Matching/) of the project. 28 | 29 | You can find a similar implementation in: 30 | - [Python](https://github.com/multi-template-matching/MultiTemplateMatching-Python) 31 | - [KNIME](https://github.com/multi-template-matching/MultipleTemplateMatching-KNIME) relying on the python implementation 32 | 33 | ## Video tutorial 34 | Playlist on [YouTube](https://www.youtube.com/playlist?list=PLHZOgc1s26MJ8QjYau7NcG5k0zh9SjHpo) 35 | [![Tuto](https://img.youtube.com/vi/KlzIqSG5XBU/0.jpg)](https://youtu.be/KlzIqSG5XBU) 36 | 37 | 38 | # Citation 39 | If you use this implementation for your research, please cite: 40 | 41 | Thomas, L.S.V., Gehrig, J. _Multi-template matching: a versatile tool for object-localization in microscopy images._ 42 | BMC Bioinformatics 21, 44 (2020). https://doi.org/10.1186/s12859-020-3363-7 43 | 44 | Download the citation as a .ris file from the journal website, [here](https://bmcbioinformatics.biomedcentral.com/articles/10.1186/s12859-020-3363-7.ris). 45 | 46 | # Related resources 47 | ## IJ-OpenCV 48 | This plugin is using OpenCV in Fiji thanks to [IJ-OpenCV](https://github.com/joheras/IJ-OpenCV). 49 | 50 | see also: 51 | _Domínguez, César, Jónathan Heras, and Vico Pascual. "IJ-OpenCV: Combining ImageJ and OpenCV for processing images in biomedicine." Computers in biology and medicine 84 (2017): 189-194._ 52 | 53 | 54 | # Licence 55 | Creative Commons License
The content of this wiki (including illustrations and videos) is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. 56 | 57 | As a derived work of IJ-OpenCV, the source codes are licensed under GPL-3. 58 | 59 | # Origin of the work 60 | This work has been part of the PhD project of **Laurent Thomas** under supervision of **Dr. Jochen Gehrig** at ACQUIFER. 61 | 62 | Fish 63 | 64 | # Funding 65 | This project has received funding from the European Union’s Horizon 2020 research and innovation program under the Marie Sklodowska-Curie grant agreement No 721537 ImageInLife. 66 | 67 |

68 | ImageInLife 69 | MarieCurie 70 |

71 | 72 | 73 | # Examples 74 | 75 | ## Zebrafish head detection 76 | Fish 77 | MontageHead 78 | 79 | Dataset available on Zenodo 80 | [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.2650162.svg)](https://doi.org/10.5281/zenodo.2650162) 81 | 82 | 83 | ## Medaka larvae detections 84 | MedakaEgg 85 | MontageEgg 86 | 87 | Image courtesy Jakob Gierten (COS, Heidelberg) 88 | Dataset available on Zenodo 89 | [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.2650147.svg)](https://doi.org/10.5281/zenodo.2650147) 90 | -------------------------------------------------------------------------------- /Tuto/2-step-TemplateMatching/2step-TemplateMatching.html: -------------------------------------------------------------------------------- 1 | 2 | 16 | 17 | 18 |

This macro allows to do a 2-step template matching, the 2 templates and the image should be opend in Fiji already.
19 | The first template allows to find an object and the second template finds a sub-object within the previously found object.
20 | Therefore the second template must be smaller than the first one.
21 | Both detection (1st and 2nd template) are returned in the ROI manager.

22 |

NB : Make sure the ROI Manager is empty before running this macro

23 |

 24 | 
 25 | 
 26 |  
 27 | 
28 |

Get image names

29 |
selectImage(temp1); 
 30 | Temp1_title = getTitle(); 
 31 | //print(Temp1_title); 
 32 |  
 33 | selectImage(temp2); 
 34 | Temp2_title = getTitle(); 
 35 | //print(Temp2_title); 
 36 |  
 37 | selectImage(image); 
 38 | Image_title = getTitle(); 
 39 | //print(Image_title); 
 40 |  
 41 | 
42 |

Call 1st template matching

43 |
run("Template Matching Image", "template=" + Temp1_title + " image=" + Image_title + " rotate=[] matching_method=[Normalised 0-mean cross-correlation] number_of_objects=1 score_threshold=0.50 maximal_overlap=0.25 add_roi"); 
 44 | 
 45 | 
 46 | 
47 |

Loop over stack of ROI

48 |
setBatchMode(true); // do not open extracted slices 
 49 | selectImage(image); 
 50 | Roi.remove; 
 51 | n = nSlices; 
 52 | nRoi_old = roiManager("count"); // Roi of the 1st template matching 
 53 | for (i=1; i<=n; i++) { 
 54 |  	 
 55 | 	// Isolate slice from stack (to perform the second template matching with a custom search ROI for that slice) 
 56 | 	selectImage(image); //important here to select back the image when entering a new iteration, during looping the slice is selected 
 57 | 	setSlice(i); 
 58 | 	Roi.remove; 
 59 | 	run("Duplicate...", "title=Slice_"+i); // The isolated slice has for title "Slice_i" 
 60 | 	 
 61 | 	// Set search ROI on isolated slice 
 62 | 	roiManager("select", i-1); // i-1 since ROI manager starts at 0 
 63 | 	Roi.getBounds(x, y, width, height); 
 64 | 	makeRectangle(x, y, width, height); 
 65 | 	//print(x,y,width,height); 
 66 |  
 67 | 	// Run template matching on slice with search ROI 
 68 | 	run("Template Matching Image", "template=" + Temp2_title + " image=Slice_" + i +" flip_template_vertically rotate=[] matching_method=[Normalised 0-mean cross-correlation] number_of_objects=2 score_threshold=0.50 maximal_overlap=0.25 add_roi show_result"); 
 69 | 	 
 70 | 	// Close hidden Slice image 
 71 | 	//selectImage("Slice_"+i); 
 72 | 	//close(); 
 73 | 	 
 74 | 	// Rename and Set Z-position of the last found ROI 
 75 | 	nRoi_new = roiManager("count"); 
 76 | 	 
 77 | 	for (j=1; j<=nRoi_new-nRoi_old; j++) { 
 78 |  
 79 | 		roiManager("select", nRoi_new-j); 
 80 | 		run("Properties... ", "position="+i); // Set slice position 
 81 | 		InitName = call("ij.plugin.frame.RoiManager.getName", nRoi_new-j); 
 82 | 		roiManager("rename", i + substring(InitName, 1)); 
 83 | 	} 
 84 | 	 
 85 | 	// Update the count 
 86 | 	nRoi_old = nRoi_new; 
 87 |  
 88 | } 
 89 |  
 90 | 
91 |

Image

92 | 93 | 94 | 95 | 96 |
ImageSliceTemplateScoreRoi IndexXcornerYcornerXcenterYcenter
Slice_11temp21.0002651897712939
Slice_11temp2_Vertical_Flip0.794365710017181043
97 |

Again make sure that all ROI are displayed and associated to the slices

98 |
roiManager("Show All"); 
 99 | roiManager("Associate", "true"); 
100 | 
101 | 102 | 103 | 104 | -------------------------------------------------------------------------------- /Tuto/2-step-TemplateMatching/2step-TemplateMatching.ijm: -------------------------------------------------------------------------------- 1 | /* 2 | This macro allows to do a 2-step template matching, the 2 templates and the image should be opend in Fiji already. 3 | The first template allows to find an object and the second template finds a sub-object within the previously found object. 4 | Therefore the second template must be smaller than the first one. 5 | Both detection (1st and 2nd template) are returned in the ROI manager. 6 | 7 | NB : Make sure the ROI Manager is empty before running this macro 8 | 9 | */ 10 | #@ImagePlus (Label="Template1") temp1 11 | #@ImagePlus (Label="Template2") temp2 12 | #@ImagePlus (Label="Image") image 13 | 14 | /* # Get image names */ 15 | selectImage(temp1); 16 | Temp1_title = getTitle(); 17 | //print(Temp1_title); 18 | 19 | selectImage(temp2); 20 | Temp2_title = getTitle(); 21 | //print(Temp2_title); 22 | 23 | selectImage(image); 24 | Image_title = getTitle(); 25 | //print(Image_title); 26 | 27 | /* # Call 1st template matching */ 28 | run("Template Matching Image", "template=" + Temp1_title + " image=" + Image_title + " rotate=[] matching_method=[Normalised 0-mean cross-correlation] number_of_objects=1 score_threshold=0.50 maximal_overlap=0.25 add_roi"); 29 | 30 | 31 | /* # Loop over stack of ROI */ 32 | setBatchMode(true); // do not open extracted slices 33 | selectImage(image); 34 | Roi.remove; 35 | n = nSlices; 36 | nRoi_old = roiManager("count"); // Roi of the 1st template matching 37 | for (i=1; i<=n; i++) { 38 | 39 | // Isolate slice from stack (to perform the second template matching with a custom search ROI for that slice) 40 | selectImage(image); //important here to select back the image when entering a new iteration, during looping the slice is selected 41 | setSlice(i); 42 | Roi.remove; 43 | run("Duplicate...", "title=Slice_"+i); // The isolated slice has for title "Slice_i" 44 | 45 | // Set search ROI on isolated slice 46 | roiManager("select", i-1); // i-1 since ROI manager starts at 0 47 | Roi.getBounds(x, y, width, height); 48 | makeRectangle(x, y, width, height); 49 | //print(x,y,width,height); 50 | 51 | // Run template matching on slice with search ROI 52 | run("Template Matching Image", "template=" + Temp2_title + " image=Slice_" + i +" flip_template_vertically rotate=[] matching_method=[Normalised 0-mean cross-correlation] number_of_objects=2 score_threshold=0.50 maximal_overlap=0.25 add_roi show_result"); 53 | 54 | // Close hidden Slice image 55 | //selectImage("Slice_"+i); 56 | //close(); 57 | 58 | // Rename and Set Z-position of the last found ROI 59 | nRoi_new = roiManager("count"); 60 | 61 | for (j=1; j<=nRoi_new-nRoi_old; j++) { 62 | 63 | roiManager("select", nRoi_new-j); 64 | run("Properties... ", "position="+i); // Set slice position 65 | InitName = call("ij.plugin.frame.RoiManager.getName", nRoi_new-j); 66 | roiManager("rename", i + substring(InitName, 1)); 67 | } 68 | 69 | // Update the count 70 | nRoi_old = nRoi_new; 71 | 72 | } 73 | 74 | /* # Again make sure that all ROI are displayed and associated to the slices */ 75 | roiManager("Show All"); 76 | roiManager("Associate", "true"); -------------------------------------------------------------------------------- /Tuto/2-step-TemplateMatching/Fish.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/multi-template-matching/MultiTemplateMatching-Fiji/47b1600f02c6bacf72c1250c9c22eb3e32809592/Tuto/2-step-TemplateMatching/Fish.png -------------------------------------------------------------------------------- /Tuto/2-step-TemplateMatching/README.md: -------------------------------------------------------------------------------- 1 | This tutorial was generated with the ImageJ-Macro-Markdown extension provided by Robert Haase 2 | See https://github.com/haesleinhuepf/imagejmacromarkdown 3 | 4 | This macro allows to do a 2-step template matching, the 2 templates and the image should be opend in Fiji already. 5 | The first template allows to find an object and the second template finds a sub-object within the previously found object. 6 | Therefore the second template must be smaller than the first one. 7 | Both detection (1st and 2nd template) are returned in the ROI manager. 8 | 9 | NB : Make sure the ROI Manager is empty before running this macro 10 | 11 | # Get image names 12 | ```java 13 | selectImage(temp1); 14 | Temp1_title = getTitle(); 15 | //print(Temp1_title); 16 | 17 | selectImage(temp2); 18 | Temp2_title = getTitle(); 19 | //print(Temp2_title); 20 | 21 | selectImage(image); 22 | Image_title = getTitle(); 23 | //print(Image_title); 24 | 25 | ``` 26 | # Call 1st template matching 27 | ```java 28 | run("Template Matching Image", "template=" + Temp1_title + " image=" + Image_title + " rotate=[] matching_method=[Normalised 0-mean cross-correlation] number_of_objects=1 score_threshold=0.50 maximal_overlap=0.25 add_roi"); 29 | 30 | 31 | ``` 32 | # Loop over stack of ROI 33 | ```java 34 | setBatchMode(true); // do not open extracted slices 35 | selectImage(image); 36 | Roi.remove; 37 | n = nSlices; 38 | nRoi_old = roiManager("count"); // Roi of the 1st template matching 39 | for (i=1; i<=n; i++) { 40 | 41 | // Isolate slice from stack (to perform the second template matching with a custom search ROI for that slice) 42 | selectImage(image); //important here to select back the image when entering a new iteration, during looping the slice is selected 43 | setSlice(i); 44 | Roi.remove; 45 | run("Duplicate...", "title=Slice_"+i); // The isolated slice has for title "Slice_i" 46 | 47 | // Set search ROI on isolated slice 48 | roiManager("select", i-1); // i-1 since ROI manager starts at 0 49 | Roi.getBounds(x, y, width, height); 50 | makeRectangle(x, y, width, height); 51 | //print(x,y,width,height); 52 | 53 | // Run template matching on slice with search ROI 54 | run("Template Matching Image", "template=" + Temp2_title + " image=Slice_" + i +" flip_template_vertically rotate=[] matching_method=[Normalised 0-mean cross-correlation] number_of_objects=2 score_threshold=0.50 maximal_overlap=0.25 add_roi show_result"); 55 | 56 | // Close hidden Slice image 57 | //selectImage("Slice_"+i); 58 | //close(); 59 | 60 | // Rename and Set Z-position of the last found ROI 61 | nRoi_new = roiManager("count"); 62 | 63 | for (j=1; j<=nRoi_new-nRoi_old; j++) { 64 | 65 | roiManager("select", nRoi_new-j); 66 | run("Properties... ", "position="+i); // Set slice position 67 | InitName = call("ij.plugin.frame.RoiManager.getName", nRoi_new-j); 68 | roiManager("rename", i + substring(InitName, 1)); 69 | } 70 | 71 | // Update the count 72 | nRoi_old = nRoi_new; 73 | 74 | } 75 | 76 | ``` 77 | ![Image](Fish.png) 78 | 79 | 80 | 81 | 82 |
ImageSliceTemplateScoreRoi IndexXcornerYcornerXcenterYcenter
Slice_11temp21.0002651897712939
Slice_11temp2_Vertical_Flip0.794365710017181043
83 | 84 | # Again make sure that all ROI are displayed and associated to the slices 85 | ```java 86 | roiManager("Show All"); 87 | roiManager("Associate", "true"); 88 | ``` 89 | --------------------------------------------------------------------------------