Question: The python code is an implementation of image steganography, however, it isn't working as intended. The output of this code should create an image file
The python code is an implementation of image steganography, however, it isn't working as intended. The output of this code should create an image file that is almost the same as the input, with some data hidden. (The difference between images isn't detectable to the human eye). This code block embeds an image but the pixels where the data are hidden in their Least Significant Bits turn out with distorted colors. Instead of getting an image identical to the original image, we get an image where the data hidden is obvious. How can this be fixed?
import sys
import numpy as np
from PIL import Image
np.set_printoptions(threshold=sys.maxsize) # To use full representation instead of summarization
#TAKES A SOURCE IMAGE TO EMBED A MESSAGE (TXT FILE), AND THE OUTPUT DESTINATION
def encode(src, message, destination):
# OPEN AND CREATE AN ARRAY OF THE SOURCE IMAGE
sourceImage = Image.open(src,'r')
width,height = sourceImage.size
array = np.array(list (sourceImage.getdata()))
textFile = open(message, 'r')
message = textFile.read()
if sourceImage.mode == 'RGB':
n=3
if sourceImage.mode == 'RGBA':
n = 4
totalPixels = array.size//n
message += "$END" #STOP FLAG TO SIGNIFY THAT THE MESSAGE IS DONE
binaryMessage = ''.join([format(ord(i), "08b") for i in message]) #BINARY CONVERSION OF STRING
#print(binaryMessage)
requiredPixels = len(binaryMessage)
if requiredPixels > totalPixels:
print("Image size not sufficient for the message, try a larger image file")
else:
if n == 3:
print("if")
index=0
for p in range(totalPixels):
for q in range(0, 3):
if index < requiredPixels:
array[p][q] = int(bin(array[p][q])[2:9] + binaryMessage[index], 2)
index += 1
elif n == 4:
print("elif")
index=0
for p in range(totalPixels):
for q in range(0, 4):
if index < requiredPixels:
if q==3:
#print(bin(array[20][3]))
array[p][q] = int((bin(array[p][q])[2:9] + binaryMessage[index]), 2)
#print(bin(array[20][3])[0:9] + binaryMessage[index])
#sys.exit()
#print(binaryMessage[index])
index += 1
else:
#print(bin(array[20][1]))
array[p][q] = int((bin(array[p][q])[2:8] + binaryMessage[index]), 2)
#print(bin(array[20][1])[0:8] + binaryMessage[index])
#sys.exit()
#print(binaryMessage[index])
index += 1
array=array.reshape(height, width, n)
enc_img = Image.fromarray(array.astype("uint8"), sourceImage.mode)
enc_img.save(destination)
print("Image Encoded Successfully")
print(n)
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
