VPI - Vision Programming Interface

3.2 Release

Python API

VPI exposes a Python API that offers a simplified way to use the library, leading to faster development cycle. Resource management is done automatically under the hood, allowing the developer to focus on the definition of the image processing pipeline.

Requirements

  • Ubuntu 20.04 or 22.04
  • Python 3.9 or 3.10
  • numpy >= 1.11.0
  • pillow >= 3.1.2

Writing an Image Blurring Application

Copy the code below to a file named main.py. The comments explain how it works.

30 import sys
31 import vpi
32 
33 import numpy as np
34 from PIL import Image
35 from argparse import ArgumentParser
36 
37 # 2. Parse command line parameters
38 # -----------------------------------------------------------------------------
39 parser = ArgumentParser()
40 parser.add_argument('input',
41  help='Image to be used as input')
42 args = parser.parse_args();
43 
44 # 3. Load input and wrap it into a VPI image.
45 # -----------------------------------------------------------------------------
46 
47 # `Image.open` returns a Pillow image that is then interpreted as
48 # a numpy array. This array is finally wrapped in a VPI image suitable
49 # for use by VPI algorithms.
50 try:
51  input = vpi.asimage(np.asarray(Image.open(args.input)))
52 except IOError:
53  sys.exit("Input file not found")
54 except:
55  sys.exit("Error with input file")
56 
57 # 4. Convert it to grayscale and blur it with a 5x5 box filter
58 # with ZERO border condition.
59 # -----------------------------------------------------------------------------
60 
61 # Enabling the CUDA backend in a python context like done below makes
62 # VPI algorithms use CUDA for execution by default. This can be overriden
63 # if needed by specifying the parameter `backend=` when calling the algorithm.
64 with vpi.Backend.CUDA:
65  # `image.convert` will return a new VPI image with the desired format, in
66  # this case U8 (grayscale, 8-bit unsigned pixels).
67  # Algorithms returning a new VPI image allows for chaining operations like
68  # done below, as the result of the conversion is then filtered.
69  # The end result is finally stored in a new `output` VPI image.
70  output = input.convert(vpi.Format.U8) \
71  .box_filter(5, border=vpi.Border.ZERO)
72 
73 # 5. Save result to disk
74 # -----------------------------------------------------------------------------
75 
76 # The read-lock context enabled below makes sure all processing is finished and
77 # results are stored in `output`.
78 with output.rlock_cpu() as outData:
79  # `outData` is a numpy array view (not a copy) of `output`
80  # contents, accessible by host (cpu).
81  # The numpy array is then converted into a Pillo image and saved
82  # to the disk
83  Image.fromarray(outData).save('tutorial_blurred_python.png')

Testing the Application

With everything set in place, execute the script as follows:

python3 main.py <image file name>

substituting <image file name> by some image on disk.