Showing posts with label open. Show all posts
Showing posts with label open. Show all posts

Friday, October 15, 2010

Python - Anagram generator

# python anagram generator 
# 
# This anagram generator uses a 
# text file as a reference for 
# appropriate words. 
# 
# The word file I used is in the 
# following format (each word has 
# it's own line): 
# 
# act 
# addition 
# adjustment 
# advertisement 
# after 
# again 
# against 
# ... and on and on... 
# 
 
def isAnagramOf(attempt, original):
    # all the same case 
    attempt = attempt.strip()
    if len(attempt) < 1: # only actual words 
        return False
    attempt, original = attempt.lower(), original.lower()
    for character in attempt:
        position = original.find(character)
        if (position == -1):
            return False
        original = original.replace(character, '', 1)
    return True
 
def getAnagramsFor(text):
    anagrams = []
    wordlist = open("wordlist.txt", 'r')
    for line in wordlist:
        line = line.strip("\n") #strip the carriage return 
        if isAnagramOf(line, text):
            anagrams.append(line)
    return anagrams
 
matching_anagrams = getAnagramsFor("pythonic prose")
print(len(matching_anagrams), "total anagrams generated")
for ana in matching_anagrams:
    print(ana)
 
 
# my output: 
# 
# 66 total anagrams generated 
# chest 
# chin 
# copper 
# copy 
# cry 
# he 
# history 
# hope 
# ... skip a few ... 
# theory 
# thin 
# this 
# tin 
# to 
# toe 
# top 
# yes 
 

Tuesday, October 27, 2009

Python - break a large mysql dump into small dumps

# created a dumpfile from my mysql db
# and found that it was too large to
# upload to my new db host.
 
# this python script breaks up the database
# into smaller pieces that you can more
# easily import through phpmyadmin
# (if I'd only had shell access I wouldn't
# have this problem at all!)
 
# indicates a new table is about to be
# created
dlmtr = "-- Table structure for table"
 
wholeFile = open("myDBDump.sql")
fileN = 0
oFile = open(str(fileN) + ".sql", 'w')
reducing = True
 
for line in wholeFile:
    if line.find(dlmtr) > -1:
        # this is the seam for the next file
        print "starting new file"
        oFile.close()
        fileN += 1
        oFile = open(str(fileN) + ".sql", 'w')
    oFile.write(line)
 
oFile.close()
print "Done"
 
 

Friday, September 25, 2009

Python - replace or remove colors from an image

from PIL import Image
 
# this script assumes that 'test.jpg' 
# is in the current working directory http://pythonicprose.blogspot.com/2009/09/python-os-module-and-working-directory.html 
n = Image.open('test.jpg')
m = n.load()
 
# get x,y size 
s = n.size
 
# iterate through x and y (every pixel) 
for x in xrange(s[0]):
    for y in xrange(s[1]):
        r,g,b = m[x,y]
        # remove red from the pic 
        m[x,y] = 0,g,b
 
# save the doctored image 
n.save('sans_red.jpg', "JPEG")
 
# removing all the red from a photo 
# makes for a creepy greenish blue (duh..with no red) 
# try it out! 
 

Tuesday, September 22, 2009

Python - find the average rgb color for an image

#   iterate through each pixel in an image and
# determine the average rgb color

# you will need to install the PIL module

from PIL import Image

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

if __name__ == '__main__':
# assumes you have a test.jpg in the working directory!
pc = PixelCounter('test.jpg')
print "(red, green, blue, total_pixel_count)"
print pc.averagePixels()


# for my picture the ouput rgb values are:
# (red, green, blue, total_pixel_count)
# (135, 122, 107, 10077696)
#
# you can see that my image had 10,077,696 pixels and python/PIL
# still churned right through it!

python - create thumbnail with PIL

#PIL is the python image library
# learn more about pil

from PIL import Image

# the size of thumbnail you would like to create
# NOTE: you may get from the 100,100 that the image is ... or will be square
# PIL takes care of this and keeps the proper aspect ratio
# the values you enter here are the max
thumbSize = 100, 100

# assumes you have a file called 'test.jpg' in
# the current directory
# how to tell where python's current directory
pic = Image.open("test.jpg")


# PIL makes thumbnails easy with the thumbnail method
pic.thumbnail(thumbSize, Image.ANTIALIAS)

# save to file and choose save type
pic.save("test.small.jpg", "JPEG")

Wednesday, July 15, 2009

Python - compare two images

 
# PIL is a great python library for doing everything related to images 
 
# check out the other PIL and Image examples: 
#   Find and Label objects in Images l 
#   Find and outline the sun  
#   Replace or remove colors from an image  
#   Find the average RGB color for and image   
#   Determine an image's type (regardless of extension)  
 
 
# here is the zipped full source for this example  
from PIL import Image
import time
import sys
 
