Code Monkey home page Code Monkey logo

multitemplatematching-python's Introduction

Binder Twitter Follow Say Thanks!

Multi-Template-Matching

Multi-Template-Matching is a python package to perform object-recognition in images using one or several smaller template images.
The main function MTM.matchTemplates returns the best predicted locations provided either a score_threshold and/or the expected number of objects in the image.

The branch opencl contains some test using the UMat object to run on GPU, but it is actually slow, which can be expected for small dataset as the transfer of the data between the CPU and GPU is slow.

News

  • Version 2.0.0 got rid of the dependency on pandas, the list of hit is simply a python list. The new version also features extensive type hints in functions
  • 03/03/2023 : Version 1.6.4 contributed by @bartleboeuf comes with speed enhancement thanks to parallelizing of the individual template searches. Thanks for this first PR !!
  • 10/11/2021 : You might be interested to test the newer python implementation which is more object-oriented and only relying on scikit-image and shapely.* https://github.com/multi-template-matching/mtm-python-oop

Installation

Using pip in a python environment, pip install Multi-Template-Matching
Once installed, import MTMshould work.
Example jupyter notebooks can be downloaded from the tutorial folder of the github repository and executed in the newly configured python environement.

Install in dev mode

If you want to contribute or experiment with the source code, you can install the package "from source", by first downloading or cloning the repo.
Then opening a command prompt in the repo's root directory (the one containing this README) and calling pip install -e . (mind the final dot).

  • the -e flag stands for editable and make sure that any change to the source code will be directly reflected when you import the package in your script
  • the . just tell pip to look for the package to install in the current directory

Documentation

The wiki section of the repo contains a mini API documentation with description of the key functions of the package.
The website of the project contains some more general documentation.

Tips and tricks

  • matchTemplates expects for the template a list of tuples with one tuple per template in the form (a string identifier for the template, array for the template image). You can generate such list of tuples, from separate lists of the label and template images as following
listLabel    = []  # this one should have the string identifier for each template
listTemplate = [] # this one should have the image array for each template, both lists should have the same length
listTemplateTuple = zip(listLabel, listTemplate)

Similarly, from the list of hits returned by matchTemplates (or NMS), you can get individual lists for the label, bounding-boxes and scores, using listLabel, listBbox, listScore = zip(*listHit)

  • To have a nicer formatting (one list item per row) when printing the list of detected hits, you can use the pprint function from the pprint module (for pretty print).
    It's usually not needed in notebooks (see the example notebooks).
from pprint import pprint
pprint(listHit)
  • Before version 2.0.0, most functions were returning or accepting pandas DataFrame for the list of hit. You can still get such DataFrame from the list of hits returned by MTM v2.0.0 and later, using the command below
import pandas as pd

listLabel, listBbox, listScore = zip(*listHit)

df = pd.DataFrame({"Label":listLabel,
				   "bounding box":listBbox,
				   "Score":listScore})

print(df)

