VPI - Vision Programming Interface

1.1 Release

2D Image Convolution

Overview

The 2D Image Convolution application outputs an image with the edges of the input image, saving the result as an image file on disk. The user can define what backend will be used for processing.

Note
The output will be in grayscale as convolution is currently only supported for single-channel images.

Instructions

The command line parameters are:

<backend> <input image>

where

  • backend: either cpu, cuda or pva; it defines the backend that will perform the processing.
  • input image: input image file name; it accepts png, jpeg and possibly others.

Here's one example:

  • C++
    ./vpi_sample_01_convolve_2d cpu ../assets/kodim8.png
  • Python
    python main.py cpu ../assets/kodim8.png

This is using the CPU backend and one of the provided sample images. You can try with other images, respecting the constraints imposed by the algorithm.

Results

Input imageOutput image, edges

Source Code

For convenience, here's the code that is also installed in the samples directory.

Language:
27 import sys
28 import vpi
29 import numpy as np
30 from PIL import Image
31 from argparse import ArgumentParser
32 
33 # Parse command line arguments
34 parser = ArgumentParser()
35 parser.add_argument('backend', choices=['cpu','cuda','pva'],
36  help='Backend to be used for processing')
37 
38 parser.add_argument('input',
39  help='Image to be used as input')
40 
41 args = parser.parse_args();
42 
43 if args.backend == 'cpu':
44  backend = vpi.Backend.CPU
45 elif args.backend == 'cuda':
46  backend = vpi.Backend.CUDA
47 else:
48  assert args.backend == 'pva'
49  backend = vpi.Backend.PVA
50 
51 # Load input into a vpi.Image
52 input = vpi.asimage(np.asarray(Image.open(args.input)))
53 
54 # Convert it to grayscale
55 input = input.convert(vpi.Format.U8, backend=vpi.Backend.CUDA)
56 
57 # Define a simple edge detection kernel
58 kernel = [[ 1, 0, -1],
59  [ 0, 0, 0],
60  [-1, 0, 1]]
61 
62 # Using the chosen backend,
63 with backend:
64  # Run input through the convolution filter
65  output = input.convolution(kernel, border=vpi.Border.ZERO)
66 
67 # Save result to disk
68 Image.fromarray(output.cpu()).save('edges_python'+str(sys.version_info[0])+'_'+args.backend+'.png')
69 
70 # vim: ts=8:sw=4:sts=4:et:ai
29 #include <opencv2/core/version.hpp>
30 #include <opencv2/imgproc/imgproc.hpp>
31 #if CV_MAJOR_VERSION >= 3
32 # include <opencv2/imgcodecs.hpp>
33 #else
34 # include <opencv2/highgui/highgui.hpp>
35 #endif
36 
37 #include <vpi/OpenCVInterop.hpp>
38 
39 #include <vpi/Image.h>
40 #include <vpi/Status.h>
41 #include <vpi/Stream.h>
42 #include <vpi/algo/Convolution.h>
43 
44 #include <cstring> // for memset
45 #include <iostream>
46 #include <sstream>
47 
48 #define CHECK_STATUS(STMT) \
49  do \
50  { \
51  VPIStatus status = (STMT); \
52  if (status != VPI_SUCCESS) \
53  { \
54  char buffer[VPI_MAX_STATUS_MESSAGE_LENGTH]; \
55  vpiGetLastStatusMessage(buffer, sizeof(buffer)); \
56  std::ostringstream ss; \
57  ss << vpiStatusGetName(status) << ": " << buffer; \
58  throw std::runtime_error(ss.str()); \
59  } \
60  } while (0);
61 
62 int main(int argc, char *argv[])
63 {
64  // OpenCV image that will be wrapped by a VPIImage.
65  // Define it here so that it's destroyed *after* wrapper is destroyed
66  cv::Mat cvImage;
67 
68  // VPI objects that will be used
69  VPIImage image = NULL;
70  VPIImage gradient = NULL;
71  VPIStream stream = NULL;
72 
73  int retval = 0;
74 
75  try
76  {
77  if (argc != 3)
78  {
79  throw std::runtime_error(std::string("Usage: ") + argv[0] + " <cpu|pva|cuda> <input image>");
80  }
81 
82  std::string strBackend = argv[1];
83  std::string strInputFileName = argv[2];
84 
85  // Load the input image
86  cvImage = cv::imread(strInputFileName);
87  if (cvImage.empty())
88  {
89  throw std::runtime_error("Can't open '" + strInputFileName + "'");
90  }
91 
92  // We can't use cv::IMREAD_GRAYSCALE when opening the input file because the
93  // color to grayscale conversion used differs between OpenCV-2.4 and OpenCV>=3.0,
94  // yielding different image content.
95 #if CV_MAJOR_VERSION >= 3
96  cvtColor(cvImage, cvImage, cv::COLOR_BGR2GRAY);
97 #else
98  cvtColor(cvImage, cvImage, CV_BGR2GRAY);
99 #endif
100 
101  assert(cvImage.type() == CV_8UC1);
102 
103  // Now parse the backend
104  VPIBackend backend;
105 
106  if (strBackend == "cpu")
107  {
108  backend = VPI_BACKEND_CPU;
109  }
110  else if (strBackend == "cuda")
111  {
112  backend = VPI_BACKEND_CUDA;
113  }
114  else if (strBackend == "pva")
115  {
116  backend = VPI_BACKEND_PVA;
117  }
118  else
119  {
120  throw std::runtime_error("Backend '" + strBackend +
121  "' not recognized, it must be either cpu, cuda or pva.");
122  }
123 
124  // Create the stream for the given backend.
125  CHECK_STATUS(vpiStreamCreate(backend, &stream));
126 
127  // We now wrap the loaded image into a VPIImage object to be used by VPI.
128  CHECK_STATUS(vpiImageCreateOpenCVMatWrapper(cvImage, 0, &image));
129 
130  // Now create the output image, single unsigned 8-bit channel.
131  CHECK_STATUS(vpiImageCreate(cvImage.cols, cvImage.rows, VPI_IMAGE_FORMAT_U8, 0, &gradient));
132 
133  // Define the convolution filter, a simple edge detector.
134  float kernel[3 * 3] = {1, 0, -1, 0, 0, 0, -1, 0, 1};
135 
136  // Submit it for processing passing the input image the result image that will store the gradient.
137  CHECK_STATUS(vpiSubmitConvolution(stream, backend, image, gradient, kernel, 3, 3, VPI_BORDER_ZERO));
138 
139  // Wait until the algorithm finishes processing
140  CHECK_STATUS(vpiStreamSync(stream));
141 
142  // Now let's retrieve the output image contents and output it to disk
143  {
144  // Lock output image to retrieve its data on cpu memory
145  VPIImageData outData;
146  CHECK_STATUS(vpiImageLock(gradient, VPI_LOCK_READ, &outData));
147 
148  cv::Mat cvOut(outData.planes[0].height, outData.planes[0].width, CV_8UC1, outData.planes[0].data,
149  outData.planes[0].pitchBytes);
150  imwrite("edges_" + strBackend + ".png", cvOut);
151 
152  // Done handling output image, don't forget to unlock it.
153  CHECK_STATUS(vpiImageUnlock(gradient));
154  }
155  }
156  catch (std::exception &e)
157  {
158  std::cerr << e.what() << std::endl;
159  retval = 1;
160  }
161 
162  // Clean up
163 
164  // Make sure stream is synchronized before destroying the objects
165  // that might still be in use.
166  if (stream != NULL)
167  {
168  vpiStreamSync(stream);
169  }
170 
171  vpiImageDestroy(image);
172  vpiImageDestroy(gradient);
173 
174  vpiStreamDestroy(stream);
175 
176  return retval;
177 }
178 
179 // vim: ts=8:sw=4:sts=4:et:ai
Declares functions to perform image filtering with convolution kernels.
Functions and structures for dealing with VPI images.
Functions for handling OpenCV interoperability with VPI.
Declaration of VPI status codes handling functions.
Declares functions dealing with VPI streams.
VPIStatus vpiSubmitConvolution(VPIStream stream, uint32_t backend, VPIImage input, VPIImage output, const float *kernelData, int32_t kernelWidth, int32_t kernelHeight, VPIBorderExtension border)
Runs a generic 2D convolution over an image.
@ VPI_IMAGE_FORMAT_U8
Single plane with one 8-bit unsigned integer channel.
Definition: ImageFormat.h:104
int32_t height
Height of this plane in pixels.
Definition: Image.h:138
int32_t width
Width of this plane in pixels.
Definition: Image.h:137
void * data
Pointer to the first row of this plane.
Definition: Image.h:147
int32_t pitchBytes
Difference in bytes of beginning of one row and the beginning of the previous.
Definition: Image.h:139
VPIImagePlane planes[VPI_MAX_PLANE_COUNT]
Data of all image planes.
Definition: Image.h:166
VPIStatus vpiImageLock(VPIImage img, VPILockMode mode, VPIImageData *hostData)
Acquires the lock on an image object and returns a pointer to the image planes.
void vpiImageDestroy(VPIImage img)
Destroy an image instance.
struct VPIImageImpl * VPIImage
A handle to an image.
Definition: Types.h:215
VPIStatus vpiImageCreate(int32_t width, int32_t height, VPIImageFormat fmt, uint32_t flags, VPIImage *img)
Create an empty image instance with the specified flags.
VPIStatus vpiImageUnlock(VPIImage img)
Releases the lock on an image object.
Stores information about image characteristics and content.
Definition: Image.h:159
VPIStatus vpiImageCreateOpenCVMatWrapper(const cv::Mat &mat, VPIImageFormat fmt, uint32_t flags, VPIImage *img)
Wraps a cv::Mat in an VPIImage with the given image format.
struct VPIStreamImpl * VPIStream
A handle to a stream.
Definition: Types.h:209
VPIStatus vpiStreamSync(VPIStream stream)
Blocks the calling thread until all submitted commands in this stream queue are done (queue is empty)...
VPIBackend
VPI Backend types.
Definition: Types.h:91
void vpiStreamDestroy(VPIStream stream)
Destroy a stream instance and deallocate all HW resources.
VPIStatus vpiStreamCreate(uint32_t flags, VPIStream *stream)
Create a stream instance.
@ VPI_BACKEND_CUDA
CUDA backend.
Definition: Types.h:93
@ VPI_BACKEND_PVA
PVA backend.
Definition: Types.h:94
@ VPI_BACKEND_CPU
CPU backend.
Definition: Types.h:92
@ VPI_BORDER_ZERO
All pixels outside the image are considered to be zero.
Definition: Types.h:237
@ VPI_LOCK_READ
Lock memory only for reading.
Definition: Types.h:383