from PIL import Image
import sys
import types

def frombits(bits):
    chars = []
    for b in range(len(bits) / 8):
        byte = bits[b*8:(b+1)*8]
        chars.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
    return ''.join(chars)

def decode_message(pixel):
    if type(pixel) is types.IntType:
        return "{0:02b}".format(pixel%4)
    #RGB
    if type(pixel) is types.TupleType:
        R, G, B = pixel
        if R >= G and R >= B:
            return  "{0:02b}".format(R%4)
        if G >= R and G >= B:
            return  "{0:02b}".format(G%4)
        if B >= G and B >= R:
            return  "{0:02b}".format(B%4)

IMAGE_PATH = "./stegano.bmp"

im = Image.open(IMAGE_PATH)

pixels = im.load()

width, height = im.size

extracted_msg = ""

for x in range(0,width):
    for y in range(0,height):
        extracted_msg = extracted_msg + decode_message(pixels[x,y])

message = frombits(extracted_msg)

print (message)
