Tuesday, March 16, 2010

March Madness Challenge - MMC16

Inspired by the Arduino meetings I got an older project out of the basement. The Hive has three Propeller chips from Parrallax. I tried to remember Spin, one of the languages you can use to program a Propeller. So I wrote a little program that lets a LED blink.
{{ blink.spin }}

PUB Toggle
dira[24]~~
repeat
!outa[24]
waitcnt(3_000_000 + cnt)

Monday, March 15, 2010

March Madness Challenge - MMC15

Picking up yesterdays topic and checked out inheritance.
#! /usr/bin/python

import math

class Class1:
def __init__(self, name='class1'):
self.name=name
def getName(self):
print self.name

class Class2(Class1):
def hello(self):
print 'class2 hello'

c1 = Class1('class 1')
c2 = Class2('class 2')

c1.getName()
c2.getName()
c2.hello()

Output:
class 1
class 2
class2 hello

Sunday, March 14, 2010

March Madness Challenge - MMC14

Today I wanted to check out the class functionality of python.
#! /usr/bin/python

import math

class classCircle:
def init(self,rad):
self.rad=rad
def radius(self):
print 'Radius: %f' % self.rad
def diameter(self):
diam = self.rad*2
print 'Diameter: %f' % diam
def circumference(self):
circum = self.rad*2*math.pi
print 'Circumference: %f' % circum
def area(self):
area = math.pow(self.rad,2)*math.pi
print 'Area: %f' % area
def info(self):
self.radius()
self.diameter()
self.circumference()
self.area()

circle = classCircle()
circle.init(5)
circle.info()

Output:
Radius: 5.000000
Diameter: 10.000000
Circumference: 31.415927
Area: 78.539816

March Madness Challenge - MMC13

Normally I work on stuff like that later at night. But we lost power from Saturday 4 pm to Sunday morning. So no program for Saturday.

Friday, March 12, 2010

March Madness Challenge - MMC12

#! /usr/bin/python

print "I'm so tired I'm going to bed now!"


BTW: It's 8:37 PM right now, the posting times are some king of wrong!

Thursday, March 11, 2010

March Madness Challenge - MMC11

The problem from yesterdays post was that it is using multiplication. I replaced the Laplace filter with a Rank filter. The result is much better and the program runs 40 seconds instead of 5 Minutes. See yourself...



The result looks like this. The result of displaying the edges is much better.


#! /usr/bin/python

from PIL import Image
from numpy import matrix

import matplotlib.pyplot as plt
import sys
import os
import shutil

outfile = os.path.splitext(sys.argv[1])[0] + 'Rank.jpg'
shutil.copy(sys.argv[1], outfile)

img = Image.open(sys.argv[1])
pix = img.load()

width = img.size[0]
height = img.size[1]

width -= 1
height -= 1

out = Image.open(outfile)
outpix = out.load()

# loop thru image
for x in range(1,width,1):
for y in range(1,height,1):
# do calculation
pixellist = []
for mx in range(-1,2,1):
for my in range(-1,2,1):
if mx!=0 and my!=0:
pixellist.append(pix[x+mx,y+my])
pixellist.sort()
val = pixellist[len(pixellist)-1]-pixellist[0]
if val > 255:
val = 255
if val < 0:
val = 0

outpix[x,y] = val

out.show()
out.save(outfile, 'JPEG')

Wednesday, March 10, 2010

March Madness Challange - MMC10

Today I created and applied a Laplace filter. The Laplace filter detects edges in an image. The program is slow, it runs about five minutes for my test image, so there is room for improvements.


You have to open it if you want to see the details!



I applied a Threshold of 30, so you be able to see a little bit more.

 
1 #! /usr/bin/python
2
3 from PIL import Image
4 from numpy import matrix
5
6 import matplotlib.pyplot as plt
7 import sys
8 import os
9 import shutil
10
11 outfile = os.path.splitext(sys.argv[1])[0] + 'Laplace.jpg'
12 shutil.copy(sys.argv[1], outfile)
13
14 # Laplace Filter
15 lp = matrix([[0,-1,0],[-1,4,-1],[0,-1,0]])
16
17 # Hot Spot
18 hs = matrix([[0,0,0],[0,0,0],[0,0,0]])
19
20 img = Image.open(sys.argv[1])
21 pix = img.load()
22
23 width = img.size[0]
24 height = img.size[1]
25
26 width -= 1
27 height -= 1
28
29 out = Image.open(outfile)
30 outpix = out.load()
31
32 # loop thru image
33 foor x in range(1,width,1):
34 for y in range(1,height,1):
35 # do calculation
36 sum = 0
37 for mx in range(-1,2,1):
38 for my in range(-1,2,1):
39 sum += pix[x+mx,y+my]*lp[mx+1,my+1]
40 if sum > 255:
41 sum = 255
42 if sum < 0:
43 sum = 0
44 # if sum > 30:
45 # sum = 255
46
47 outpix[x,y] = sum
48
49 #out.show()
50 out.save(outfile, 'JPEG')

