FatemeZamanian
FatemeZamanian

Reputation: 154

Encrypt and decrypt image using multiplication and subtraction

I used addition and subtraction to encode and decode the image in Python but I could not do it by multiplication and division. Can anyone?

Encryption code section:

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

Decryption code section :

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

Upvotes: 1

Views: 399

Answers (2)

Sajjad Aemmi
Sajjad Aemmi

Reputation: 2625

you can try this way:

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

Encryption

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)

Decryption

image_output = image_encrypted * key
image_output *= 255.0
imwrite('image_output.jpg', image_output)

Upvotes: 2

Red
Red

Reputation: 27577

As you know, with multiplication, the

        if temp > 255:
            temp = image[i, j] + key[i,j] - 255

becomes useless as two numbers multiplied in an image can way exceed 255 and 510.

And with division, the

        if temp < 0:
            temp = 255 + temp

becomes useless as two numbers divided in an image will never reach 0 or below 0. Also, you should make sure that you are working with arrays that can store floats; if your array has dtype of uint8, and float inserted inside would auto-convert to be an integer.

Here is something you can try. Encryption code section:

for i in range(image.shape[0]):
    for j in range(image.shape[1]):
        result[i, j] = image[i, j] * (key[i, j] / 255)

Decryption code section :

for i in range(image.shape[0]):
    for j in range(image.shape[1]):
        result[i, j] = image[i, j] / (key[i, j] / 255)

Upvotes: 1

Related Questions