
Image Pixel Arithmetic Operations代码注释如下:
import cv2 as cv
import numpy as np
# 第一次运行发现报错,error: (-209:Sizes of input arguments do not match)
# The operation is neither 'array op array'
#(where arrays have the same
# size and the same number of channels),
# nor 'array op scalar', nor 'scalar op array' in function
# 'cv::arithm_op'
# 原因是两个图像的宽高比及深度不同,在console中用
# print(src1.shape, src2.shape)来检测。
src1 = cv.imread("dataset/train/test0.jpg")
src2 = cv.imread("dataset/train/test1.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)
#首先对图片像素进行相加,值得注意的是由于黑色像素值为0,
#白色像素值为255,所以白色相加后仍为白色,黑色部分相当于没有加。
#图片整体变白。
sub_result = np.zeros(src1.shape, src1.dtype)
cv.subtract(src1, src2, sub_result)
cv.imshow("sub_result", sub_result)
#相减时,白色为255,会变成其他颜色,而黑色部分为小于0部分,
#更为黑色,图片整体变暗。
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()
第一次找的图片不能用,通过print(src1.shape, src2.shape)来检测发现两个图片尺寸不同导致的。
后来选择了两个一样大小的图片,两个原图以及 相加、相减、相乘、相除的结果如下图所示:
相加:黑色像素值为0,白色像素值为255,所以白色相加后仍为白色,黑色部分相当于没有加,图片整体变白。
相减:白色为255,会变成其他颜色,而黑色部分为小于0部分,更为黑色,图片整体变暗。
相乘:图片整体变白
相除:图片整体变黑