Tuesday, March 9, 2010

March Madness Challenge - MMC09

Today only a little play around with plotting. I guess tomorrow when I have more time I will plot my own histogram.

1 #! /usr/bin/python
2
3 import matplotlib.pyplot as plt
4
5 plt.plot([0,2,1,3])
6 plt.ylabel('value')
7 plt.xlabel('plot test')
8 plt.show()

Monday, March 8, 2010

March Madness Challenge - MMC08

Image processing at University was not always fun. Today I tried to create a histogram of a gray scale image. I wanted to use an array that has 256 elements. Then I wanted to loop thru the whole image, use the value as index and increase by one in the 256 array. But the histogram function does not like tuples I guess. So this python script is totally inefficient, because it creates an array that has x*y values between 0 and 255 instead of 256 values.

1 #! /usr/bin/python
2
3 from PIL import Image
4 import matplotlib.pyplot as plt
5 import sys
6
7 histo = []
8
9 """for i in range(0,256,1):
10 histo.append([i,0])"""
11
12 img = Image.open(sys.argv[1])
13 pix = img.load()
14
15 width = img.size[0]
16 height = img.size[1]
17
18 for x in range(0,width,1):
19 for y in range(0,height,1):
20 #histo[pix[x,y]][1] += 1
21 histo.append(pix[x,y])
22
23 plt.hist(histo,256)
24 plt.xlabel('Grayvalue')
25 plt.ylabel('Frequency')
26 plt.title('Histogram %s' % sys.argv[1])
27 plt.grid(True)
28 plt.show()
29



Sunday, March 7, 2010

March Madness Challenge - MMC07

Inspired by Adams post I made the FizzBuzz test. I used python and it took me about two Minutes. So I guess I'm ok. ;-)

1 #! /usr/bin/python
2
3 mod3 = False
4 mod5 = False
5
6 for i in range(1,101,1):
7 mod3 = False
8 mod5 = False
9
10 if (i % 3) == 0:
11 mod3 = True
12 if (i % 5) == 0:
13 mod5 = True
14
15 if (mod3 and mod5):
16 print 'fizzbuzz'
17 elif mod3:
18 print 'fizz'
19 elif mod5:
20 print 'buzz'
21 else:
22 print '%d' % i
23

Saturday, March 6, 2010

March Madness Challenge - MMC06

Going to PA today, coming home late. So I have to pull the "Hello World" one.

1 #! /usr/bin/python
2
3 print 'Hello World'
4

Friday, March 5, 2010

March Madness Challenge - MMC05

Today I had absolutely no time. So here is a little bit of bit-shifting for you.
    1 #! /usr/bin/python
2
3 x = 1
4
5 for i in range(8):
6 x <<= 1
7 print x
8

Thursday, March 4, 2010

March Madness Challenge - MMC04

Working with the python documentation some kind of sucks. Maybe its me.... Putting code into blogger is still a problem, will see what I can do about that.

Threading is todays topic. A user specified number of threads are going to sleep for random 1 to 5 seconds and then try to access a shared counter. Whatever number of threads you set as argument, the counter should have the some value. I'm still a little bit confused about when to use "import" or "from x import y".



1 #! /usr/bin python
2
3 import random
4 import thread
5 import time
6
7 counter = 0
8
9 def threadFunc(threadID, lock):
10 print 'Thread %d START' % threadID
11 sleep = random.randint(1,5)
12 print 'Thread %d will sleep for %d seconds' % (threadID,sleep)
13 time.sleep(sleep)
14 lock.acquire()
15 try:
16 global counter
17 counter += 1
18 finally:
19 lock.release()
20 print 'Thread %d END' % threadID
21
22 def runThreads(threadCount):
23 cntLock = thread.allocate_lock()
24
25 for i in range(int(threadCount)):
26 t = Thread(target=threadFunc, args=(i,cntLock))
27 t.start()
28
29 if __name__ == '__main__':
30 print '***** MMC04 *****'
31
32 from threading import Thread
33
34 from optparse import OptionParser
35 parser = OptionParser()
36 parser.add_option("-t", "--threads", dest="threadCount", default='1',
37 help='number of threads')
38 (options, args) = parser.parse_args()
39
40 runThreads(options.threadCount)
41
42 time.sleep(6)
43 print 'Counter = %d' % counter
44

