2016-11-11 108 views
-3

我想根據給定數量的類的輸入訓練樣本對RGB圖像執行像素分類。所以我有4個類包含像素(r,g,b),因此目標是將圖像分爲四個階段。Python中的最大似然像素分類opencv

我發現python opencv2具有可以完成這項工作的期望最大化算法。但不幸的是,我沒有找到任何教程或材料可以解釋我(因爲我是初學者)如何使用該算法。

你能否提出任何一種可以作爲出發點的教程?

更新...的另一種方法爲以下代碼:

**def getsamples(img): 
    x, y, z = img.shape 
    samples = np.empty([x * y, z]) 
    index = 0 
    for i in range(x): 
     for j in range(y): 
      samples[index] = img[i, j] 
      index += 1 
    return samples 
def EMSegmentation(img, no_of_clusters=2): 
    output = img.copy() 
    colors = np.array([[0, 11, 111], [22, 22, 22]]) 
    samples = getsamples(img) 
    #em = cv2.ml.EM_create() 
    em = cv2.EM(no_of_clusters) 
    #em.setClustersNumber(no_of_clusters) 
    #em.trainEM(samples) 
    em.train(samples) 
    x, y, z = img.shape 
    index = 0 
    for i in range(x): 
     for j in range(y): 

      result = em.predict(samples[index])[0][1] 
      #print(result) 
      output[i][j] = colors[result] 
      index = index + 1 
    return output 
img = cv2.imread('00.jpg') 
smallImg = small = cv2.resize(img, (0,0), fx=0.5, fy=0.5) 
output = EMSegmentation(img) 
smallOutput = cv2.resize(output, (0,0), fx=0.5, fy=0.5) 
cv2.imshow('image', smallImg) 
cv2.imshow('EM', smallOutput) 
cv2.waitKey(0) 
cv2.destroyAllWindows()** 
+1

簡而言之:ģO_O GLE。長:谷歌「期望最大化算法」。一旦你有足夠的關於這個概念的信息,谷歌這個:「期望最大化算法opencv」。請注意,opencv是一個庫,而不是一本書。您需要研究研究論文,書籍,維基或任何您覺得最適合的來源的技術。 downvote的原因: - 我在第一次嘗試中找到了多個教程。如果仍然有問題,谷歌YouTube的相同,你會發現相同的視頻教程。 – saurabheights

+0

搜索opencv 2.4.x和3.0之間的等效函數,對於我的代碼使用來源:https://subokita.com/2014/03/24/image-segmentation-using-opencvs-expectation-maximization/ – eyllanesc

回答

1

轉換C++到Python source

enter image description here

import cv2 
import numpy as np 


def getsamples(img): 
    x, y, z = img.shape 
    samples = np.empty([x * y, z]) 
    index = 0 
    for i in range(x): 
     for j in range(y): 
      samples[index] = img[i, j] 
      index += 1 
    return samples 


def EMSegmentation(img, no_of_clusters=2): 
    output = img.copy() 
    colors = np.array([[0, 11, 111], [22, 22, 22]]) 
    samples = getsamples(img) 
    em = cv2.ml.EM_create() 
    em.setClustersNumber(no_of_clusters) 
    em.trainEM(samples) 
    means = em.getMeans() 
    covs = em.getCovs() # Known bug: https://github.com/opencv/opencv/pull/4232 
    x, y, z = img.shape 
    distance = [0] * no_of_clusters 
    for i in range(x): 
     for j in range(y): 
      for k in range(no_of_clusters): 
       diff = img[i, j] - means[k] 
       distance[k] = abs(np.dot(np.dot(diff, covs[k]), diff.T)) 
      output[i][j] = colors[distance.index(max(distance))] 
    return output 


img = cv2.imread('dinosaur.jpg') 
output = EMSegmentation(img) 
cv2.imshow('image', img) 
cv2.imshow('EM', output) 
cv2.waitKey(0) 
cv2.destroyAllWindows() 
+0

謝謝你幫助! – Kristan

+0

品牌作爲正確的解決方案:D – eyllanesc

+0

您能否告訴我您使用哪種opencv版本?我有2.4.13,它似乎不能打電話給getMeans()。 – Kristan