from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
def plus(str):
return str.zfill(8)
# 获取水印图片的每一个像素值,i:指定要检查的像素点的逻辑X轴坐标。j:指定要检查的像素点的逻辑Y轴坐标。
def getcode(watermark):
str1 = ""
for i in range(watermark.size[0]):
for j in range(watermark.size[1]):
# 获取每个像素的RGB值
rgb = watermark.getpixel((i, j))
#print(rgb)
str1 = str1 + plus(bin(rgb[0]).replace('0b', ''))
str1 = str1 + plus(bin(rgb[1]).replace('0b', ''))
str1 = str1 + plus(bin(rgb[2]).replace('0b', ''))
#print (str1)
return str1
#加密
def encry(img, code):
# 计数器
count = 0
codelen = len(code)
#count = codelen
print (codelen)
for i in range(img.size[0]):
for j in range(img.size[1]):
# 获取每个像素的RGB值
data = img.getpixel((i, j))
if count == codelen:
break
r = data[0]
g = data[1]
b = data[2]
#print (r)
# print(codelen)#24
r = (r - r % 2) + int(code[count])
# if r >= 128:
# r = r - 128 + int(code[count]) * 128
# else:
# r = int(code[count]) * 128 + r
count += 1
if count == codelen:
img.putpixel((i, j), (r, g, b))
break
g = (g - g % 2) + int(code[count])
# if g >= 128:
# g = g - 128 + int(code[count]) * 128
# else:
# g = int(code[count]) * 128 + g
count += 1
if count == codelen:
img.putpixel((i, j), (r, g, b))
break
b = (b - b % 2) + int(code[count])
# if b >= 128:
# b = b - 128 + int(code[count]) * 128
# else:
# b = int(code[count]) * 128 + b
count += 1
if count == codelen:
img.putpixel((i, j), (r, g, b))
break
# 每3次循环表示一组RGB值被替换完毕,可以进行写入
if count % 3 == 0:
img.putpixel((i, j), (r, g, b))
#img.save('F:/pythonProject/watermark_im.png')
plt.imshow(im)
plt.show()
im = Image.open("F:/pythonProject/image.jfif")
watermark = Image.open("F:/pythonProject/waterimage.jfif")
print(im)
print(watermark)
#watermark = watermark.convert("RGB")
code = getcode(watermark)
encry(im, code)
# import matplotlib.pyplot as plt
# import numpy as np
#
# # R = "10000010"
# # G = "10000001"
# # B = "01001111"
#
# # R = "10000000"
# # G = "10000000"
# # B = "01001100"
#
# R = "11000010"
# G = "11000001"
# B = "11001111"
# print(int(R, 2))
# print(int(G, 2))
# print(int(B, 2))
# image = np.zeros(shape=(50, 50, 3))
# image[:, :, 0] = int(R, 2)
# image[:, :, 1] = int(G, 2)
# image[:, :, 2] = int(B, 2)
# image = image/255
# plt.imshow(image)
# plt.show()
# def LSB_encode(cover, m, k):
# m = np.array(m, dtype = np.uint8)
# cover = np.array(cover, dtype = np.uint8)
#
# k = 2**k -1
# mask1 = 255-k
# mask2 = k
# cover = np.bitwise_and(cover, mask1)
# m = np.bitwise_and(m, mask2)
# res = np.bitwise_or(cover,m)
# return res
LSB图像水印
最新推荐文章于 2024-05-27 21:53:10 发布