1.OpenCV中像素算术操作
- 像素算术操作 + 加add、减subtract、乘multiply、除divide + saturate_cast<T>(value)
- 注意点:图像的数据类型、通道数目、大小必须相同
- 其他待补充...
2.示例
Python代表性代码
1 import cv2 as cv 2 import numpy as np 3 4 src1 = cv.imread("D:/vcprojects/images/LinuxLogo.jpg"); 5 src2 = cv.imread("D:/vcprojects/images/WindowsLogo.jpg"); 6 cv.imshow("input1", src1) 7 cv.imshow("input2", src2) 8 h, w, ch = src1.shape 9 print("h , w, ch", h, w, ch) 10 11 add_result = np.zeros(src1.shape, src1.dtype); 12 cv.add(src1, src2, add_result); 13 cv.imshow("add_result", add_result); 14 15 sub_result = np.zeros(src1.shape, src1.dtype); 16 cv.subtract(src1, src2, sub_result); 17 cv.imshow("sub_result", sub_result); 18 19 mul_result = np.zeros(src1.shape, src1.dtype); 20 cv.multiply(src1, src2, mul_result); 21 cv.imshow("mul_result", mul_result); 22 23 div_result = np.zeros(src1.shape, src1.dtype); 24 cv.divide(src1, src2, div_result); 25 cv.imshow("div_result", div_result); 26 27 cv.waitKey(0) 28 cv.destroyAllWindows()
C++代表性代码
1 #include <opencv2/opencv.hpp> 2 #include <iostream> 3 4 5 using namespace cv; 6 using namespace std; 7 8 9 int main(int artc, char** argv) { 10 Mat src1 = imread("D:/vcprojects/images/LinuxLogo.jpg"); 11 Mat src2 = imread("D:/vcprojects/images/WindowsLogo.jpg"); 12 if (src1.empty() || src2.empty()) { 13 printf("could not load image...\n"); 14 return -1; 15 } 16 namedWindow("input", CV_WINDOW_AUTOSIZE); 17 imshow("input1", src1); 18 imshow("input2", src2); 19 int height = src1.rows; 20 int width = src1.cols; 21 22 23 int b1 = 0, g1 = 0, r1 = 0; 24 int b2 = 0, g2 = 0, r2 = 0; 25 int b = 0, g = 0, r = 0; 26 Mat result = Mat::zeros(src1.size(), src1.type()); 27 for (int row = 0; row < height; row++) { 28 for (int col = 0; col < width; col++) { 29 b1 = src1.at<Vec3b>(row, col)[0]; 30 g1 = src1.at<Vec3b>(row, col)[1]; 31 r1 = src1.at<Vec3b>(row, col)[2]; 32 33 34 b2 = src2.at<Vec3b>(row, col)[0]; 35 g2 = src2.at<Vec3b>(row, col)[1]; 36 r2 = src2.at<Vec3b>(row, col)[2]; 37 38 39 result.at<Vec3b>(row, col)[0] = saturate_cast<uchar>(b1 + b2); 40 result.at<Vec3b>(row, col)[1] = saturate_cast<uchar>(g1 + g2); 41 result.at<Vec3b>(row, col)[2] = saturate_cast<uchar>(r1 + r2); 42 } 43 } 44 imshow("output", result); 45 46 47 Mat add_result = Mat::zeros(src1.size(), src1.type()); 48 add(src1, src2, add_result); 49 imshow("add_result", add_result); 50 51 52 Mat sub_result = Mat::zeros(src1.size(), src1.type()); 53 subtract(src1, src2, sub_result); 54 imshow("sub_result", sub_result); 55 56 57 Mat mul_result = Mat::zeros(src1.size(), src1.type()); 58 multiply(src1, src2, mul_result); 59 imshow("mul_result", mul_result); 60 61 62 Mat div_result = Mat::zeros(src1.size(), src1.type()); 63 divide(src1, src2, div_result); 64 imshow("div_result", div_result); 65 66 waitKey(0); 67 return 0; 68 }