使用乘法和减法加密和解密图像
Encrypt and decrypt image using multiplication and subtraction
我用加法和减法对Python中的图像进行编码和解码,但我不能通过乘法和除法来完成。任何人都可以吗?
加密代码部分:
for i in range(image.shape[0]):
for j in range(image.shape[1]):
temp=image[i, j] + key[i,j]
if temp > 255:
temp = image[i, j] + key[i,j] - 255
result[i,j]=temp
解密代码部分:
for i in range(image.shape[0]):
for j in range(image.shape[1]):
temp = image[i, j]-key[i,j]
if temp < 0:
temp = 255 + temp
result[i, j] = temp
如你所知,通过乘法,
if temp > 255:
temp = image[i, j] + key[i,j] - 255
变得毫无用处,因为图像中相乘的两个数字可能超过 255 和 510。
加上除法,
if temp < 0:
temp = 255 + temp
变得毫无用处,因为在图像中划分的两个数字永远不会达到 0 或低于 0。另外,您应该 确保您正在使用可以存储浮点数的数组;如果您的数组有 dtype
个 uint8
,并且插入其中的浮点数将自动转换为整数。
您可以尝试以下方法。加密代码部分:
for i in range(image.shape[0]):
for j in range(image.shape[1]):
result[i, j] = image[i, j] * (key[i, j] / 255)
解密代码部分:
for i in range(image.shape[0]):
for j in range(image.shape[1]):
result[i, j] = image[i, j] / (key[i, j] / 255)
你可以这样试试:
from cv2 import *
import numpy as np
image_input = imread('image_input.jpeg', IMREAD_GRAYSCALE)
(x, y) = image_input.shape
image_input = image_input.astype(float) / 255.0
加密
mu, sigma = 0, 0.1 # mean and standard deviation
key = np.random.normal(mu, sigma, (x, y)) + np.finfo(float).eps
image_encrypted = image_input / key
imwrite('image_encrypted.jpg', image_encrypted * 255)
解密
image_output = image_encrypted * key
image_output *= 255.0
imwrite('image_output.jpg', image_output)
我用加法和减法对Python中的图像进行编码和解码,但我不能通过乘法和除法来完成。任何人都可以吗?
加密代码部分:
for i in range(image.shape[0]):
for j in range(image.shape[1]):
temp=image[i, j] + key[i,j]
if temp > 255:
temp = image[i, j] + key[i,j] - 255
result[i,j]=temp
解密代码部分:
for i in range(image.shape[0]):
for j in range(image.shape[1]):
temp = image[i, j]-key[i,j]
if temp < 0:
temp = 255 + temp
result[i, j] = temp
如你所知,通过乘法,
if temp > 255:
temp = image[i, j] + key[i,j] - 255
变得毫无用处,因为图像中相乘的两个数字可能超过 255 和 510。
加上除法,
if temp < 0:
temp = 255 + temp
变得毫无用处,因为在图像中划分的两个数字永远不会达到 0 或低于 0。另外,您应该 确保您正在使用可以存储浮点数的数组;如果您的数组有 dtype
个 uint8
,并且插入其中的浮点数将自动转换为整数。
您可以尝试以下方法。加密代码部分:
for i in range(image.shape[0]):
for j in range(image.shape[1]):
result[i, j] = image[i, j] * (key[i, j] / 255)
解密代码部分:
for i in range(image.shape[0]):
for j in range(image.shape[1]):
result[i, j] = image[i, j] / (key[i, j] / 255)
你可以这样试试:
from cv2 import *
import numpy as np
image_input = imread('image_input.jpeg', IMREAD_GRAYSCALE)
(x, y) = image_input.shape
image_input = image_input.astype(float) / 255.0
加密
mu, sigma = 0, 0.1 # mean and standard deviation
key = np.random.normal(mu, sigma, (x, y)) + np.finfo(float).eps
image_encrypted = image_input / key
imwrite('image_encrypted.jpg', image_encrypted * 255)
解密
image_output = image_encrypted * key
image_output *= 255.0
imwrite('image_output.jpg', image_output)