Using Gibbs sampling to segment an image
Since this is homework, I won't give you the exact answer, but here are some hints. 


== is overloaded in numpy to return an array when you pass in an array. So you can do things like this: 

&gt;&gt;&gt; numpy.arange(5) == 3
array([False, False, False,  True, False], dtype=bool)
&gt;&gt;&gt; (numpy.arange(5) == 3) == False
array([ True,  True,  True, False,  True], dtype=bool)

You can use boolean arrays to assign to specific locations in an array. For example:

&gt;&gt;&gt; mostly_true = (numpy.arange(5) == 3) == False
&gt;&gt;&gt; empty = numpy.zeros(5)
&gt;&gt;&gt; empty[mostly_true] = 5
&gt;&gt;&gt; empty
array([ 5.,  5.,  5.,  0.,  5.])

You can also negate boolean arrays; together, these facts allow you to conditionally assign values to an array. (numpy.where can be used to do something similar.):

&gt;&gt;&gt; empty[~mostly_true] = 1
&gt;&gt;&gt; empty
array([ 5.,  5.,  5.,  1.,  5.])

You can then multiply those values by other values:

&gt;&gt;&gt; empty * numpy.arange(5)
array([  0.,   5.,  10.,   3.,  20.])

And many different numpy functions (really ufuncs) provide a reduce method that applies the function along the entire array:

&gt;&gt;&gt; results = empty * numpy.arange(5)
&gt;&gt;&gt; numpy.multiply.reduce(results)
0.0



You should be able to completely eliminate that for loop using only the above techniques.