常用的像素的算数操作有:
add
subtract
multiply
divide
饱和运算的概念:因为像素值得范围一般是0~255,因此像素值经过算术操作后大于等于255的时候应该取255,小于等于0的时候取0。在C++
中通过saturate_cast
对可以对a+b的结果进行上述的溢出保护,Python
中则通过cv.subtract
方法。
读入图片:
Mat input1 = imread("test_images/opencv.jpg", 1);
if (input1.empty())
{
cout << "read input failed!" << endl;
return -1;
}
Mat input2 = imread("test_images/cat.jpg", 1);
if (input2.empty())
{
cout << "read input failed!" << endl;
return -1;
}
因为算术操作是对两张图像的操作,所以需要读入两张图片。
进行相应的操作,需要定义出保存操作结果的Mat
,当然也要保证两个图像的大小是一样的,这样才能保证对应位置上的像素值进行相应的操作:
//将两个图片resize到同样大小
resize(input1, input1, Size(400, 300));
resize(input2, input2, Size(400, 300));
imshow("input1", input1);
imshow("input2", input2);
//定义出保存操作结果的 Mat
Mat add_result = Mat::zeros(input1.size(), input1.type());
Mat sub_result = Mat::zeros(input1.size(), input1.type());
Mat mul_result = Mat::zeros(input1.size(), input1.type());
Mat div_result = Mat::zeros(input1.size(), input1.type());
add(input1, input2, add_result);
subtract(input1, input2, sub_result);
multiply(input1, input2, mul_result);
divide(input1, input2, div_result);
imshow("add_result", add_result);
imshow("sub_result", sub_result);
imshow("mul_result", mul_result);
imshow("div_result", div_result);
src1 = cv.imread("test_images/opencv.jpg");
src2 = cv.imread("test_images/cat.jpg");
cv.imshow("input1", src1)
cv.imshow("input2", src2)
h, w, ch = src1.shape
print("h , w, ch", h, w, ch)
add_result = np.zeros(src1.shape, src1.dtype);
cv.add(src1, src2, add_result);
cv.imshow("add_result", add_result);
sub_result = np.zeros(src1.shape, src1.dtype);
cv.subtract(src1, src2, sub_result);
cv.imshow("sub_result", sub_result);
mul_result = np.zeros(src1.shape, src1.dtype);
cv.multiply(src1, src2, mul_result);
cv.imshow("mul_result", mul_result);
div_result = np.zeros(src1.shape, src1.dtype);
cv.divide(src1, src2, div_result);
cv.imshow("div_result", div_result);
cv.waitKey(0)
cv.destroyAllWindows()
逻辑操作是对于图像中像素点位的操作。
对两张图像的操作:
bitwise_and
bitwise_xor
bitwise_or
对单个图像的操作:
bitwise_not
Mat1 | Mat2 | 与 | 或 | 异或 |
---|---|---|---|---|
0 | 0 | 0 | 0 | 0 |
1 | 0 | 0 | 1 | 1 |
0 | 1 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 0 |
C++:
Mat and_, xor_, or_ , not_;
bitwise_and(input1, input2, and_);
bitwise_xor(input1, input2, xor_);
bitwise_or(input1, input2, or_ );
bitwise_not(input1, not_);
imshow("and", and_);
imshow("xor", xor_);
imshow("or", or_ );
imshow("not", not_);
本部分完整代码:
image_common_pixels_op.cpp
image_common_pixels_op.py