You can also stick to previous version of MTM by specifying the version to pip install, or in a requirements.txt or environment.yml `pip install "Multi-Template-Matching < 2.0.0"

Examples

Check out the jupyter notebook tutorial for some example of how to use the package.
You can run the tutorials online using Binder, no configuration needed ! (click the Binder banner on top of this page).
To run the tutorials locally, install the package using pip as described above, then clone the repository and unzip it.
Finally open a jupyter-notebook session in the unzipped folder to be able to open and execute the notebook.
The wiki section of this related repository also provides some information about the implementation.

Citation

If you use this implementation for your research, please cite:

Thomas, L.S.V., Gehrig, J. 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

Download the citation as a .ris file from the journal website, here.

Releases

Previous github releases were archived to Zenodo, but the best is to use pip to install specific versions.
DOI

Related projects

See this repo for the implementation as a Fiji plugin.
Here for a KNIME workflow using Multi-Template-Matching.

Origin of the work

This work has been part of the PhD project of Laurent Thomas under supervision of Dr. Jochen Gehrig at ACQUIFER.

ACQUIFER

Funding

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.

ImageInLife MarieCurie

multitemplatematching-python's People

Contributors

bart-leboeuf avatar dependabot[bot] avatar imagejan avatar laulauthom avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

multitemplatematching-python's Issues

The required opencv-python-headless version could not be found

When I try to use pip install it gives me this error because it can't find this version of opencv-python-headless. I tried using pip install to install the latest opencv-python-headless, which is 4.2.0.34, but when I tried to install your package it still tried to grab the older version dependency and returned that error.
I've made sure that I uninstalled previous opencv-python versions before doing this too.

(venv) C:\Users\Stuart\PycharmProjects\bot_tutorial1>pip install Multi-Template-Matching
Collecting Multi-Template-Matching
  Using cached Multi_Template_Matching-1.5.3-py3-none-any.whl (22 kB)
Collecting scikit-image
  Using cached scikit_image-0.17.1-cp38-cp38-win32.whl (10.6 MB)
Requirement already satisfied: numpy in c:\users\stuart\pycharmprojects\bot_tutorial1\venv\lib\site-packages (from Multi-Template-Matching) (1.18.4)
ERROR: Could not find a version that satisfies the requirement opencv-python-headless==4.1.0.25 (from Multi-Template-Matching) (from versions: 3.4.8.29, 3.4.9.31, 3.4.9.33, 4.1.2.30, 4.2.0.32, 4.2.0.34)
ERROR: No matching distribution found for opencv-python-headless==4.1.0.25 (from Multi-Template-Matching)

Possible outside Jupyter?

Hi. Is it possible to use MTM outside of Jupyter? For example, in Visual Studio Code, using Anaconda/Python3.7 (and not a Jupyter notebook)?

Problem with images

I am trying to use this for detecting cracks on metal surfaces. I am getting this error (copied in the end). I have attached the code and images to reproduce this error. Can you please help out?

Error:


Traceback (most recent call last):
File "/Users/pallavidubey/Documents/MultiTemplateMatching-Python/tutorials/SampleError.py", line 41, in
Hits = matchTemplates(listTemplate, im1, score_threshold=0.9, method=5, maxOverlap=0)
File "/Users/pallavidubey/Documents/MultiTemplateMatching-Python/MTM/init.py", line 271, in matchTemplates
tableHit = findMatches(listTemplates, image, method, N_object, score_threshold, searchBox)
File "/Users/pallavidubey/Documents/MultiTemplateMatching-Python/MTM/init.py", line 149, in findMatches
_ = future.result()
File "/Users/pallavidubey/mambaforge/envs/mtm/lib/python3.9/concurrent/futures/_base.py", line 439, in result
return self.__get_result()
File "/Users/pallavidubey/mambaforge/envs/mtm/lib/python3.9/concurrent/futures/_base.py", line 391, in __get_result
raise self._exception
File "/Users/pallavidubey/mambaforge/envs/mtm/lib/python3.9/concurrent/futures/thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
File "/Users/pallavidubey/Documents/MultiTemplateMatching-Python/MTM/init.py", line 201, in _multi_compute
corrMap = computeScoreMap(template, image, method, mask=mask)
File "/Users/pallavidubey/Documents/MultiTemplateMatching-Python/MTM/init.py", line 87, in computeScoreMap
return cv2.matchTemplate(image, template, method, mask=mask)
cv2.error: OpenCV(4.7.0) /Users/xperience/GHA-OCV-Python/_work/opencv-python/opencv-python/opencv/modules/imgproc/src/templmatch.cpp:588: error: (-215:Assertion failed) corr.rows <= img.rows + templ.rows - 1 && corr.cols <= img.cols + templ.cols - 1 in function 'crossCorr'
SampleError.zip

Use of masks possible?

If we use method = TM_CCORR_NORMED, are we able to use a mask (as one can with OpenCV's matchTemplate)?

Or are there any other ways to search for something other than a rectangle? For example:

r

rmask

Getting findMatches to work when a template doesn't fit the searchBox

To speed up the matchTemplates function I decided to first run some image preprocessing and extract rectangles representing my regions of interest. With some templates being smaller than others I often get rectangles that only fit the smaller templates. When a template bigger than the currrent searchbox is tried, the error

  • cv2.error: (-215:Assertion failed) _img.size().height <= _templ.size().height && ;_img.size().width <= _templ.size().width in function 'cv::matchTemplate'

occurs on

  • init line 143 corrMap = computeScoreMap(template, image, method, mask=mask)

I bandaided the issue by wrapping that line in a try except block, but some logic to check sizes earlier in the function would probably save time.

License

Hi @LauLauThom

Really useful.
Would it be possible to change this to a more permissive license such as MIT ?
With GPL it is difficult to bundle this with other applications.

Typo?

Hi. Is it possible this is a typo?

`- sortAscending : use True when low score means better prediction (Difference-based score), True otherwise (Correlation score)`

(Should it say "False otherwise"?)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.