I have an RGB image such that:
Img[3*(row*imgWidth+column)+0], //R
Img[3*(row*imgWidth+column)+1], //G
Img[3*(row*imgWidth+column)+2] //B
represent the intensity value for each pixel for each RGB. What is a clean method to pad borders of 0’s(0-255 scale) around the image? The border can be adjusted to any width.
The only thing I can come up with is pretty much manual insertion of rows and columns, which becomes a very tediously long piece of code.
sorry, but libraries are not what I’m looking for here
Here’s the most readable way I can think of, which is also reasonably efficient. Say you have an image of dimensions
WidthbyHeightand desired margins ofLeft,Right,Top, andBottom. Allocate a buffer ofWidth + Left + RightbyHeight + Top + Bottomfilled with zeros. In C++ you can use one of the handystd::vectorconstructors:The C function
calloc()is also an option. Next, copy each row in the source image to the target image, starting at vertical offsetTopand horizontal offsetLeft. Usestd::copy()to copy rows, and run the outer loop in row-major order to avoid cache misses:If you can use 32-bit RGB0 or RGBA instead of 24-bit RGB, you might see faster copying thanks to more consistent alignment, for which
std::copy()ormemcpy()are well optimised. If you can use OpenMP, you might also experiment with parallelising the loop: