Something strange happens when substracting 2 images (mat type) in opencv

about loop it’s here OpenCV: How to scan images, lookup tables and time measurement with OpenCV

May be you should start reading and trying all tutorials