Skip to content

Instantly share code, notes, and snippets.

@erik-whiting
Created August 29, 2019 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erik-whiting/d9988122b5e94b1db4c15236b6d86975 to your computer and use it in GitHub Desktop.
Save erik-whiting/d9988122b5e94b1db4c15236b6d86975 to your computer and use it in GitHub Desktop.
Simple steganography script using cv2
import cv2
# Make a generator object for the message to be hidden
def char_generator(message):
for c in message:
yield ord(c)
# Convenience function for getting image
def get_image(image_location):
img = cv2.imread(image_location)
return img
# We'll use this as the pattern for picking pixels to write to
def gcd(x, y):
while(y):
x, y = y, x % y
return x
def encode_image(image_location, msg):
img = get_image(image_location)
msg_gen = char_generator(msg)
pattern = gcd(len(img), len(img[0]))
for i in range(len(img)):
for j in range(len(img[0])):
if (i+1 * j+1) % pattern == 0:
try:
img[i-1][j-1][0] = next(msg_gen)
except StopIteration:
img[i-1][j-1][0] = 0
return img
def decode_image(img_loc):
img = get_image(img_loc)
pattern = gcd(len(img), len(img[0]))
message = ''
for i in range(len(img)):
for j in range(len(img[0])):
if (i-1 * j-1) % pattern == 0:
if img[i-1][j-1][0] != 0:
message = message + chr(img[i-1][j-1][0])
else:
return message
@erik-whiting
Copy link
Author

Example usage in Python console:

>>> import stego
>>> secret_message = "Hello from inside the picture!"
>>> img_location = "test_img.jpg"
>>> img = stego.encode_image(img_location, secret_message)
>>> import cv2
>>> cv2.imwrite("output.jpg", img)
True
>>> encoded_pic_location = "output.jpg"
>>> stego.decode_image(encoded_pic_location)
'Hello from inside the picture!'
>>>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment