SAD算法在opencv上的实现代码(c++)
Posted 俺叫王梦涵
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SAD算法在opencv上的实现代码(c++)相关的知识,希望对你有一定的参考价值。
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace std;
using namespace cv;
const int w = 384;
const int h = 288;
const int n = 3;
void SAD(uchar* Limg,
uchar* Rimg,
uchar* Oimg)
{
for (int y = 0; y< h; y++)
{
for (int x = 0; x< w; x++){
unsigned int bestCost = 999999;
unsigned int bestDisparity = 0;
for (int d = 0; d <= w-x-5; d++)
{
unsigned int cost = 0;
for (int i = -n; i <= n; i++)
{
for (int j = -n; j <= n; j++)
{
int yy, xx, xxd;
yy = y + i;
if (yy < 0) yy = 0;
if (yy >= h) yy = h;
xx = x + j;
if (xx < 0) xx = 0;
if (xx >= w) xx = w;
xxd = xx - d;
if (xxd < 0) xxd = 0;
if (xxd >= w) xxd = w;
cost += abs((int)(Limg[yy*w + xx] - Rimg[yy*w + xxd]));
}
}
if (cost < bestCost)
{
bestCost = cost;
bestDisparity = d*d;
}
Oimg[y*w + x] = bestDisparity;
}
}
}
}
int main()
{
Mat imL, imR, imO;
imL = imread("C:\\\\Users\\\\Administrator\\\\Desktop\\\\im2.png", 0);
if (imL.empty())
{
return -1;
}
imR = imread("C:\\\\Users\\\\Administrator\\\\Desktop\\\\im6.png", 0);
if (imR.empty())
{
return -1;
}
imO.create(imL.rows, imL.cols, imL.type());
SAD(imL.data, imR.data, imO.data);
namedWindow("left", WINDOW_AUTOSIZE);
namedWindow("right", WINDOW_AUTOSIZE);
namedWindow("Output", WINDOW_AUTOSIZE);
imshow("Output", imO);
imshow("left", imL);
imshow("right", imR);
waitKey(0);
return 0;
}
以上是关于SAD算法在opencv上的实现代码(c++)的主要内容,如果未能解决你的问题,请参考以下文章
FPGA目标跟踪基于FPGA的帧差法和SAD匹配算法的目标跟踪实现
如何在 Flutter 的原生 C++ 中使用 OpenCV 4(2021 年)(支持 Flutter 2.0)? [关闭]