Guest User

Untitled

a guest
Jan 22nd, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. import time
  2. import serial
  3. import random
  4. from PIL import Image
  5. import os
  6.  
  7. class PixelCounter(object):
  8. ''' loop through each pixel and average rgb '''
  9. def __init__(self, imageName):
  10. self.pic = Image.open(imageName)
  11. # load image data
  12. self.imgData = self.pic.load()
  13. def averagePixels(self):
  14. r, g, b = 0, 0, 0
  15. count = 0
  16. for x in xrange(self.pic.size[0]):
  17. for y in xrange(self.pic.size[1]):
  18. tempr,tempg,tempb = self.imgData[x,y]
  19. r += tempr
  20. g += tempg
  21. b += tempb
  22. count += 1
  23. # calculate averages
  24. return (r/count), (g/count), (b/count), count
  25.  
  26.  
  27. # configure the serial connections (the parameters differs on the device you are connecting to)
  28. ser = serial.Serial(
  29. port='/dev/tty.usbmodem411',
  30. baudrate=9600,
  31. parity=serial.PARITY_NONE,
  32. stopbits=serial.STOPBITS_ONE,
  33. bytesize=serial.EIGHTBITS
  34. )
  35.  
  36. ser.open()
  37.  
  38. # Check we opened the port correctly
  39. if not (ser.isOpen()):
  40. print "Failed to open the serial port"
  41. exit(1)
  42.  
  43. # Initialise all variables
  44. input=1
  45. r=128
  46. b=128
  47. g=128
  48.  
  49. # Loop forever
  50. while 1 :
  51. # Monitor the serial connection
  52. if not (ser.isOpen()):
  53. print "The connection to the device was closed"
  54. exit(1)
  55.  
  56. os.system("screencapture 1.jpg")
  57. pc = PixelCounter('1.jpg')
  58. colourvals=pc.averagePixels()
  59. r=colourvals[0]
  60.  
  61. # Construct the string
  62. string = 'w0-' + "%03d" % r
  63. string += '-' + "%03d" % g
  64. string += '-' + "%03d" % b
  65. print "Sending command: " + string
  66.  
  67.  
  68. # Append a carriage return and newline
  69. string += '\r\n'
  70.  
  71. # Write the string to the serial port
  72. ser.write(string)
  73. time.sleep(0.1)
  74.  
  75. # Increment values and handle variable overflow
  76. # r += 1
  77. # b += 1
  78. # g += 1
  79. #if b>254:b=128
  80. #if g>254:g=128
  81. #if r>254:r=128
  82.  
  83.  
  84. # Wait a little bit
  85. time.sleep(0.1)
Add Comment
Please, Sign In to add comment