Skip to content

Instantly share code, notes, and snippets.

@mmiliaus
Created December 23, 2011 13:03
Show Gist options
  • Save mmiliaus/1514153 to your computer and use it in GitHub Desktop.
Save mmiliaus/1514153 to your computer and use it in GitHub Desktop.
python cheatsheet
def foo(x, y=10, **kwargs):
# dictionaries
dict = {'a':1, 'b':23, 'c':'eggs'}
del dict['b']
dict.has_key('e')
# list comprehension
[x for x in range(5) if x%2 == 0]
# exception
try:
# conditions
if x == 0:
bar()
else:
foo(x - 1)
except AttributeError:
handle_error()
print("%s pages to the printer %s" % (num, printer))
# Matrixes
b[2,3]
b[0:5, 1] # each row in the second column of b
b[ : ,1] # equivalent to the previous example
b[1:3, : ] # each column in the second and third row of b
from PIL import Image
import numpy
import scipy
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from scipy import ndimage
from stsci.convolve import convolve2d, correlate2d
# reads and converts to grayscale and stores to ndarray
image = numpy.asarray( Image.open('TokyoPanoramaShredded.png').convert('L') )
x_kernel = numpy.array (
[
[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]
]
)
y_kernel = numpy.array (
[
[-1, -2, -1],
[0, 0, 0],
[1, 2, 1]
]
)
gx = convolve2d( image, x_kernel )
gy = convolve2d( image, y_kernel )
out = numpy.hypot( gx, gy )
out *= 255.0 / numpy.max(out)
# plots ndarray using gray color map
plt.imshow(out, cmap=cm.gray)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment