import numpy as np import cv2
# 加密 ''' new_x = (x + a*y) % img_side_len new_y = (b*x + (a*b+1)*y) % img_side_len '''
def arnold_encode(image, arnold_times): a = 7 b = 35 # 创建新图像,大小和原图一样 encode_image = np.zeros(shape=(1734, 1734, 3)) height, width = image.shape[0], image.shape[1] N = height # 边长
for time in range(arnold_times): # 变换次数time # 遍历像素 for x in range(height): for y in range(width): # 猫脸变换,计算加密后的像素坐标 new_x = (x + a * y) % N new_y = (b * x + (a * b + 1) * y) % N # 填入加密后的像素值 encode_image[new_x, new_y, :] = image[x, y, :]
cv2.imwrite('encode1.png', encode_image, [cv2.IMWRITE_PNG_COMPRESSION, 0]) return encode_image
# 解密 ''' ori_x = ((a * b + 1) * old_x + (-a) * old_y) % N #原像素点的x坐标值 ori_y = ((-b) * old_x + old_y) % N #原像素点y的坐标值 '''
def arnold_decode(image, arnold_times): a = 7 b = 35 # 创建新图像,大小和原图一样 decode_image = np.zeros(shape=(1734, 1734, 3)) height, width = image.shape[0], image.shape[1] N = height # 边长
for time in range(arnold_times): # 变换次数time # 遍历像素点 for x in range(height): for y in range(width): # 猫脸公式逆置换 ori_x = ((a * b + 1) * x + (-a) * y) % N # 原像素点的x坐标值 ori_y = ((-b) * x + y) % N # 原像素点y的坐标值 decode_image[ori_x, ori_y, :] = image[x, y, :] cv2.imwrite('decode1.png', decode_image, [int(cv2.IMWRITE_PNG_COMPRESSION), 0]) # 以PNG写入图片 return decode_image
if __name__ == '__main__': # imread(path,flag)读取图片,加载彩色图片默认参数值是flag=1,灰度是0,透明度-1,结果是三维数组,前两维是像素坐标,最后一维是通道索引 # 加密 # en_it = cv2.imread('origin.png') # arnold_encode(en_it,1) # 解密 it = cv2.imread('1.png') arnold_decode(it, 1)
|