User:Eleanorg/1.3/Dissolute Image/Code1

From XPUB & Lens-Based wiki

Make database of pixels

Splits up image into pixels with imageMagick, then inserts each one as a hash in a Mongo database. Shown here with dummy values for testing, imagemagick bits commented out.

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

# this script grabs pixel data from imagemagick & creates the mongo database of pixels. to be run once with python.

import pymongo  #the library that serves as python interface to mongo database system
from pymongo import Connection


#--------- create database -----------------------#	

connection = Connection()
myDB = connection['pixelsDatabaseTest1']
collection = myDB.collection  					#tables in Mongo are called 'collections'. variable name on the left can be anything.


#--------- determine image dimensions-----------------------#	
 
#image = "20by10PixelsSection1.png"
#sizeQuery = "identify -format '%w %h' " + image		# system command gets image dimensions with ImageMagick
#size = os.popen(sizeQuery, 'r').read()				# captures output of system call
#(width, height) = size.split()					# splits ImageMagick output into separate column & row no's
#columns = int(width)
#rows = int(height)

columns = 5
rows = 2
 
#--------- assign pixel details to database-----------------#		
 # RUN ONCE ONLY

def getcolors ():
    n = 0
    for row in range (0, rows):					# for each row in the image...		
        for column in range (0, columns):			# for each column in the row...
#            colorQuery = "convert " + image + " -format '%[pixel:p{" + str(column) + "," + str(row) + "}]' info:-"
#            colorResult = os.popen(colorQuery, 'r').read()	# makes & captures output of system call
#            color = re.sub("\n", "", colorResult)		# strips newline character from end of sys call result
            color = "red"
            n = (n + 1)						# this counter increments by one on each loop, generating a unique pixel id
            pixelID = str(n)					
            pixelName = "pixel" + pixelID			# creates a unique name from the pixel ID, as a handle for this pixel in the database. warning: db has no qualms about creating duplicates if this code is run more than once; it assigns its own unique id string to each entry
            #string = "I'm adopting pixel " + str(pixelID) + " at position " + str(column) + "," + str(row) + "; color " + color
            pixelName = {'id': n , 'xpos': str(column) , 'ypos': str(row) , 'color': color, 'url': ""}
            #print pixelName
            collection.insert(pixelName)			# insert this pixel into the db
 
getcolors()