Title: How to find functions by name in OpenCV - PyImageSearch

URL Source: https://pyimagesearch.com/2015/08/31/how-to-find-functions-by-name-in-opencv/

Published Time: 2015-08-31T14:00:02+00:00

Markdown Content:
[![Image 1: opencv_func_names_examples](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20408'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/08/opencv_func_names_examples.jpg)

OpenCV can be a big, hard to navigate library, _especially_ if you are just getting started learning computer vision and image processing.

The [release of OpenCV 3](https://pyimagesearch.com/2015/06/08/opencv-3-0-released-and-the-coming-changes-to-the-pyimagesearch-blog/) has only further complicated matters, moving a few important functions around and even slightly altering their names (the `cv2.cv.BoxPoints` vs. `cv2.boxPoints` methods come to mind off the top of my head).

While a good IDE can help you search and find a particular function based on only a few keystrokes, sometimes you won’t have access to your IDE. And if you’re trying to develop code that is compatible with _**both**_ OpenCV 2.4 and OpenCV 3, then you’ll need to _programmatically_ determine if a given function is available (whether via [version detection](https://pyimagesearch.com/2015/08/10/checking-your-opencv-version-using-python/) or function listing).

Enter the `find_function` method, now part of the [imutils](https://github.com/jrosebr1/imutils) library, that can help you search and lookup OpenCV methods _simply by providing a query string_.

In the rest of this blog post I’ll show you how to _quickly and_ _programmatically_ search and lookup functions in the OpenCV library using only simple Python methods.

![Image 2](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20128%20128'%3E%3C/svg%3E)

#### Looking for the source code to this post?

[Jump Right To The Downloads Section](#download-the-code)

Dumping all OpenCV function names and attributes
------------------------------------------------

A quick way to view _all_ OpenCV functions and attributes exposed to the Python bindings is to use the built-in Python `dir` function, which is used to return a list of names in the current local scope.

Assuming you have OpenCV installed and a Python shell ready, we can use the `dir` method to create a list of all OpenCV methods and attributes available to us:

\>>> import cv2
>>> funcs = dir(cv2)
>>> for f in funcs:
...     print(f)
... 
ACCESS\_FAST
ACCESS\_MASK
ACCESS\_READ
ACCESS\_RW
ACCESS\_WRITE
ADAPTIVE\_THRESH\_GAUSSIAN\_C
ADAPTIVE\_THRESH\_MEAN\_C
AGAST\_FEATURE\_DETECTOR\_AGAST\_5\_8
AGAST\_FEATURE\_DETECTOR\_AGAST\_7\_12D
AGAST\_FEATURE\_DETECTOR\_AGAST\_7\_12S
AGAST\_FEATURE\_DETECTOR\_NONMAX\_SUPPRESSION
AGAST\_FEATURE\_DETECTOR\_OAST\_9\_16
AGAST\_FEATURE\_DETECTOR\_THRESHOLD
AKAZE\_DESCRIPTOR\_KAZE
AKAZE\_DESCRIPTOR\_KAZE\_UPRIGHT
AKAZE\_DESCRIPTOR\_MLDB
AKAZE\_DESCRIPTOR\_MLDB\_UPRIGHT
AKAZE\_create
...
waitKey
warpAffine
warpPerspective
watershed
xfeatures2d
ximgproc
xphoto

While this method does indeed give us the list of attributes and functions inside OpenCV, it requires a _manual scan_ or a _grep_ of the list to find a particular function.

**Personally, I like to use this raw list of method names if I have a rough idea of what you’re looking for** (kind of like a _“I’ll know it when I see it”_ type of situation); otherwise, I look to use the `find_function` method of `imutils` to quickly narrow down the search space — similar to grep’ing the output of `dir(cv2)` .

Searching the OpenCV library for (partial) function names
---------------------------------------------------------

Let’s start off this section by defining our `find_function` method:

\# import the necessary packages
from \_\_future\_\_ import print\_function
import cv2
import re

def find\_function(name, pretty\_print=True, module=None):
	# if the module is None, initialize it to to the root \`cv2\`
	# library
	if module is None:
		module = cv2

	# grab all function names that contain \`name\` from the module
	p = ".\*{}.\*".format(name)
	filtered = filter(lambda x: re.search(p, x, re.IGNORECASE), dir(module))
	
	# check to see if the filtered names should be returned to the
	# calling function
	if not pretty\_print:
		return filtered

	# otherwise, loop over the function names and print them
	for (i, funcName) in enumerate(filtered):
		print("{}. {}".format(i + 1, funcName))

if \_\_name\_\_ == "\_\_main\_\_":
	find\_function("blur")

**Lines 2-4** start off by importing our necessary packages. We’ll need `cv2` for our OpenCV bindings and `re` for Python’s built-in regular expression functionality.

We define our `find_function` method on **Line 6**. This method requires a single required argument, the (partial) `name` of the function we want to search `cv2` for. We’ll also accept two optional arguments: `pretty_print` which is a boolean indicating whether the results should be returned as a list or neatly formatted to our console; and `module` which is the root-module or sub-module of the OpenCV library.

We’ll initialize `module` to be `cv2` , the root-module, but we could also pass in a sub-module such as `xfeatures2d` . In either case, the `module` will be searched for partial function/attribute matches to `name` .

The actual search takes place on **Lines 13 and 14** where we apply a regular expression to determine if any attribute/function name inside of `module` contains the supplied `name` .

**Lines 18 and 19** make a check to see if we should return the list of `filtered` functions to the calling function; otherwise, we loop over the function names and print them to our console (**Lines 22 and 23**).

Finally, **Line 26** takes our `find_function` method for a test drive by searching for functions containing the `blur` in their name.

To see our `find_function` method in action, just open a terminal and execute the following command:

$ python find\_function.py
1. GaussianBlur
2. blur
3. medianBlur

As our output shows, it seems there are three functions inside of OpenCV that contain the text `blur` , including `cv2.GaussianBlur` , `cv2.blur` , and `cv2.medianBlur` .

A real-world example of finding OpenCV functions by name
--------------------------------------------------------

As I already mentioned earlier in this post, the `find_functions` method is already part of the [imutils](https://github.com/jrosebr1/imutils) library. You can install `imutils` via `pip` :

$ pip install imutils

If you already have `imutils` installed on your system, be sure to upgrade it to the latest version:

$ pip install --upgrade imutils

Our goal in this project is to write a Python script to detect the _**[hardcopy edition of Practical Python and OpenCV + Case Studies](https://pyimagesearch.com/practical-python-opencv/)**_ (which is set to be released on **Wednesday, August 16th at 12:00 EST**, so be sure to mark your calendars!) in an image and draw a _its bounding contour_ surrounding it:

[![Image 3: Our goal is to find the outline (i.e. contours) of the original book (left) and then draw the outline on the book (right).](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20394'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/08/opencv_func_names_input.jpg)

**Figure 1:** Our goal is to find the original book in the image _(left)_ and then draw the outline on the book _(right)_.

Open up a new file, name it `find_book.py` , and let’s get coding:

\# import the necessary packages
import numpy as np
import imutils
import cv2

# load the image containing the book
image = cv2.imread("ppao\_hardcopy.png")
orig = image.copy()

# convert the image to grayscale, threshold it, and then perform a
# series of erosions and dilations to remove small blobs from the
# image
gray = cv2.cvtColor(image, cv2.COLOR\_BGR2GRAY)
thresh = cv2.threshold(gray, 40, 255, cv2.THRESH\_BINARY)\[1\]
thresh = cv2.erode(thresh, None, iterations=2)
thresh = cv2.dilate(thresh, None, iterations=2)

We start off by loading our image from disk on **Line 7**. We then do some basic image processing on **Lines 13-16**, including conversion to grayscale, thresholding, and a series of erosions and dilations to remove any small blobs from the thresholded image. Our output thresholded image looks like this:

[![Image 4: Figure 3: The thresholded, binary representation of the book image.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20386%20450'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/08/opencv_func_name_thresh.jpg)

**Figure 3:** The thresholded, binary representation of the book image.

However, in order to _draw the contour_ surrounding the book, I first need to _find the outline of the book itself_.

Let’s pretend that I’m stuck and I don’t know what the name of the function is that finds the outline of an object in an image — **but I do recall that “outlines” are called “contours” in OpenCV.**

By firing up a shell and using the `find_function` in `imutils` , I quickly ascertain that that I am looking for the `cv2.findContours` function:

$ python
>>> import imutils
>>> imutils.find\_function("contour")
1. contourArea
2. drawContours
3. findContours
4. isContourConvex

Now that I know I am using the `cv2.findContours` method, I need to figure out what contour extraction flag should be used for the function. I only want to return _external_ contours (i.e the outer-most outlines) so I’ll need to look up that attribute as well:

\>>> imutils.find\_function("external")
1. RETR\_EXTERNAL

Got it. I need to use the `cv2.RETR_EXTERNAL` flag. Now that I have that settled, I can finish up my Python script:

\# find contours in the thresholded image, keeping only the largest
# one
cnts = cv2.findContours(thresh.copy(), cv2.RETR\_EXTERNAL,
	cv2.CHAIN\_APPROX\_SIMPLE)
cnts = imutils.grab\_contours(cnts)
c = max(cnts, key=cv2.contourArea)
cv2.drawContours(image, \[c\], -1, (0, 255, 255), 3)

# show the output image
thresh = np.dstack(\[thresh\] \* 3)
cv2.imshow("Output", np.hstack(\[orig, thresh, image\]))
cv2.waitKey(0)

**Lines 20-22** makes a call to `cv2.findContours` to find the _external outlines_ of the objects (thanks to the `cv2.RETR_EXTERNAL` attribute) in the thresholded image.

We’ll then take the largest contour found (which is presumed to be the outline of the book) and draw the outline on our image (**Lines 23 and 24**).

Finally, **Lines 27-29** show our output images.

To see my script in action, I just fire up a terminal and issue the following command:

$ python find\_book.py

[![Image 5: Figure 2: Our original input image (left), the thresholded, binary representation of the image (center), and the contour drawn surrounding the book (right).](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20600%20274'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2015/08/opencv_func_names_output.jpg)

**Figure 3:** Our original input image (left), the thresholded, binary representation of the image (center), and the contour drawn surrounding the book (right).

Sure enough, we’ve been able to detect and draw the outline of the book without a problem!

### What's next? We recommend [PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend).

**Course information:**  
84 total classes • 114+ hours of on-demand code walkthrough videos • Last updated: February 2024  
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled

**I strongly believe that if you had the right teacher you could _master_ computer vision and deep learning.**

Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?

That’s _not_ the case.

All you need to master computer vision and deep learning is for someone to explain things to you in _simple, intuitive_ terms. _And that’s exactly what I do_. My mission is to change education and how complex Artificial Intelligence topics are taught.

If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to _successfully_ and _confidently_ apply computer vision to your work, research, and projects. Join me in computer vision mastery.

**Inside PyImageSearch University you'll find:**

*   ✓ **84 courses** on essential computer vision, deep learning, and OpenCV topics
*   ✓ **84 Certificates** of Completion
*   ✓ **114+ hours** of on-demand video
*   ✓ **Brand new courses released _regularly_**, ensuring you can keep up with state-of-the-art techniques
*   ✓ **Pre-configured Jupyter Notebooks in Google Colab**
*   ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
*   ✓ Access to **centralized code repos for _all_ 536+ tutorials** on PyImageSearch
*   ✓ **Easy one-click downloads** for code, datasets, pre-trained models, etc.
*   ✓ **Access** on mobile, laptop, desktop, etc.

[Click here to join PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend)

Summary
-------

In this blog post we learned how to get the names of all functions and attributes in OpenCV that are exposed to the Python bindings.

We then built a Python function to programmatically search these function/attribute names via a text query. This function has been included in the [imutils](https://github.com/jrosebr1/imutils) package.

Finally, we explored how OpenCV function filtering can be used in your every-day workflow to increase productivity and facilitate quick function lookup. We demonstrated this by building a small Python script detect the presence of a book in an image.

![Image 6](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20410%20567'%3E%3C/svg%3E)

#### Download the Source Code and FREE 17-page Resource Guide

Enter your email address below to get a .zip of the code and a **FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning.** Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!