User:Eleanorg/1.2/Forbidden Pixels/RGB values stored in an array

From XPUB & Lens-Based wiki
< User:Eleanorg‎ | 1.2/Forbidden Pixels
Revision as of 15:20, 23 January 2012 by Eleanorg (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

I've been learning how to uses hashes to store key-value pairs. And what luck; it was just what I needed here. A somewhat more elegant improvement upon my previous prototype, where a system call grabs the colour of each pixel in an image, then python assigns it to a hash which is then used to print a list of html span elements of the correct colour.

In the example below, the image only has 4 pixels in a row. I'll need to develop it from here to handle multiple rows of pixels, and eventually, to figure out on its own how many pixels there are in each row. (Here, I've had to tell it by using a fixed range in the for loop.)

#!/usr/bin/python
#-*- coding:utf-8 -*-

import os, re

pixels = {}
image = "4by1PixelsSection1.png"
for x in range(0,4):
    command = "convert " + image + " -format '%[pixel:p{" + str(x) + "," + str(0) + "}]' info:-"
    result = os.popen(command, 'r').read()	# captures output of system call
    rgbValue = re.sub("\n", "", result)		# stripts newline character from the end of returned RGB value
    pixels[x] = rgbValue   			# assign rgb value to a key in hash 'pixels'

for pixel, color in pixels.items():		# .items() method returns each key-value pair in the hash
    print """<span id="pixel_""" + str(pixel) + """" style="background-color: """ + color + """ ">hello world</span>"""