Wednesday, March 3, 2010

March Madness Challenge - MMC03

I wrote a little program that checks if a web server is running at a user specified ip address. While I was browsing to the documentation is saw OptionParse. This is a really nice way to parse arguments. Especially the -h option, that will generate the usage info automatically.

Possible output:

python mmc03.py -i 127.0.0.1 -r /
***** MMC03 *****
Port 80 check successfull!
Webserver is running! Response: 302 Found

python mmc03.py -i 127.0.0.1 -r /
***** MMC03 *****
Port 80 check failed: [Errno 10061] No connection could be made because the target machine actively refused it


1 #! /usr/bin python
2
3 import httplib
4
5 def checkPort(ip, resource):
6 if not resource.startswith('/'):
7 resource = '/' + resource
8
9 try:
10 conn = httplib.HTTPConnection(ip, httplib.HTTP_PORT)
11 conn.request('GET', resource)
12 response = conn.getresponse()
13 print 'Port %s check successfull!' % httplib.HTTP_PORT
14 if (httplib.responses[response.status]):
15 print 'Webserver is running! Response: %s %s' % \
16 (response.status, response.reason)
17 except Exception, e:
18 print 'Port %s check failed: %s' % (httplib.HTTP_PORT, e)
19 return False
20 finally:
21 conn.close()
22
23 if __name__ == '__main__':
24 print '***** MMC03 *****'
25
26 from optparse import OptionParser
27 parser = OptionParser()
28 parser.add_option("-i", "--ip", dest="ip", default='127.0.0.1',
29 help='ip address of server')
30 parser.add_option("-r", "--resource", dest="resource", default="/",
31 help="resource to check")
32 (options, args) = parser.parse_args()
33
34 checkPort(options.ip, options.resource)
35

Tuesday, March 2, 2010

March Madness Challenge - MMC02

Today I worked a little bit with file handling and string manipulation. The script takes two files as argument, one input and one output file. It reads the input file line by line, capitalize all letters, prints each line and writes then into the output file.

My input file in.txt looked like that:

This is a test for March Madness 2010!
The idea is absolutely cool!

After run the mmc02.py, my out.txt looked like that:

THIS IS A TEST FOR MARCH MADNESS 2010!
THE IDEA IS ABSOLUTELY COOL!


1 #! /usr/bin/python
2
3 import os
4 import sys
5
6 print '***** MMC02 *****'
7
8 if os.path.isfile(sys.argv[2]):
9 os.remove(sys.argv[2])
10
11 try:
12 inFile = file(sys.argv[1], 'r')
13 outFile = file(sys.argv[2], 'w')
14 except:
15 inFile = None
16 outfile = None
17
18 if inFile and outFile:
19 for line in inFile:
20 outFile.write(line.upper())
21 print line.upper()
22

Monday, March 1, 2010

March Madness Challenge - MMC01

I'm going to be part of the March Madness Challenge!

I'm will use Python, because I never used it. So don't expect much, just small little helper programs to learn Python.

The first program is a classic: It loops thru a given folder and prints the name of the files that have the extension you want.

#! /usr/bin/python

import os
import sys

def visit(arg, dirname, names):
os.chdir(dirname)
for name in names:
splitName = os.path.splitext(name)
if (splitName[1] == sys.argv[2]):
print name

def usage():
print 'List all files in given folder with specified extension.'
print 'Use MMC01 Path Extension'
print 'Example MMC01.py . .py'

print '***** MMC01 *****'
if (len(sys.argv) != 3):
usage()
else:
os.path.walk(sys.argv[1], visit, 0)


Possible output:

b$ python mmc01.py
***** MMC01 *****
List all files in given folder with specified extension.
Use MMC01 Path Extension
Example MMC01.py . .py

b$ python mmc01.py . .py
***** MMC01 *****
mmc01.py


Sorry about the format messup. I will figure out how to post code with format in here.


This is it!

I'm officially entering the bolgosphere.