机器视觉编程作业02(00)EM算法

任务:对图像进行边缘检测

思路:

  1. )将图像的灰度数值进行0-255的维度统计;
  2. )EM算法分析出几个核心显示区块的灰度;
  3. )使用通用的边界检测算法(具体哪一种待定)。

编辑于2017.12.24 15:45

 EM算法的使用参考:

# -*- coding: utf-8 -*-
"""
Created on Tue Oct 24 18:40:00 2017

@author: nvidia
"""

#EM Algorithm

from numpy import *
import numpy as np
import random
import copy

SIGMA = 6
EPS = 0.0001
#生成方差相同,均值不同的样本
def generate_data():
    Miu1 = 20
    Miu2 = 40
    N = 1000
    #N = 10000
    X = mat(zeros((N,1)))
    for i in range(N):
        temp = random.uniform(0,1)
        if(temp > 0.5):
            X[i] = temp*SIGMA + Miu1
        else:
            X[i] = temp*SIGMA + Miu2
    return X

#EM算法 key
def my_EM(X):
    k = 2
    N = len(X)
    Miu = np.random.rand(k,1)
    print "This is the origenal key :\n",Miu
    Posterior = mat(zeros((N,2)))
    dominator = 0
    numerator = 0
    #先求后验概率
    for iter in range(1000):
        for i in range(N):
            dominator = 0
            for j in range(k):
                dominator = dominator + np.exp(-1.0/(2.0*SIGMA**2) * (X[i] - Miu[j])**2)
                #print dominator,-1/(2*SIGMA**2) * (X[i] - Miu[j])**2,2*SIGMA**2,(X[i] - Miu[j])**2
                #return
            for j in range(k):
                numerator = np.exp(-1.0/(2.0*SIGMA**2) * (X[i] - Miu[j])**2)
                Posterior[i,j] = numerator/dominator
        oldMiu = copy.deepcopy(Miu)
        #最大化
        for j in range(k):
            numerator = 0
            dominator = 0
            for i in range(N):
                numerator = numerator + Posterior[i,j] * X[i]
                dominator = dominator + Posterior[i,j]
            Miu[j] = numerator/dominator
        print Miu
        #print (abs(Miu - oldMiu)).sum()
            #print '\n'
        if (abs(Miu - oldMiu)).sum() < EPS:
            print Miu
            print iter
            print (abs(Miu - oldMiu)).sum()
            break
        

if __name__ == '__main__':
    X = generate_data()
    my_EM(X)

 

posted on 2017-12-24 15:29  周健康  阅读(542)  评论(0编辑  收藏  举报

导航