It's confusing what you are looking for in an answer. If we make the assumption that your filter is stored in a std::vector<double>
called filter
and that your image is really 2D and has type std::vector< std::vector<double> >
called image
, then we can do the following to apply the 1-D filter [-1,0,1]
:
std::vector< std::vector<double> > new_image;
std::vector<double> filter;
filter.push_back(-1.0); filter.push_back(0.0); filter.push_back(1.0);
for(int i = 0; i < image.size(); i++){
for(int j = 0; j < image.at(i).size(); j++){
new_image.at(i).push_back( filter.at(0)*image.at(i).at(j-1)
+ filter.at(1)*image.at(i).at(j)
+ filter.at(2)*image.at(i).at(j+1) );
}
}
If you want to have a 2-dimensional filter like this one for example
[0 1 0]
[1 0 1]
[0 1 0]
then we assume it is stored as a vector of vectors as well, and basically do the same.
std::vector< std::vector<double> > new_image;
for(int i = 0; i < image.size(); i++){
for(int j = 0; j < image.at(i).size(); j++){
top_filter_term = filter.at(0).at(0)*image.at(i-1).at(j-1)
+ filter.at(0).at(1)*image.at(i-1).at(j)
+ filter.at(0).at(2)*image.at(i-1).at(j+1);
mid_filter_term = filter.at(1).at(0)*image.at(i).at(j-1)
+ filter.at(1).at(1)*image.at(i).at(j)
+ filter.at(1).at(2)*image.at(i).at(j+1);
bot_filter_term = filter.at(2).at(0)*image.at(i+1).at(j-1)
+ filter.at(2).at(1)*image.at(i+1).at(j)
+ filter.at(2).at(2)*image.at(i+1).at(j+1);
new_image.at(i).push_back(top_filter_term + mid_filter_term + bot_filter_term);
}
}
Please note -- I'm not making any effort to do bounds checking for the filter arrays, you really you should only apply this away from the edges of the image, or add code to apply whatever kinds of boundary conditions you want for your filter. I'm also not making any claims about this being optimized. For most purposes, using vectors is a good way to go because they are dynamically resizable and provide enough built-in support to do a lot of useful image manipulations. But for really large-scale processing, you'll want to optimize things like filter operations.
As for your question about filtering a 3D array, there are a couple of things to consider. One, make sure that you really do want to filter the whole array. For many image processing tasks, it is better and more efficient to split all of the color channels into their own 2D arrays, do your processing, and then put them back together. If you do want a true 3D filter, then be sure that your filter actually is 3D, that is, it will be a vector of vectors of vectors. Then you'll use the exact same logic as above, but you'll have an additional layer of terms for the parts of the filter applied to each color channel, or "slice", of the image.
[0, 1, 0]
is going to be an identify transformation, unless the different values represent colors, as ElKamina suggests, or some other information is missing.