Skip to content

Instantly share code, notes, and snippets.

@dmyates
Created March 2, 2014 12:27
Show Gist options
  • Save dmyates/9305849 to your computer and use it in GitHub Desktop.
Save dmyates/9305849 to your computer and use it in GitHub Desktop.
Hide messages in images and get them back.
# Hiding Messages in Images
#
#
# Just do this to encode messages:
#
# python hidemessage.py -e <filewithmessage> <imagetohidein>
#
#
# ...and do this to decode messages:
#
# python hidemessage.py -d <imagetodecode>
#
#
# End messages with one ` to tell the decoder when to stop. PNGs recommended.
#
# Python 2.7.5+, requires OpenCV.
import sys, getopt, cv2, base64, binascii
"""
Encode message in image
"""
def encode(img, msg):
binmsg = "".join('{:08b}'.format(ord(c)) for c in msg)
msgcounter = 0
for x in range(0, img.shape[1]):
for y in range(0, img.shape[0]):
for c in range(0,3):
iodd = img[y, x, c] % 2
modd = binmsg[msgcounter]
if iodd != int(modd):
if img[y,x,c] == 255:
img[y, x, c] -= 1
elif img[y,x,c] == 0:
img[y,x,c] += 1
else:
img[y,x,c] -= 1
if msgcounter+1 < len(binmsg):
msgcounter += 1
else:
return img
return img
"""
Decode message from image
"""
def decode(img):
characters = []
for x in range(0, img.shape[1]):
for y in range(0, img.shape[0]):
for c in range(0,3):
characters.append(str(img[y, x, c] % 2))
binmsg = "".join(characters)
msglist = []
for c in range(0, len(binmsg), 8):
char = chr(int(binmsg[c:c+8], 2))
if char != "`":
msglist.append(char)
else:
break
return "".join(msglist)
def usage():
print("""Usage: python message.py [ options... ] [image]
-e/--encode [file] -- Encode message in given file
-d/--decode -- Decode message""")
def main(argv):
try:
opts, args = getopt.getopt(argv, "he:d", ["help", "encode=", "decode"])
except getopt.GetoptError:
usage()
sys.exit(2)
img = cv2.imread(args[0])
for opt, arg in opts:
if opt in ("-h","--help"):
usage()
sys.exit()
elif opt in ("-e", "--encode"):
with open(arg, 'r') as thefile:
message = thefile.read()
codedimage = encode(img, message)
cv2.imwrite("coded.png", codedimage)
elif opt in ("-d", "--decode"):
message = decode(img)
print(message)
if __name__ == '__main__':
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment