[Tutor] Pythonify this code!

Muhammad Ali ali.jan at gmail.com
Mon Jul 13 10:01:19 CEST 2009


Hi,

This is my first attempt at python. I tried my hand at steganography for
fun. The code includes separate, combine, encode, decode functions. The
separate function takes a number and it's base and returns a list containing
each digit of the number in a list, vice versa for combine. The encode
function encodes each char's ascii value into each pixel's RGB values at the
least significant end. The decode function does the opposite. e.g.,

a = 97, so if we have at a pixel r, g, b (230, 107, 155) it will become
(230, 109, 157) when it's encoded.

Since I am new and don't speak the python idiom yet, I would like the
experts to pythonify the following code as much as possible for both python
2.6 and 3.0. Any other suggestion to improve the quality would also be
highly appreciated

Thanks a lot!


#The code starts here:

def separate(num, base):
    li = []
    while num / base > 0:
        li.insert(0, num % base)
        num = num / base

    li.insert(0,num)
    return li

def combine(tup, base):
    num = 0
    mul = pow(base, len(tup) - 1)
    for i in tup:
        num = num + i * mul
        mul = mul / base

    return num


#Will make changes to the original image and not to a copy! You have been
warned!
import Image

def encode(img, text):
    x = 0
    y = 0
    height, width = img.size

    text = text + "~~"

    if len(text) > height * width:
        return false

    pix = img.load()

    for c in text:
        li = separate(ord(c), 10)

        if(len(li) == 1):
            li.insert(0, 0)
            li.insert(0, 0)
        elif(len(li) == 2):
            li.insert(0, 0)

        r, g, b = pix[x, y]

        r = r - (r % 10) + li[0]
        if (r > 255):
            r = r - 10

        g = g - (g % 10) + li[1]
        if (g > 255):
            g = g - 10

        b = b - (b % 10) + li[2]
        if (b > 255):
            b = b - 10

        pix[x,y] = (r,g,b)

        if y == width - 1:
            y = 0
            x = x + 1
        else:
            y = y + 1

    img.save(img.filename)

def decode(img):
    x = 0
    y = 0
    text = ""
    c = ""
    height, width = img.size
    pix = img.load()
    while 1:
        r, g, b = pix[x, y]
        if (c == '~') and chr(combine([r % 10, g % 10, b % 10], 10)) == '~':
            return text[:len(text) - 1]

        c = chr(combineUnits([r % 10, g % 10, b % 10], 10))
        text = text + c

        if y == width - 1:
            y = 0
            x = x + 1
        else:
            y = y + 1
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090713/17d620d7/attachment.htm>


More information about the Tutor mailing list