SAD(Sum of absolute differences)是一种图像局部匹配算法。
1、本文结构
首先介绍SAD算法的基本原理与流程,之后使用C++和Verilog实现算法。
2、算法流程
输入:左摄像机图片,右摄像机图片,最大视差等级
(1)确定模板大小(一般是3*3,5*5);
(2)用这个模板提取左图像的一块区域中的像素值;
(3)用这个模板提取右图相对应位置的一块区域中的像素值;
(4)用左图像中提取的数据分别减去右图像中提取的数据,结果取绝对值;
(5)在搜索范围内移动右图像的模板,重复(4)
(6)找到这个范围内SAD最小值对应的位置,即找到了左边图像在右图像中的最佳匹配像素块。
#pragma once
#include
#include
#include
using namespace std;
using namespace cv;
class mySAD
{
public :
mySAD() :wsize(3), dsr(30) {}
mySAD(unsigned int _size, int _dsr) :wsize(_size), dsr(_dsr) {}
Mat computeSAD(Mat &L,Mat &R);
private:
int wsize;
int dsr;
};
#include "stdafx.h"
#include "mysad.h"
Mat mySAD::computeSAD(Mat &L, Mat &R)
{
Mat Disparity(L.rows,L.cols,CV_8U,Scalar::all(0));
float temp=0;
float temp_min = 0;
for (int nrow = 1; nrow < L.rows-1; nrow++)
{
for (int ncol = 1; ncol < L.cols-1; ncol++)
{
temp_min = 100000;
for (int d = 0; (d < this->dsr && ncol+d+1(nrow - 1, ncol - 1) - R.at(nrow - 1, ncol + d - 1)
+ L.at(nrow - 1, ncol ) - R.at(nrow - 1, ncol + d )
+ L.at(nrow - 1, ncol + 1) - R.at(nrow - 1, ncol + d + 1)
+ L.at(nrow , ncol - 1) - R.at(nrow , ncol + d - 1)
+ L.at(nrow , ncol ) - R.at(nrow , ncol + d )
+ L.at(nrow , ncol + 1) - R.at(nrow , ncol + d + 1)
+ L.at(nrow + 1, ncol - 1) - R.at(nrow + 1, ncol + d - 1)
+ L.at(nrow + 1, ncol ) - R.at(nrow + 1, ncol + d )
+ L.at(nrow + 1, ncol + 1) - R.at(nrow + 1, ncol + d + 1));
if (temp < temp_min)
{
temp_min = temp;
Disparity.at(nrow,ncol) = d*16;
}
}
}
float rate = (float)(nrow / L.rows);
}
return Disparity;
}
// SAD.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include
#include
#include "mysad.h"
using namespace std;
using namespace cv;
int main()
{
Mat imgl_gray = imread("C:\\Users\\WangDongwei\\Documents\\Visual Studio 2015\\Projects\\SAD\\pic\\im6.png", CV_LOAD_IMAGE_GRAYSCALE);
Mat imgr_gray = imread("C:\\Users\\WangDongwei\\Documents\\Visual Studio 2015\\Projects\\SAD\\pic\\im2.png", CV_LOAD_IMAGE_GRAYSCALE);
Mat d;
mySAD my_sad;
d = my_sad.computeSAD(imgl_gray,imgr_gray);
return 0;
}
fpga的实现将在之后补上