一、相关概念
1、算术运算
Ⅰ加减乘除
Ⅱ调节亮度
Ⅲ调整对比度
2、逻辑运算
Ⅰ与或非
Ⅱ遮罩层控制
二、图像算术运算(加减乘除均值方差)
其中图像的加减乘除需要保证两张图像的大小相同
import cv2
import numpy as npdef add(src1,src2):dst = cv2.add(src1,src2)cv2.imshow("add",dst)def subtract(src1,src2):dst1 = cv2.subtract(src1,src2)dst2 = cv2.subtract(src2,src1)cv2.imshow("subtract1",dst1)cv2.imshow("subtract2",dst2)def divide(src1,src2):dst1 = cv2.divide(src1,src2)dst2 = cv2.divide(src2,src1)cv2.imshow("divide1",dst1)cv2.imshow("divide2",dst2)def multiply(src1,src2):dst = cv2.multiply(src1,src2)cv2.imshow("multiply",dst)def average_value(src1,src2):#图像均值m1 = cv2.mean(src1)m2 = cv2.mean(src2)print("均值1:",m1)print("均值2:",m2)def mean_variance(src1,src2):m1,dev1 = cv2.meanStdDev(src1)#m为均值,dev为方差m2,dev2 = cv2.meanStdDev(src2)print("均值1:",m1)print("均值2:",m2)print("方差1:",dev1)print("方差2:",dev2)def compare(src1):#当全为1的图像,其方差为0h,w = src1.shape[:2]print(h,w)img = np.ones([h,w],np.uint8)m,dev = cv2.meanStdDev(img)print("均值是:",m,"方差是:",dev)src1 = cv2.imread(r"G:\Juptyer_workspace\study\opencv\opencv3\a1.jpg")
src2 = cv2.imread(r"G:\Juptyer_workspace\study\opencv\opencv3\a2.jpg")
print(src1.shape)
print(src2.shape)#cv2.namedWindow("image1",cv2.WINDOW_AUTOSIZE)
cv2.imshow("image1",src1)
cv2.imshow("image2",src2)add(src1,src2)
subtract(src1,src2)
divide(src1,src2)
multiply(src1,src2)average_value(src1,src2)
mean_variance(src1,src2)compare(src1)cv2.waitKey(0)
cv2.destroyAllWindows()
运行效果如下:
三、图像的逻辑运算(与或非)
与或运算针对两张图片而言,非运算针对单一图片而言
import cv2
import numpy as npdef logic(src1,src2):And = cv2.bitwise_and(src1,src2)cv2.imshow("logic_and",And)Or = cv2.bitwise_or(src1,src2)cv2.imshow("logic_or",Or)Not1 = cv2.bitwise_not(src1)cv2.imshow("logic_not1",Not1)Not2 = cv2.bitwise_not(src2)cv2.imshow("logic_not2",Not2)src1 = cv2.imread(r"G:\Juptyer_workspace\study\opencv\opencv3\a1.jpg")
src2 = cv2.imread(r"G:\Juptyer_workspace\study\opencv\opencv3\a2.jpg")
cv2.imshow("image1",src1)
cv2.imshow("image2",src2)logic(src1,src2)cv2.waitKey(0)
cv2.destroyAllWindows()
运行效果图如下:
四、对图像的对比度、亮度进行调节
import cv2
import numpy as npdef contrast_brightness(src,c,b):#目标图像、对比度、亮度h,w,ch = src.shapeblack = np.zeros([h,w,ch],src.dtype)dst = cv2.addWeighted(src,c,black,1-c,b)cv2.imshow("contrast_brightness",dst)src = cv2.imread(r"G:\Juptyer_workspace\study\opencv\opencv3\a1.jpg")
cv2.imshow("image",src)contrast_brightness(src,1,2)cv2.waitKey(0)
cv2.destroyAllWindows()
效果图如下: