Hướng dẫn gaussian mixture model histogram python - biểu đồ mô hình hỗn hợp gaussian python

Tôi đang cố gắng thực hiện phân đoạn hình ảnh tự động của các vùng khác nhau của hình ảnh MR 2D dựa trên các giá trị cường độ pixel. Bước đầu tiên là triển khai mô hình hỗn hợp Gaussian trên biểu đồ của hình ảnh.

Hướng dẫn gaussian mixture model histogram python - biểu đồ mô hình hỗn hợp gaussian python

Tôi cần vẽ đồ thị Gaussian thu được từ phương pháp score_samples lên biểu đồ. Tôi đã thử tuân theo mã trong câu trả lời (hiểu các mô hình hỗn hợp Gaussian).

Tuy nhiên, Gaussian kết quả không thể phù hợp với biểu đồ. Làm thế nào để tôi có được Gaussian phù hợp với biểu đồ?

Hướng dẫn gaussian mixture model histogram python - biểu đồ mô hình hỗn hợp gaussian python

import numpy as np
import cv2
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture

# Read image
img = cv2.imread("test.jpg",0)

hist = cv2.calcHist([img],[0],None,[256],[0,256])
hist[0] = 0     # Removes background pixels

# Fit GMM
gmm = GaussianMixture(n_components = 3)
gmm = gmm.fit(hist)

# Evaluate GMM
gmm_x = np.linspace(0,255,256)
gmm_y = np.exp(gmm.score_samples(gmm_x.reshape(-1,1)))


# Plot histograms and gaussian curves
fig, ax = plt.subplots()
ax.hist(img.ravel(),255,[1,256])
ax.plot(gmm_x, gmm_y, color="crimson", lw=4, label="GMM")

ax.set_ylabel("Frequency")
ax.set_xlabel("Pixel Intensity")

plt.legend()

plt.show()

Tôi cũng đã cố gắng xây dựng thủ công người Gaussian với số tiền.

Hướng dẫn gaussian mixture model histogram python - biểu đồ mô hình hỗn hợp gaussian python

import numpy as np
import cv2
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture

def gauss_function(x, amp, x0, sigma):
    return amp * np.exp(-(x - x0) ** 2. / (2. * sigma ** 2.))

# Read image
img = cv2.imread("test.jpg",0)

hist = cv2.calcHist([img],[0],None,[256],[0,256])
hist[0] = 0     # Removes background pixels

# Fit GMM
gmm = GaussianMixture(n_components = 3)
gmm = gmm.fit(hist)

# Evaluate GMM
gmm_x = np.linspace(0,255,256)
gmm_y = np.exp(gmm.score_samples(gmm_x.reshape(-1,1)))

# Construct function manually as sum of gaussians
gmm_y_sum = np.full_like(gmm_x, fill_value=0, dtype=np.float32)
for m, c, w in zip(gmm.means_.ravel(), gmm.covariances_.ravel(), gmm.weights_.ravel()):
    gauss = gauss_function(x=gmm_x, amp=1, x0=m, sigma=np.sqrt(c))
    gmm_y_sum += gauss / np.trapz(gauss, gmm_x) * w

# Plot histograms and gaussian curves
fig, ax = plt.subplots()
ax.hist(img.ravel(),255,[1,256])
ax.plot(gmm_x, gmm_y, color="crimson", lw=4, label="GMM")
ax.plot(gmm_x, gmm_y_sum, color="black", lw=4, label="Gauss_sum", linestyle="dashed")

ax.set_ylabel("Frequency")
ax.set_xlabel("Pixel Intensity")

plt.legend()

plt.show()

Với ax.hist(img.ravel(),255,[1,256], normed=True)

Hướng dẫn gaussian mixture model histogram python - biểu đồ mô hình hỗn hợp gaussian python

Ghi chú

Nhấn vào đây để tải xuống mã ví dụ đầy đủhere to download the full example code

Ví dụ này thực hiện phân tích mô hình hỗn hợp Gaussian của biểu đồ hình ảnh để tìm các ngưỡng phù hợp để tách tiền cảnh khỏi nền.

Hướng dẫn gaussian mixture model histogram python - biểu đồ mô hình hỗn hợp gaussian python

import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture

