cpu加速warpAffine例程
时间: 2023-10-24 12:20:27 浏览: 91
CPU卡读写例程
下面是CPU加速的warpAffine例程:
```c++
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
Mat src = imread("lena.jpg");
if (src.empty())
{
cout << "Could not open or find the image!\n" << endl;
return -1;
}
Point2f srcTri[3], dstTri[3];
Mat warp_mat(2, 3, CV_32FC1);
Mat dst, dst_cpu;
srcTri[0] = Point2f(0, 0);
srcTri[1] = Point2f(src.cols - 1, 0);
srcTri[2] = Point2f(0, src.rows - 1);
dstTri[0] = Point2f(src.cols*0.0, src.rows*0.33);
dstTri[1] = Point2f(src.cols*0.85, src.rows*0.25);
dstTri[2] = Point2f(src.cols*0.15, src.rows*0.7);
warp_mat = getAffineTransform(srcTri, dstTri);
warpAffine(src, dst, warp_mat, src.size(), INTER_LINEAR, BORDER_CONSTANT, Scalar());
TickMeter tm;
tm.start();
int rows = src.rows;
int cols = src.cols;
dst_cpu.create(rows, cols, src.type());
float M[6];
Mat map_matrix(2, 3, CV_32F, M);
int map_width = dst_cpu.cols;
int map_height = dst_cpu.rows;
for (int i = 0; i < map_height; ++i)
{
for (int j = 0; j < map_width; ++j)
{
float x = M[0] * j + M[1] * i + M[2];
float y = M[3] * j + M[4] * i + M[5];
int src_x = (int)(x + 0.5);
int src_y = (int)(y + 0.5);
if (src_x >= 0 && src_x < cols && src_y >= 0 && src_y < rows)
{
dst_cpu.at<Vec3b>(i, j) = src.at<Vec3b>(src_y, src_x);
}
else
{
dst_cpu.at<Vec3b>(i, j) = Vec3b(0, 0, 0);
}
}
}
tm.stop();
cout << "CPU Time: " << tm.getTimeMilli() << " ms" << endl;
imshow("Original image", src);
imshow("Affine Transform", dst);
imshow("CPU Affine Transform", dst_cpu);
waitKey(0);
return 0;
}
```
其中,CPU加速部分使用了一个双重循环,对每个像素进行仿射变换,最终得到变换后的图像。在循环中,使用了OpenCV的at方法对像素进行访问和修改。需要注意的是,at方法中的模板参数应该与原图像的类型相同。
阅读全文