use artificial neural network for image encryption in matlab

To use artificial neural network for image encryption in matlab, we can follow the steps given below:

  1. Load the image that needs to be encrypted.
main.m
img = imread('image.jpg');
27 chars
2 lines
  1. Convert the image to grayscale, if needed.
main.m
if size(img,3) == 3 % if img is RGB image
    img = rgb2gray(img);
end
71 chars
4 lines
  1. Convert the image pixel values to binary values.
main.m
img_binary = de2bi(img); % img_binary will be a matrix with rows containing the binary values of each pixel
108 chars
2 lines
  1. Create a neural network model using the nprtool command. Set the number of inputs to the same as the number of pixels in the image (numel(img)) and the number of outputs to the same as the number of pixels in the image (numel(img)). You can experiment with different numbers of hidden layers and neurons to find the best model for your use case.
main.m
inputs = img_binary(:,:)';
targets = img_binary(:,:)';
hiddenLayerSize = 10; % change this to experiment with different numbers of hidden layers and neurons
net = fitnet(hiddenLayerSize);
[net,tr] = train(net,inputs,targets);
226 chars
6 lines
  1. Encrypt the image using the neural network model. To do so, we will need to convert the encrypted data back to pixel values and then back to an image format. We can use the bi2de function to convert the binary data back to decimal form.
main.m
encrypted_data = sim(net, inputs);
encrypted_pixel_values = bi2de(encrypted_data); % encrypted_pixel_values will be a column vector containing the decimal values of each pixel in the encrypted image
encrypted_img = reshape(encrypted_pixel_values, size(img));
imwrite(encrypted_img, 'encrypted_image.jpg');
306 chars
5 lines
  1. To decrypt the image, we simply pass the encrypted data to the neural network in the same way as before (sim(net, encrypted_inputs)) and then convert the decrypted data back to pixel values and back to an image format.
main.m
decrypted_data = sim(net, encrypted_data);
decrypted_pixel_values = bi2de(decrypted_data);
decrypted_img = reshape(decrypted_pixel_values, size(img));
imwrite(decrypted_img, 'decrypted_image.jpg');
198 chars
5 lines

Note that this encryption method is not very secure and should not be used for sensitive data. There are many other encryption methods that should be used instead.

gistlibby LogSnag