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

From XPUB & Lens-Based wiki
(Created page with "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, whe...")
 
No edit summary
 
Line 17: Line 17:
     rgbValue = re.sub("\n", "", result) # stripts newline character from the end of returned RGB value
     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'
     pixels[x] = rgbValue  # assign rgb value to a key in hash 'pixels'
    print rgbValue


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

Latest revision as of 16:20, 23 January 2012

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>"""