VPI - Vision Programming Interface

1.2 Release

Image Resampling

Overview

The Rescale application rescales the input image by first applying a low-pass filter to avoid aliasing, then doing a downsampling. The resulting image has half of input's width and one third of input's height. The result is then saved to disk.

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 to be downsampled, it accepts png, jpeg and possibly others.

Here's one example:

  • C++
    ./vpi_sample_04_rescale cuda ../assets/kodim8.png
  • Python
    python main.py cuda ../assets/kodim8.png

This is using the CUDA 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, downsampled

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','vic'],
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 == 'vic'
49  backend = vpi.Backend.VIC
50 
51 # Load input into a vpi.Image
52 input = vpi.asimage(np.asarray(Image.open(args.input)))
53 
54 # Using the chosen backend,
55 with backend:
56  # First convert input to NV12_ER.
57  # We're overriding the default backend with CUDA.
58  temp = input.convert(vpi.Format.NV12_ER, backend=vpi.Backend.CUDA)
59 
60  # Rescale the image using the chosen backend
61  temp = temp.rescale((input.width//2, input.height//3))
62 
63  # Convert result back to input's format
64  output = temp.convert(input.format, backend=vpi.Backend.CUDA)
65 
66 # Save result to disk
67 Image.fromarray(output.cpu()).save('scaled_python'+str(sys.version_info[0])+'_'+args.backend+'.png')
68 
69 # vim: ts=8:sw=4:sts=4:et:ai
29 #include <opencv2/core/version.hpp>
30 #if CV_MAJOR_VERSION >= 3
31 # include <opencv2/imgcodecs.hpp>
32 #else
33 # include <opencv2/highgui/highgui.hpp>
34 #endif
35 
36 #include <vpi/OpenCVInterop.hpp>
37 
38 #include <vpi/Image.h>
39 #include <vpi/Status.h>
40 #include <vpi/Stream.h>
42 #include <vpi/algo/Rescale.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 imageNV12 = NULL;
71  VPIImage outputNV12 = NULL;
72  VPIImage output = NULL;
73  VPIStream stream = NULL;
74 
75  int retval = 0;
76 
77  try
78  {
79  if (argc != 3)
80  {
81  throw std::runtime_error(std::string("Usage: ") + argv[0] + " <cpu|vic|cuda> <input image>");
82  }
83 
84  std::string strBackend = argv[1];
85  std::string strInputFileName = argv[2];
86 
87  // Load the input image
88  cvImage = cv::imread(strInputFileName);
89  if (cvImage.empty())
90  {
91  throw std::runtime_error("Can't open '" + strInputFileName + "'");
92  }
93 
94  assert(cvImage.type() == CV_8UC3);
95 
96  // Now parse the backend
97  VPIBackend backend;
98 
99  if (strBackend == "cpu")
100  {
101  backend = VPI_BACKEND_CPU;
102  }
103  else if (strBackend == "cuda")
104  {
105  backend = VPI_BACKEND_CUDA;
106  }
107  else if (strBackend == "vic")
108  {
109  backend = VPI_BACKEND_VIC;
110  }
111  else
112  {
113  throw std::runtime_error("Backend '" + strBackend + "' not recognized, it must be either cpu, cuda or vic");
114  }
115 
116  // 1. Initialization phase ---------------------------------------
117 
118  // Create the stream for the given backend. We'll also enable CUDA for gaussian filter.
119  CHECK_STATUS(vpiStreamCreate(backend | VPI_BACKEND_CUDA, &stream));
120 
121  // We now wrap the loaded image into a VPIImage object to be used by VPI.
122  // VPI won't make a copy of it, so the original
123  // image must be in scope at all times.
124  CHECK_STATUS(vpiImageCreateOpenCVMatWrapper(cvImage, 0, &image));
125 
126  // Create a temporary image to hold the input converted to NV12.
127  CHECK_STATUS(vpiImageCreate(cvImage.cols, cvImage.rows, VPI_IMAGE_FORMAT_NV12_ER, 0, &imageNV12));
128 
129  // Now create the output image.
130  CHECK_STATUS(vpiImageCreate(cvImage.cols / 2, cvImage.rows / 3, VPI_IMAGE_FORMAT_NV12_ER, 0, &outputNV12));
131 
132  // And the output image converted back to BGR8
133  CHECK_STATUS(vpiImageCreate(cvImage.cols / 2, cvImage.rows / 3, VPI_IMAGE_FORMAT_BGR8, 0, &output));
134 
135  // 2. Computation phase ---------------------------------------
136 
137  // Convert input from BGR8 to NV12
138  CHECK_STATUS(vpiSubmitConvertImageFormat(stream, VPI_BACKEND_CUDA, image, imageNV12, NULL));
139 
140  // Now we downsample
141  CHECK_STATUS(vpiSubmitRescale(stream, backend, imageNV12, outputNV12, VPI_INTERP_LINEAR, VPI_BORDER_CLAMP, 0));
142 
143  // Finally, convert the result back to BGR8
144  CHECK_STATUS(vpiSubmitConvertImageFormat(stream, VPI_BACKEND_CUDA, outputNV12, output, NULL));
145 
146  // Wait until the algorithm finishes processing
147  CHECK_STATUS(vpiStreamSync(stream));
148 
149  // Now let's retrieve the output image contents and output it to disk
150  {
151  VPIImageData data;
152  CHECK_STATUS(vpiImageLock(output, VPI_LOCK_READ, &data));
153 
154  // Lock output image to retrieve its data on cpu memory
155  VPIImageData outData;
156  CHECK_STATUS(vpiImageLock(output, VPI_LOCK_READ, &outData));
157 
158  cv::Mat cvOut(outData.planes[0].height, outData.planes[0].width, CV_8UC3, outData.planes[0].data,
159  outData.planes[0].pitchBytes);
160  imwrite("scaled_" + strBackend + ".png", cvOut);
161 
162  // Done handling output image, don't forget to unlock it.
163  CHECK_STATUS(vpiImageUnlock(output));
164  }
165  }
166  catch (std::exception &e)
167  {
168  std::cerr << e.what() << std::endl;
169  retval = 1;
170  }
171 
172  // Clean up
173 
174  // Make sure stream is synchronized before destroying the objects
175  // that might still be in use.
176  vpiStreamSync(stream);
177 
178  vpiImageDestroy(image);
179  vpiImageDestroy(imageNV12);
180  vpiImageDestroy(output);
181  vpiStreamDestroy(stream);
182 
183  return retval;
184 }
185 
186 // vim: ts=8:sw=4:sts=4:et:ai
Declares functions that handle image format conversion.
Functions and structures for dealing with VPI images.
Functions for handling OpenCV interoperability with VPI.
Declares functions that implement the Rescale algorithm.
Declaration of VPI status codes handling functions.
Declares functions dealing with VPI streams.
VPIStatus vpiSubmitConvertImageFormat(VPIStream stream, uint32_t backend, VPIImage input, VPIImage output, const VPIConvertImageFormatParams *params)
Converts the image contents to the desired format, with optional scaling and offset.
@ VPI_IMAGE_FORMAT_BGR8
Single plane with interleaved BGR 8-bit channel.
Definition: ImageFormat.h:278
@ VPI_IMAGE_FORMAT_NV12_ER
YUV420sp 8-bit pitch-linear format with full range.
Definition: ImageFormat.h:194
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.
VPIStatus vpiSubmitRescale(VPIStream stream, uint32_t backend, VPIImage input, VPIImage output, VPIInterpolationType interpolationType, VPIBorderExtension border, uint32_t flags)
Changes the size and scale of a 2D image.
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_VIC
VIC backend.
Definition: Types.h:95
@ VPI_BACKEND_CPU
CPU backend.
Definition: Types.h:92
@ VPI_BORDER_CLAMP
Border pixels are repeated indefinitely.
Definition: Types.h:238
@ VPI_INTERP_LINEAR
Linear interpolation.
Definition: Interpolation.h:93
@ VPI_LOCK_READ
Lock memory only for reading.
Definition: Types.h:383