{"title":"opencv应用-算术运算","slug":"b559997d","url":"https://blog.biss.click/posts/b559997d/","date":"2026-03-17T13:13:08.000Z","updated":null,"summary":"这篇文章介绍了如何使用OpenCV进行图像的加法运算。首先,通过包含OpenCV和iostream头文件,并使用std命名空间,开始编写代码。主函数中,读取两张图片,检查是否成功加载,并确保它们的尺寸相同。如果尺寸不同,将第二张图片调整为与第一张相同的大小。然后,调用add函数对两幅图片进行加法运算,并将结果存储在result矩阵中。最后,显示原始图片和加法运算的结果,并等待按键关闭窗口。代码已上传至自建的git仓库。","tags":["opencv"],"categories":["技术"],"series":"opencv","seriesOrder":null,"contentFormat":"text/markdown","content":"opencv对图像的算数运算,感觉都大同小异,分为以下几种:加减乘除和位运算。\n\n| 函数 | 功能 | 应用场景 |\n|-------------------|--------|------------|\n| cv2.bitwise_and() | 按位与操作 | 掩码操作、图像分割 |\n| cv2.bitwise_or() | 按位或操作 | 图像叠加 |\n| cv2.bitwise_not() | 按位取反操作 | 图像反色 |\n| cv2.bitwise_xor() | 按位异或操作 | 图像差异检测 |\n\n因为感觉都差不多,所以只把加法运算代码搬过来\n\n```cpp\n// 加法\n#include \n#include \n\nusing namespace std;\nusing namespace cv;\n\nint main()\n{\n string path1 = \"../img/2.jpg\";\n string path2 = \"../img/3.jpg\";\n\n Mat img1 = imread(path1);\n Mat img2 = imread(path2);\n\n if (img1.empty() || img2.empty())\n {\n cout << \"无法读取图片,请检查路径!\" << endl;\n return -1;\n }\n\n if (img1.size() != img2.size())\n {\n cout << \"尺寸不一致,正在自动调整 img2 的尺寸...\" << endl;\n // 将 img2 缩放到与 img1 相同的尺寸\n resize(img2, img2, img1.size());\n }\n\n Mat result;\n add(img1, img2, result);\n\n imshow(\"Original Image 1\", img1);\n imshow(\"Original Image 2\", img2);\n imshow(\"Add Result\", result);\n\n // 等待按键后关闭窗口\n waitKey(0);\n destroyAllWindows();\n\n return 0;\n}\n```\n\n另外,把代码上传到了自建的git中\n{% link opencv-learning,opencv-learning,https://git.biss.click/biss/opencv-learning/src/branch/master/Arithmetic%20operations %}"}