Python List Display
I have a list of indices stored in a list of tuples:
index=[(0,0), (0,1), (1,0), (1,1) ....]
These indices will be used to calculate the energy in the image im
(numpy array) in the following formula:
(1-im[0,0])^2+(1-im[0,1])^2+....
im
is a two dimensional numpy array. Here's an example im
:
im=Image.open('lena_noisy.png')
im=numpy.array(im)
print im
[[168 133 131 ..., 127 213 107]
[174 151 111 ..., 191 88 122]
[197 173 143 ..., 182 153 125]
...,
[ 34 15 6 ..., 111 95 104]
[ 37 15 57 ..., 121 133 134]
[ 49 39 58 ..., 115 74 107]]
How do I use the list map feature to do this calculation?
source to share
If you split index
into two tuples, xidx
and yidx
, you can use fantasy indexing to access all values im
as a single numpy array. The computation then becomes simpler to express and faster than executing a Python loop (or list comprehension):
import numpy as np
xidx, yidx = zip(*index)
print(((1-im[xidx, yidx])**2).sum())
import numpy as np
import scipy.misc as misc
im = misc.lena()
n = min(im.shape)
index = np.random.randint(n, size = (10000,2)).tolist()
def using_fancy_indexing(index, im):
xidx, yidx = zip(*index)
return (((1-im[xidx, yidx])**2).sum())
def using_generator_expression(index, im):
return sum(((1 - im[i[0], i[1]]) ** 2) for i in index)
Here's a comparison using timeit:
In [27]: %timeit using_generator_expression(index, im)
100 loops, best of 3: 17.9 ms per loop
In [28]: %timeit using_fancy_indexing(index, im)
100 loops, best of 3: 2.07 ms per loop
So, depending on size, index
using index fing can be up to 8 times faster than using a generator expression.
source to share