赞
踩
目录
3、图像mask掩模(包括按位AND,OR,NOT和XOR运算)
可以通过OpenCV函数cv.add()
或简单地通过numpy操作添加两个图像,res = img1 + img2.两个图像应该具有相同的深度和类型,或者第二个图像可以是标量值.
- import cv2
- import numpy as np
-
- img1 = cv2.imread('4.jpg')
- img2 = cv2.imread('1.jpg')
-
- imgadd = cv2.add(cv2.resize(img1,(200,200)),cv2.resize(img2,(200,200)))
- cv2.imshow('imgadd',imgadd)
- cv2.waitKey(0)
叠加结果:如果叠加两个图像,它将改变颜色
图像加法,但是对图像赋予不同的权重(0到1之间),使得它具有混合感或透明感。
- # 图像融合
- combine = cv2.addWeighted(cv2.resize(img1,(200,200)),0.5,cv2.resize(img2,(200,200)),0.5,0)
-
- cv2.imshow('combine',combine)
- cv2.waitKey(0)
结果:如果融合两个图像,会得到一个透明的效果.
.
目的:希望将opencv徽标放在图像上方
- img2 = cv2.resize(img2,(100,100))
-
- # I want to put logo on top-left corner, So I create a ROI
- #首先获取原始图像roi
- rows,cols,channels = img2.shape
- roi = img1[0:rows, 0:cols ]
-
- #原始图像转化为灰度值
- # Now create a mask of logo and create its inverse mask also
- img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
-
- cv2.imshow('img2gray',img2gray)
- cv2.waitKey(0)
- '''
- 将一个灰色的图片,变成要么是白色要么就是黑色。(大于规定thresh值就是设置的最大值(常为255,也就是白色))
- '''
- #将灰度值二值化,得到ROI区域掩模
- ret, mask = cv2.threshold(img2gray, 200, 255, cv2.THRESH_BINARY)
-
- cv2.imshow('mask',mask)
- cv2.waitKey(0)
-
- #ROI掩模区域反向掩模
- mask_inv = cv2.bitwise_not(mask)
-
- cv2.imshow('mask_inv',mask_inv)
- cv2.waitKey(0)
-
- #掩模显示背景
- # Now black-out the area of logo in ROI
- img1_bg = cv2.bitwise_and(roi,roi,mask = mask)
-
- cv2.imshow('img1_bg',img1_bg)
- cv2.waitKey(0)
-
- #掩模显示前景
- # Take only region of logo from logo image.
- img2_fg = cv2.bitwise_and(img2,img2,mask = mask_inv)
- cv2.imshow('img2_fg',img2_fg)
- cv2.waitKey(0)
-
- #前背景图像叠加
- # Put logo in ROI and modify the main image
- dst = cv2.add(img1_bg,img2_fg)
- img1[0:rows, 0:cols ] = dst
-
- cv2.imshow('res',img1)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
-
-
- img1[0:rows, 0:cols ] = dst
-
- cv2.imshow('res',img1)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
结果:
灰度图
二值化掩模 二值化掩模取反 ROI背景提取 ROI前景提取 ROI前背景融合
最终融合:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。