Goal
In this guide, you will gain insights into the thread safety of Ascend operators already in use, as well as discover how to effectively employ Ascend operators for image preprocessing and understand their usage limitations.
Preface
We provide a suite of common matrix operation operators that support the Ascend NPU within OpenCV. For user convenience, the new 'AscendMat' structure and its associated operators maintain compatibility with the 'Mat' interface in OpenCV. These operators encompass a wide range of frequently used functions, including arithmetic operations, image processing operations, and image color space conversion. All of these operators are implemented utilizing CANN(Compute Architecture of Neural Networks). The Ascend operator facilitates accelerated operations on the NPU by making use of CANN. This acceleration effect is particularly noticeable when working with larger images, such as those with dimensions like 2048x2048, 3840x2160, 7680x4320, etc.
Instructions on Thread Safety
Our stream function is implemented by invoking the CANN operators. In the same stream, tasks are executed sequentially, while across different streams, tasks are executed in parallel. The use of event mechanisms ensures synchronization of tasks between streams, please refer to the Stream Management documentation for details.
Example for Image Preprocessing
In this section, you will discover how to use Ascend operators for image preprocessing, including functions below:
code
C++
#include <iostream>
int main(
int argc,
char* argv[])
{
"{@input|puppy.png|path to input image}"
"{@output|output.png|path to output image}"
"{help||show help}");
parser.about("This is a sample for image processing with Ascend NPU. \n");
if (argc != 3 || parser.has("help"))
{
parser.printMessage();
return 0;
}
std::string imagePath = parser.get<std::string>(0);
std::string outputPath = parser.get<std::string>(1);
cv::Mat gaussNoise(img.rows, img.cols, img.type());
return 0;
}
Designed for command line parsing.
Definition utility.hpp:890
n-dimensional dense array class
Definition mat.hpp:951
Random Number Generator.
Definition core.hpp:2805
@ NORMAL
Definition core.hpp:2808
void fill(InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange=false)
Fills arrays with random numbers.
void resetDevice()
Clear all context created in current Ascend device.
void initAcl()
init AscendCL.
void finalizeAcl()
finalize AscendCL.
void setDevice(int device)
Choose Ascend npu device.
void rotate(InputArray src, OutputArray dst, int rotateCode, AscendStream &stream=AscendStream::Null())
Rotates a 2D array in multiples of 90 degrees. The function cv::rotate rotates the array in one of th...
void flip(InputArray src, OutputArray dst, int flipCode, AscendStream &stream=AscendStream::Null())
Flips a 2D matrix around vertical, horizontal, or both axes.
void add(const InputArray src1, const InputArray src2, OutputArray dst, const InputArray mask=noArray(), int dtype=-1, AscendStream &stream=AscendStream::Null())
Computes a matrix-matrix or matrix-scalar sum.
CV_EXPORTS_W bool imwrite(const String &filename, InputArray img, const std::vector< int > ¶ms=std::vector< int >())
Saves an image to a specified file.
CV_EXPORTS_W Mat imread(const String &filename, int flags=IMREAD_COLOR_BGR)
Loads an image from a file.
int main(int argc, char *argv[])
Definition highgui_qt.cpp:3
Python
import numpy as np
import cv2
import argparse
parser = argparse.ArgumentParser(description='This is a sample for image processing with Ascend NPU.')
parser.add_argument('image', help='path to input image')
parser.add_argument('output', help='path to output image')
args = parser.parse_args()
img = cv2.imread(args.image)
gaussNoise = np.random.normal(0, 25,(img.shape[0], img.shape[1], img.shape[2])).astype(img.dtype)
cv2.cann.initAcl()
cv2.cann.setDevice(0)
output = cv2.cann.add(img, gaussNoise)
output = cv2.cann.rotate(output, 0)
output = cv2.cann.flip(output, 0)
cv2.imwrite(args.output, output)
cv2.cann.finalizeAcl()
Explanation
Input Image
C++
cv::Mat gaussNoise(img.rows, img.cols, img.type());
Python
img = cv2.imread("/path/to/img")
gaussNoise = np.random.normal(mean=0,sigma=25,(img.shape[0],img.shape[1],img.shape[2])).astype(img.dtype)
Setup CANN
C++
Python
cv2.cann.initAcl()
cv2.cann.setDevice(0)
Image Preprocessing Example
C++
Python
output = cv2.cann.add(img, gaussNoise)
output = cv2.cann.rotate(output, 0)
output = cv2.cann.flip(output, 0)
Tear down CANN
C++
Python
Results
- The original RGB input image with dimensions of (480, 640, 3):
puppy
- After introducing Gaussian noise, we obtain the following result:
puppy_noisy
- When applying the rotate operation with a rotation code of 0 (90 degrees clockwise), we obtain this result:
puppy_noisy_rotate
- Upon applying the flip operation with a flip code of 0 (flipping around the x-axis), we achieve the final result:
puppy_processed_normalized