图像运算
算术运算
import cv2
import numpy as np
import cv2
img1=cv2.imread("LinuxLogo.jpg")
img2=cv2.imread("WindowsLogo.jpg")
img3=img1+img2
cv2.imshow("add",img3)
cv2.waitKey()
cv2.destroyAllWindows()
#按位与 按位或
def logic_demo(m1, m2):
dst1 = cv2.bitwise_and(m1, m2)
dst2 = cv2.bitwise_or(m1, m2)
cv2.imshow("logic_demo_and", dst1)
cv2.imshow("logic_demo_or",dst2)
#按位非运算 按位异或
def logic_demo2(m1,m2):
dst1=cv2.bitwise_not(m1,m2)
dst2=cv2.bitwise_xor(m1,m2)
cv2.imshow("logic_demo_not", dst1)
cv2.imshow("logic_demo_xor",dst2)
#实现
img1=cv2.imread("LinuxLogo.jpg")
img2=cv2.imread("WindowsLogo.jpg")
cv2.imshow("image1", img1)
cv2.imshow("image2", img2)
logic_demo(img1,img2)
#logic_demo2(img2,img1)
cv2.waitKey(0)
cv2.destroyAllWindows()
图像加密
import cv2
import numpy as np
demo = cv2.imread("shenmi.jpg", 0)
r, c = demo.shape
key = np.random.randint(0, 256, size=(r, c), dtype=np.uint8) # 生成随机的密钥图像
cv2.imshow("shenmi", demo) # 显示原始图像
cv2.imshow("key", key) # 显示密钥图像
encryption = cv2.bitwise_xor(demo, key) # 加密
decryption = cv2.bitwise_xor(encryption, key) # 解密
cv2.imshow("jiami", encryption) # 显示密文图像
cv2.imshow("jiemi", decryption) # 显示解密后的图像
cv2.waitKey(-1)
cv2.destroyAllWindows()
面部打码和解码
lena=cv2.imread("lena.bmp",0)
r,c=lena.shape
mask=np.zeros((r,c),dtype=np.uint8)
mask[220:400,250:350]=1
key=np.random.randint(0,256,size=[r,c],dtype=np.uint8) # 获取密匙
lenaXorKey=cv2.bitwise_xor(lena,key) # 对原图像加密
encryptFace=cv2.bitwise_and(lenaXorKey,mask*255) # 获取加密图的脸部信息
noFace1=cv2.bitwise_and(lena,(1-mask)*255) # 将原图的脸部位置置0
maskFace=encryptFace+noFace1 # 得到打码的原图
# 解码
extractOriginal=cv2.bitwise_xor(maskFace,key) # 得到脸部的原始信息
extractFace=cv2.bitwise_and(extractOriginal,mask*255) # 提取脸部信息
noFace2=cv2.bitwise_and(maskFace,(1-mask)*255) # 从打码的原图内提取没有脸的原图
extractLena=noFace2+extractFace # 得到解码的原图
# 显示图像
cv2.imshow("lena",lena)
cv2.imshow("mask",mask*255)
cv2.imshow("1-mask",(1-mask)*255)
cv2.imshow("key",key)
cv2.imshow("lenaXorKey",lenaXorKey)
cv2.imshow("encryptFace",encryptFace)
cv2.imshow("noFace1",noFace1)
cv2.imshow("maskFace",maskFace)
cv2.imshow("extractOriginal",extractOriginal)
cv2.imshow("extractFace",extractFace)
cv2.imshow("noFace2",noFace2)
cv2.imshow("extractLena",extractLena)
cv2.waitKey()
cv2.destroyAllWindows()
数字水印
lena=cv2.imread("lena.bmp",0)
watermark=cv2.imread("watermark.bmp",0)
w=watermark[:,:]>0
watermark[w]=1
r,c=lena.shape
#============嵌入过程============
t254=np.ones((r,c),dtype=np.uint8)*254
lenaH7=cv2.bitwise_and(lena,t254)
e=cv2.bitwise_or(lenaH7,watermark)
#============提取过程============
t1=np.ones((r,c),dtype=np.uint8)
wm=cv2.bitwise_and(e,t1)
print(wm)
w=wm[:,:]>0
wm[w]=255
#============显示============
cv2.imshow("lena",lena)
cv2.imshow("watermark",watermark*255)
cv2.imshow("e",e)
cv2.imshow("wm",wm)
cv2.waitKey()
cv2.destroyAllWindows()
© Fu Xianjun. All Rights Reserved.