首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >利用Gibbs采样分割图像

利用Gibbs采样分割图像
EN

Code Review用户
提问于 2012-12-04 02:31:53
回答 1查看 915关注 0票数 3

我一直在阅读一些NumPy指南,但似乎无法理解。我的助教告诉我,我应该能够通过在下面的代码段中使用NumPy数组而不是for循环来加速我的代码。

代码语言:javascript
复制
for neighbor in get_neighbors(estimates,i,j):
            pXgivenX_ *= edge_model(True,neighbor)*observation_model(obs,True)
            pX_givenX_  *= edge_model(False,neighbor)*observation_model(obs,False)

下面是它所在的方法的全部代码:

代码语言:javascript
复制
def gibbs_segmentation(image, burnin, collect_frequency, n_samples):
"""
Uses Gibbs sampling to segment an image into foreground and background.

Inputs
------
image : a numpy array with the image. Should be Nx x Ny x 3
burnin : Number of iterations to run as 'burn-in' before collecting data
collect_frequency : How many samples in between collected samples
n_samples : how many samples to collect in total

Returns
-------
A distribution of the collected samples: a numpy array with a value between
0 and 1 (inclusive) at every pixel.
"""
(Nx, Ny, _) = image.shape
total_iterations = burnin + (collect_frequency * (n_samples - 1))
pixel_indices = list(itertools.product(xrange(Nx),xrange(Ny)))
# The distribution that you will return
distribution = np.zeros( (Nx, Ny) )

# Initialize binary estimates at every pixel randomly. Your code should
# update this array pixel by pixel at each iteration.
estimates = np.random.random( (Nx, Ny) ) > .5

# PreProcessing
preProObs = {}
for (i,j) in pixel_indices:
        preProObs[(i,j)] = []
        preProObs[(i,j)].append(observation_model(image[i][j],False))
        preProObs[(i,j)].append(observation_model(image[i][j],True))

for iteration in xrange(total_iterations):

    # Loop over entire grid, using a random order for faster convergence
    random.shuffle(pixel_indices)

    for (i,j) in pixel_indices:

        pXgivenX_ = 1
        pX_givenX_ = 1

        for neighbor in get_neighbors(estimates,i,j):
            pXgivenX_ *= edge_model(True,neighbor)*preProObs[(i,j)][1]
            pX_givenX_  *= edge_model(False,neighbor)*preProObs[(i,j)][0]
        estimates[i][j] = np.random.random() > pXgivenX_/(pXgivenX_+pX_givenX_)

    if iteration > burnin and (iteration-burnin)%collect_frequency == 0:
        distribution += estimates

return distribution / n_samples

def edge_model(label1, label2):
    """
    Given the values at two pixels, returns the edge potential between
    those two pixels.

    Hint: there might be a more efficient way to compute this for an array
    of values using numpy!
    """
    if label1 == label2:
        return ALPHA
    else:
        return 1-ALPHA
EN

回答 1

Code Review用户

回答已采纳

发布于 2012-12-04 03:40:59

由于这是家庭作业,我不会给你确切的答案,但这里有一些提示。

  1. ==在numpy中重载,以便在传入数组时返回数组。所以你可以这样做:>>> numpy.arange(5) == 3数组(假,真,假,dtype=bool) >>> (numpy.arange(5) == 3) == False array(真,假,真,真,dtype=bool)
  2. 可以使用布尔数组向数组中的特定位置分配。例如:>>> mostly_true = (numpy.arange(5) == 3) == False >>> === numpy.zeros(5) >>>空主要是_真的=5 >>>空数组(5.、5.、5.、0.5)
  3. 您还可以否定布尔数组;这些事实一起允许您有条件地将值赋值给数组。(numpy.where可以用来做类似的事情):>>>空~大部分_真的=1 >>>空数组(5.、5.、5.、1、5。)
  4. 然后可以将这些值乘以其他值:>>>空* numpy.arange(5)数组(0、5、10、3、20。)
  5. 许多不同的numpy函数(真正的古函数)提供了一个沿整个数组应用函数的reduce方法:>>>结果=空* numpy.arange(5) >>> numpy.multiply.reduce(结果) 0.0

您应该能够使用上述技术完全消除该for循环。

票数 6
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/19329

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档