np.random.seed(1)
n = 10
l = 256
im = np.zeros((l, l))
points = l*np.random.random((2, n**2))
im[(points[0]).astype(np.int), (points[1]).astype(np.int)] = 1
im = ndimage.gaussian_filter(im, sigma=l/(4.*n))

mask = (im > im.mean()).astype(np.float)


img = mask + 0.3*np.random.randn(*mask.shape)

hist, bin_edges = np.histogram(img, bins=60)
bin_centers = 0.5*(bin_edges[:-1] + bin_edges[1:])

classif = GaussianMixture(n_components=2)
classif.fit(img.reshape((img.size, 1)))

threshold = np.mean(classif.means_)
binary_img = img > threshold


plt.figure(figsize=(11,4))

plt.subplot(131)
plt.imshow(img)
plt.axis('off')
plt.subplot(132)
plt.plot(bin_centers, hist, lw=2)
plt.axvline(0.5, color='r', ls='--', lw=2)
plt.text(0.57, 0.8, 'histogram', fontsize=20, transform = plt.gca().transAxes)
plt.yticks([])
plt.subplot(133)
plt.imshow(binary_img, cmap=plt.cm.gray, interpolation='nearest')
plt.axis('off')

plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1)
plt.show()

Tổng thời gian chạy của tập lệnh: (0 phút 0,248 giây) ( 0 minutes 0.248 seconds)

Phòng trưng bày được tạo ra bởi Sphinx-Gallery

Sự khác biệt giữa k là gì

Sự khác biệt có thể nhìn thấy đầu tiên giữa hỗn hợp K-means và Gaussian là hình dạng ranh giới quyết định. GM có phần linh hoạt hơn và với một ma trận hiệp phương sai, chúng ta có thể tạo ra các ranh giới hình elip, trái ngược với ranh giới tròn với K-MEAN. Một điều nữa là GMS là một thuật toán xác suất.the shape the decision boundaries. GMs are somewhat more flexible and with a covariance matrix ∑ we can make the boundaries elliptical, as opposed to circular boundaries with K-means. Another thing is that GMs is a probabilistic algorithm.

Mô hình hỗn hợp Gaussian có tốt hơn K không

Mô hình hỗn hợp Gaussian cung cấp phân cụm tốt hơn với ranh giới sử dụng riêng biệt.Mặc dù, mô hình hỗn hợp Gaussian có thời gian tính toán cao hơn K-MEAN, nó có thể được sử dụng khi cần có nhiều đặc tính và phân tích khối lượng công việc chi tiết hơn.c 2020 Các tác giả.. Although, Gaussian Mixture Model has higher computation time than K-Means, it can be used when more fine-grained workload characterization and analysis is required. c 2020 The Authors.

GMM trong Python là gì?

Một mô hình hỗn hợp Gaussian (GMM) cố gắng tìm một hỗn hợp các phân phối xác suất Gaussian đa chiều mà mô hình hóa tốt nhất bất kỳ bộ dữ liệu đầu vào nào.Trong trường hợp đơn giản nhất, GMMS có thể được sử dụng để tìm các cụm theo cách tương tự như K-MEANS: từ Sklearn.Mixture Nhập GMM GMM = GMM (N_Components = 4).FIT (x) Nhãn = gmm. (GMM) attempts to find a mixture of multi-dimensional Gaussian probability distributions that best model any input dataset. In the simplest case, GMMs can be used for finding clusters in the same manner as k-means: from sklearn.mixture import GMM gmm = GMM(n_components=4). fit(X) labels = gmm.

Làm thế nào một mô hình hỗn hợp Gaussian có thể được sử dụng để phân cụm?

Các mô hình hỗn hợp Gaussian (GMM) thường được sử dụng để phân cụm dữ liệu.Bạn có thể sử dụng GMM để thực hiện phân cụm cứng hoặc phân cụm mềm trên dữ liệu truy vấn.Để thực hiện phân cụm cứng, GMM gán dữ liệu truy vấn chỉ vào các thành phần bình thường đa biến nhằm tối đa hóa xác suất sau thành phần, được đưa ra dữ liệu.use GMMs to perform either hard clustering or soft clustering on query data. To perform hard clustering, the GMM assigns query data points to the multivariate normal components that maximize the component posterior probability, given the data.