Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- import serial
- import random
- from PIL import Image
- import os
- class PixelCounter(object):
- ''' loop through each pixel and average rgb '''
- def __init__(self, imageName):
- self.pic = Image.open(imageName)
- # load image data
- self.imgData = self.pic.load()
- def averagePixels(self):
- r, g, b = 0, 0, 0
- count = 0
- for x in xrange(self.pic.size[0]):
- for y in xrange(self.pic.size[1]):
- tempr,tempg,tempb = self.imgData[x,y]
- r += tempr
- g += tempg
- b += tempb
- count += 1
- # calculate averages
- return (r/count), (g/count), (b/count), count
- # configure the serial connections (the parameters differs on the device you are connecting to)
- ser = serial.Serial(
- port='/dev/tty.usbmodem411',
- baudrate=9600,
- parity=serial.PARITY_NONE,
- stopbits=serial.STOPBITS_ONE,
- bytesize=serial.EIGHTBITS
- )
- ser.open()
- # Check we opened the port correctly
- if not (ser.isOpen()):
- print "Failed to open the serial port"
- exit(1)
- # Initialise all variables
- input=1
- r=128
- b=128
- g=128
- # Loop forever
- while 1 :
- # Monitor the serial connection
- if not (ser.isOpen()):
- print "The connection to the device was closed"
- exit(1)
- os.system("screencapture 1.jpg")
- pc = PixelCounter('1.jpg')
- colourvals=pc.averagePixels()
- r=colourvals[0]
- # Construct the string
- string = 'w0-' + "%03d" % r
- string += '-' + "%03d" % g
- string += '-' + "%03d" % b
- print "Sending command: " + string
- # Append a carriage return and newline
- string += '\r\n'
- # Write the string to the serial port
- ser.write(string)
- time.sleep(0.1)
- # Increment values and handle variable overflow
- # r += 1
- # b += 1
- # g += 1
- #if b>254:b=128
- #if g>254:g=128
- #if r>254:r=128
- # Wait a little bit
- time.sleep(0.1)
Add Comment
Please, Sign In to add comment