def compareTwoPics(picture_1, picture_2, step=20):
    step = int(step)
    if step < 1:
        step = 1
 
    percent_similar = 0.0
    percent_red = 0.0
    percent_green = 0.0
    percent_blue = 0.0
    percent_totalcolor = 0.0
 
 
    total_check_points = 0.0
    total_not_match = 0.0
    percent_similar = 0.0
 
    pic1_total_red = 0
    pic1_total_green = 0
    pic1_total_blue = 0
    pic1_total_color = 0
 
    pic2_total_red = 0
    pic2_total_green = 0
    pic2_total_blue = 0
    pic2_total_color = 0
 
    #print picture_1 
    #print picture_2 
 
    try:
        pic1 = Image.open(picture_1)
        pic2 = Image.open(picture_2)
    except:
        # tried to open an unsupported format!! 
        #print str(picture_1) + " is not a supported image format" 
        #print str(picture_2) + " is not a supported image format" 
        return -1.0, 0.0, 0.0, 0.0
 
    pic1_width = pic1.size[0]
    pic1_height = pic1.size[1]
 
    pic2_width = pic2.size[0]
    pic2_height = pic2.size[1]
 
 
    if pic1_width != pic2_width:
        print "\n widths must be the same \n" 
        sys.exit()
    if pic1_height != pic2_height:
        print "\n widths must be the same \n" 
        sys.exit()
 
 
    for x in range(0, pic1_width):
        for y in range(0, pic1_height):
 
            if x % step == 0:
                pic1_color = pic1.getpixel((x,y))
                pic2_color = pic2.getpixel((x,y))
 
                total_check_points += 3
 
                if pic1_color[0] != pic2_color[0]:
                    total_not_match += 1
                if pic1_color[1] != pic2_color[1]:
                    total_not_match += 1
                if pic1_color[2] != pic2_color[2]:
                    total_not_match += 1
 
                pic1_total_red += pic1_color[0]
                pic1_total_green += pic1_color[1]
                pic1_total_blue += pic1_color[2]
 
 
                pic2_total_red += pic2_color[0]
                pic2_total_green += pic2_color[1]
                pic2_total_blue += pic2_color[2]
 
                #print "     pic1 count: "+ str(pic1_total_red) 
                #print "     pic2 count: "+ str(pic2_total_red) 
 
 
 
    pic1_total_color = pic1_total_red + pic1_total_green + pic1_total_blue
    pic2_total_color = pic2_total_red + pic2_total_green + pic2_total_blue
 
 
    percent_similar = 1 - (total_not_match / total_check_points)
    percent_red = abs(float(pic2_total_red) / float(pic1_total_red))
    percent_green = abs(float(pic2_total_green) / float(pic1_total_green))
    percent_blue = abs(float(pic2_total_blue) / float(pic1_total_blue))
    percent_totalcolor = abs(float(pic2_total_color) / float(pic1_total_color))
 
    print '----' 
    print "total % comparible red:  " + str(percent_red)
    print "total % comparible green:" + str(percent_green)
    print "total % comparible blue: " + str(percent_blue)
    print "total % comparible:      " + str(percent_totalcolor)
    print "total pic1:              " + str(pic1_total_color)
    print "total pic2               " + str(pic2_total_color)
 
 
    return percent_similar, percent_totalcolor, pic1_total_color, pic2_total_color
 
 
 
if __name__ == '__main__':
    try:
        import psyco
        psyco.full()
    except ImportError:
        print "...installing psyco would provide additional performance" 
 
 
    thedetail = 20
    if len( sys.argv ) < 3:
        print "\n\n" 
        print "Usage: " + str(sys.argv[0]) + " <photo1.png> <photo2.png> [detail]" 
        print "" 
        print " - photo1.png and photo2.png are the photos you are comparing" 
        print " - detail is just a number.  The higher the number the faster" 
        print " and less detailed the comparison will be.  Default detail is 20" 
        print "" 
        print "example:" 
        print " # Highest quality comparison, slowest turn around" 
        print " " + str(sys.argv[0]) + " photo.png photo2.png 1" 
        print " " 
        print " # Low quality comparison, high turn around" 
        print " " + str(sys.argv[0]) + " photo.png photo2.png 100" 
        sys.exit()
    else:
        try:
            thedetail = sys.argv[3]
        except:
            thedetail = 20
 
        tt = time.time()
        print str(compareTwoPics(sys.argv[1], sys.argv[2], step=thedetail))
        print "execution seconds: " + str(time.time() - tt)
 
 

Wednesday, June 24, 2009

python open and read through file

# open file 'r' for read only 
# this assumes that myfile.txt is 
#   in the current working directory  
theFile = open('myfile.txt', 'r')
 
# iterate through the lines in the file object 
for line in theFile:
    # this is where you would perform logic on each line, or just print 
    print line
 
# close the file 
theFile.close()
 
#output: 
# Line one is here 
# line two is here 
# line 3 is here!