Our first Python and OpenCV project

Based on the minimal project structure that was shown in the previous section, we are going to create our first Python and OpenCV project. This project has the following structure:

helloopencv/

├── images/

├── .gitignore
├── helloopencv.py
├── LICENSE
├── README.rst
├── requirements.txt
├── setup.py
└── helloopencvtests.py

README.rst (.rst extension) follows a basic structure, which was shown in the previous section. Python and ReStructuredText (RST) are deeply linked—RST is the format of docutils and sphinx (the de facto standard for documenting python code). RST is used both to document objects via docstrings, and to write additional documentation. If you go to the official Python documentation (https://docs.python.org/3/library/stdtypes.html), you can view the RST source of each page (https://raw.githubusercontent.com/python/cpython/3.6/Doc/library/stdtypes.rst). Using RST for the README.rst makes it directly compatible with the entire documentation setup. In fact, README.rst is often the cover page of a project's documentation. 

There are some RST editors you can use to help you write the README.rst. You can also use some online editors. For example, the online Sphinx editor is a good choice (https://livesphinx.herokuapp.com/).

The .gitignore file specifies intentionally untracked files that Git should ignore (https://git-scm.com/docs/gitignore). .gitignore tells git which files (or patterns) Git should ignore. It is usually used to avoid committing transient files from your working directory that are not useful to other collaborators, such as compilation products and temporary files that IDEs create. Open https://github.com/github/gitignore/blob/master/Python.gitignore to see a .gitignore file that you can include in your Python projects.

setup.py (see the previous section for a deeper description), it is a Python file that is usually shipped with libraries or programs, also written in Python. Its purpose is to correctly install the software. A very complete example of this file can be seen at https://github.com/pypa/sampleproject/blob/master/setup.py, which is full of comments to help you understand how to adapt it to your needs. This file is proposed by the Python Packaging Authority (PyPa) (https://www.pypa.io/en/latest/). One key point is in connection with the packages option, as we can read in the aforementioned setup.py file.

You can just specify package directories manually here if your project is simple. Or you can use find_packages(). Alternatively, if you just want to distribute a single Python file, use the py_modules argument instead as follows, which will expect a file
called my_module.py to exist, py_modules=["my_module"]

Therefore, in our case, py_modules =["helloopencv"] is used.

Additionally, setup.py allows you to easily install Python packages. Often it is enough to write the following:

$ python setup.py install

Therefore, if we want to install this simple package, we can write the previous command, python setup.py install, inside the helloopencv folder. For example, in Windows, run the following command:

C:\...\helloopencv>python setup.py install

You should see something like this:

 running install
...
...
Installed c:\python37\lib\site-packages\helloopencv-0.1-py3.7.egg
Processing dependencies for helloopencv==0.1
...
...
Finished processing dependencies for helloopencv==0.1

When finished, helloopencv is installed in our system (like any other Python package). You can also install helloopencv with pip, pip install .inside the helloopencv folder. For example, in Windows, run the following command:

C:\...\helloopencv>pip install .

You should see something like this:

 Processing c:\...\helloopencv
...
...
Successfully installed helloopencv-0.1

This indicates that helloopencv has been installed successfully. To use this package, we can write a Python file and import the helloopencv package. Alternatively, we can perform a quick use of this package by importing it directly from the Python interpreter. Following this second approach, you can open Command Prompt, import the package, and make use of it. First, open Command Prompt, then type python to run the interpreter:

C:\...\helloopencv>python
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Once the interpreter is loaded, we can import the package:

>>> import helloopencv
helloopencv.py is being imported into another module
>>>

The helloopencv.py is being imported into another module output is a message from the helloopencv package (specifically from the helloopencv.py file) indicating that this file has been imported. Therefore, this message indicates that the module has been successfully imported. Once imported, we can make use of it. For example, we can call the show_message method:

>>> helloopencv.show_message()
'this function returns a message'
>>>

We can see that the result of calling this method is a message that is printed on the screen. This method is a simple way to know that everything has been installed correctly because it involves installing, importing, and making use of a function from the package. Furthermore, we can call a more useful method contained in the helloopencv package. You can, for example, call the load_image method to load an image from disk and afterwards, you can display it using the show_image method:

>>> image = helloopencv.load_image("C:/.../images/logo.png")
>>> helloopencv.show_image(image)

Here, the parameter of the load_image function is the path of an image from your computer. In this case, the logo.png image is loaded. After calling the show_image method, an image should be displayed. To close the window, a key must be pressed. Then you should be able to write in the interpreter again. To see all the methods that are available in the helloopencv package, you can open the helloopencv.py file with your favorite editor or IDE and have a look at it. In this Python file, you can see some methods that conform to our first Python project:

  • show_message(): This function prints the this function returns a message message.
  • load_image(): This function loads an image from its path.
  • show_image(): This function shows an image once it has been loaded.
  • convert_to_grayscale(): This function converts an image to grayscale once it has been loaded.
  • write_image_to_disk(): This function saves an image on disk.

All of these methods perform simple and basic operations. Most of them make use of the OpenCV library, which is imported at the beginning of this file (import cv2). Do not worry about the Python code contained in this file, because only basic operations and calls to the OpenCV library are performed. 

You can execute the helloopencv.py script without installing the package. To execute this file, you should run the python helloopencv.py command once Command Prompt is opened:

 C:\...\helloopencv>python helloopencv.py
helloopencv.py is being run directly

After the execution of this file, the helloopencv.py is being run directly message will appear, which means that the file is executed directly and not imported from another module or package (or the Python interpreter). You can also see that an image is loaded and displayed. You can press any key to continue the execution. Once again, the grayscale version of the logo is displayed and any key should be pressed again to end the execution. The execution ends after the grayscale image is saved on the disk.

Lastly, the helloopencvtests.py file can be used for unit testing. Testing applications has become a standard skill for any competent developer. The Python community embraces testing, and the Python standard library has good built-in tools to support testing (https://docs.python.org/3/library/unittest.html).

In the Python ecosystem, there are a lot of testing tools. The two most common packages used for testing are nose (https://pypi.org/project/nose/) and pytest (https://pypi.org/project/pytest/). In this first Python project, we are going to use pytest for unit testing. 

To execute the test, run the py.test -s -v helloopencvtests.py command once Command Prompt is opened:

C:\...\helloopencv>py.test -s -v helloopencvtests.py
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-3.8.0, py-1.6.0, pluggy-0.7.1 -- c:\python37\python.exe
cachedir: .pytest_cache
collected 4 items
helloopencvtests.py::test_show_message testing show_message
PASSED
helloopencvtests.py::test_load_image testing load_image
PASSED
helloopencvtests.py::test_write_image_to_disk testing
write_image_to_disk
PASSED
helloopencvtests.py::test_convert_to_grayscale testing test_convert_to_grayscale
PASSED
========================== 4 passed in 0.57 seconds ===========================

After the execution of the tests, you can see that four tests were executed. The PASSED message means that the tests were executed successfully. This is a quick introduction to unit testing in Python. Nevertheless, the full pytest documentation can be found at https://docs.pytest.org/en/latest/contents.html#toc