参考教程:
p.s 进行加减乘除运算首先需要两张大小(宽和高)一样的图像
这里我使用的两张图如下:
import cv2 as cv
def operation_demo(src1,src2):
"""
四则运算
- - - -
src1 - 图像1
src2 - 图像2
"""
# 加运算
addimg = cv.add(src1,src2)
cv.imwrite("add.png",addimg)
# 减运算
subimg = cv.subtract(src1,src2)
cv.imwrite("subtract.png",subimg)
# 乘运算
mulimg = cv.multiply(src1,src2)
cv.imwrite("multiply.png",mulimg)
# 除运算
divimg = cv.divide(src1,src2)
cv.imwrite("divide.png",divimg)
if __name__ == "__main__":
# 1.加、减、乘、除
img1 = cv.imread("cat.jpg")
img2 = cv.imread("logo.jpeg")
operation_demo(img1,img2)
def change_brightness_demo(image,c,b):
"""
改变图像的亮度和对比度
- - - -
image - 原图像
c - 需要亮度
b - 需要对比度
"""
h, w, ch = image.shape
# 创建空白图像
blank = np.zeros([w, h, ch],image.dtype)
# 实际上也是加法,只不过是按比例混合
dst = cv.addWeighted(image, c, blank, 1-c, b)
cv.imwrite("change.png", dst)
if __name__ == "__main__":
image = cv.imread("cat.jpg")
change_brightness_demo(image,1.2,10)
# 调高亮度
contrast_brightness_demo(image,1.8,0)
# 调高对比度
contrast_brightness_demo(image,1,50)
p.s 与、或需要两张大小(宽和高)一样的图像进行运算,非只需要一张
def logic_demo(src1,src2):
"""
逻辑运算
- - - -
src1 - 图像1
src2 - 图像2
"""
# 与运算
andimg = cv.bitwise_and(src1,src2)
cv.imwrite("and.png",andimg)
# 或运算
orimg = cv.bitwise_or(src1,src2)
cv.imwrite("or.png",orimg)
# 非运算,结果图像与之前说的反色图像一致
notimg = cv.bitwise_not(src1)
cv.imwrite("not.png",notimg)
if __name__ == "__main__":
img1 = cv.imread("cat.jpg")
img2 = cv.imread("logo.jpeg")
logic_demo(img1,img2)
结合之前色彩空间的遮罩层应用
def extrace_object_demo2():
"""
通过inRange()函数实现对视频中绿色部分的过滤,再利用逻辑运算改进图像的显示
"""
capture = cv.VideoCapture('MV.mp4')
while(True):
ret, frame = capture.read()
if ret == False:
break
# 转化为HSV
hsv = cv.cvtColor(frame,cv.COLOR_BGR2HSV)
# 设置绿色数值过滤
lower_hsv = np.array([37,43,46])
upper_hsv = np.array([77,255,255])
# 利用逻辑运算改进遮罩后图像的显示
mask = cv.inRange(hsv,lowerb=lower_hsv,upperb=upper_hsv)
dst = cv.bitwise_and(frame,frame,mask=mask)
cv.imshow("mask",dst)
cv.imshow("video",frame)
c = cv.waitKey(40)
if c == 27:
break
if __name__ == "__main__":
extrace_object_demo2()