Gaussian Mixture Model for Image Histogram


Dotted glass

I am trying to do automatic image segmentation of different regions of a 2D MR image based on pixel intensity values. The first step is to implement a Gaussian mixture model on the histogram of the image.

test.jpg

I need to plot the resulting Gaussian obtained from this score_samplesmethod onto a histogram. I have tried following the code in the answer ( Understanding Gaussian Mixture Models ) .

However, the resulting Gaussian cannot match the histogram at all. How can I make a Gaussian match a histogram?

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()

I also tried manually constructing the Gaussian with the sum.

enter image description here

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()

useax.hist(img.ravel(),255,[1,256], normed=True) enter image description here

Dotted glass

The problem is with passing a histogram to GaussianMixture.fit instead of an array of pixel intensities gmm = gmm.fit(hist). I've also found that there are minimal requirements that n_components = 6visually fit this particular histogram .

enter image description here

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

data = img.ravel()
data = data[data != 0]
data = data[data != 1]  #Removes background pixels (intensities 0 and 1)

# Fit GMM
gmm = GaussianMixture(n_components = 6)
gmm = gmm.fit(X=np.expand_dims(data,1))

# Evaluate GMM
gmm_x = np.linspace(0,253,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,[2,256], normed=True)
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()

Related


Gaussian Mixture Model for Image Histogram

Dotted glass I am trying to do automatic image segmentation of different regions of a 2D MR image based on pixel intensity values. The first step is to implement a Gaussian mixture model on the histogram of the image. I need to plot the resulting Gaussian obta

Gaussian Mixture Model for Image Histogram

Dotted glass I am trying to do automatic image segmentation of different regions of a 2D MR image based on pixel intensity values. The first step is to implement a Gaussian mixture model on the histogram of the image. I need to plot the resulting Gaussian obta

Gaussian Mixture Model for Image Histogram

Dotted glass I am trying to do automatic image segmentation of different regions of a 2D MR image based on pixel intensity values. The first step is to implement a Gaussian mixture model on the histogram of the image. I need to plot the resulting Gaussian obta

Gaussian Mixture Model for Image Histogram

Dotted glass I am trying to do automatic image segmentation of different regions of a 2D MR image based on pixel intensity values. The first step is to implement a Gaussian mixture model on the histogram of the image. I need to plot the resulting Gaussian obta

Gaussian Mixture Model Cross Validation

Newkid I want to perform cross validation on my Gaussian mixture model. Currently, my cross_validationapproach using sklearn is as follows. clf = GaussianMixture(n_components=len(np.unique(y)), covariance_type='full') cv_ortho = cross_validate(clf, parameters_

Gaussian Mixture Model Cross Validation

Newkid I want to perform cross validation on my Gaussian mixture model. Currently, my cross_validationapproach using sklearn is as follows. clf = GaussianMixture(n_components=len(np.unique(y)), covariance_type='full') cv_ortho = cross_validate(clf, parameters_

Gaussian Mixture Model (GMM) is not suitable

Book I've been using Scikit-learn's GMM function. First, I created a distribution along the line x=y. from sklearn import mixture import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D line_model = mixture.GMM(n_components

Gaussian Mixture Model (GMM) is not suitable

BenB I've been using Scikit-learn's GMM function. First, I created a distribution along the line x=y. from sklearn import mixture import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D line_model = mixture.GMM(n_components

Number of parameters in a Gaussian mixture model

golden_truth I have D-dimensional data with K components. How many parameters do I need if I use a model with a full covariance matrix? and if I use the diagonal covariance matrix how many? golden_truth xyLe_ 's answer in CrossValidated https://stats.stackexch

Gaussian Mixture Model Cross Validation

Newkid I want to perform cross validation on my Gaussian mixture model. Currently, my cross_validationapproach using sklearn is as follows. clf = GaussianMixture(n_components=len(np.unique(y)), covariance_type='full') cv_ortho = cross_validate(clf, parameters_

Gaussian Mixture Model Cross Validation

Newkid I want to perform cross validation on my Gaussian mixture model. Currently, my cross_validationapproach using sklearn is as follows. clf = GaussianMixture(n_components=len(np.unique(y)), covariance_type='full') cv_ortho = cross_validate(clf, parameters_

Gaussian Mixture Model (GMM) is not suitable

BenB I've been using Scikit-learn's GMM function. First, I created a distribution along the line x=y. from sklearn import mixture import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D line_model = mixture.GMM(n_components

Problems with sklearn.mixture.GMM (Gaussian Mixture Model)

Gabriele Pompa I'm fairly new to scikit-lear and GMM in general...I have some questions about the fit quality of Gaussian mixture models in python (scikit-learn). I have an array of data that you can find in DATA HERE to match a GMM of n=2 components . As a be

PyMC3 Gaussian Mixture Model

Anjum Sayed I've been following PyMC3's Gaussian Mixture Model example here: https://github.com/pymc-devs/pymc3/blob/master/pymc3/examples/gaussian_mixture_model.ipynb , and it works perfectly with artificial datasets . I've tried using real datasets, but I'm

Clustering images using a Gaussian mixture model

ninja I want to cluster a binary image using GMM (Gaussian Mixture Model) and also want to plot the cluster centroids on the binary image itself. I used this as a reference : http://in.mathworks.com/help/stats/gaussian-mixture-models.html Here is my initial co

Clustering images using a Gaussian mixture model

ninja I want to cluster a binary image using GMM (Gaussian Mixture Model) and also want to plot the cluster centroids on the binary image itself. I used this as a reference : http://in.mathworks.com/help/stats/gaussian-mixture-models.html Here is my initial co

Equivalent of Matlab "fit" of Gaussian mixture model in R?

Dentist_Not edible I have some time series data that looks like this: x <- c(0.5833, 0.95041, 1.722, 3.1928, 3.941, 5.1202, 6.2125, 5.8828, 4.3406, 5.1353, 3.8468, 4.233, 5.8468, 6.1872, 6.1245, 7.6262, 8.6887, 7.7549, 6.9805, 4.3217, 3.0347, 2.4026, 1.9317,

How to evaluate samples in a weighted Gaussian mixture model?

kind Lite: If I have a MoG model with n components, each component has its own weight w^n. I have a sample. I wish to calculate the probability of drawing samples from the MoG. I can easily evaluate individual Gaussians, but I don't know how to consider their

PyMC3 Gaussian Mixture Model

Anjum Sayed I've been following the Gaussian Mixture Model example for PyMC3 here: https://github.com/pymc-devs/pymc3/blob/master/pymc3/examples/gaussian_mixture_model.ipynb , and it works perfectly with the artificial dataset . I've tried using real datasets,

PyMC3 Gaussian Mixture Model

Anjum Sayed I've been following the Gaussian Mixture Model example for PyMC3 here: https://github.com/pymc-devs/pymc3/blob/master/pymc3/examples/gaussian_mixture_model.ipynb , and got it working perfectly with the artificial dataset . I've tried using real dat

PyMC3 Gaussian Mixture Model

Anjum Sayed I've been following the Gaussian Mixture Model example for PyMC3 here: https://github.com/pymc-devs/pymc3/blob/master/pymc3/examples/gaussian_mixture_model.ipynb , and got it working perfectly with the artificial dataset . I've tried using real dat

PyMC3 Gaussian Mixture Model

Anjum Sayed I've been following the Gaussian Mixture Model example for PyMC3 here: https://github.com/pymc-devs/pymc3/blob/master/pymc3/examples/gaussian_mixture_model.ipynb , and got it working perfectly with the artificial dataset . I've tried using real dat

PyMC3 Gaussian Mixture Model

Anjum Sayed I've been following the Gaussian Mixture Model example for PyMC3 here: https://github.com/pymc-devs/pymc3/blob/master/pymc3/examples/gaussian_mixture_model.ipynb , and got it working perfectly with the artificial dataset . I've tried using real dat

Gaussian mixture model - Matlab parameter training

Hillel I am running a speech enhancement algorithm based on Gaussian mixture model. The problem is that the estimation algorithm underflows during training. XI am trying to calculate the product of the PDF of each frequnecy component of the Gaussian cluster gi

Label new data with a trained Gaussian mixture model

only Jerome I'm not sure how to use a trained Gaussian Mixture Model (GMM) to make predictions on some new data. For example, I have some labeled data from 3 different classes (clusters). For each class of data points I fit a GMM (gm1, gm2 and gm3). Suppose we

Clustering images using a Gaussian mixture model

ninja I want to cluster a binary image using GMM (Gaussian Mixture Model) and also want to plot the cluster centroids on the binary image itself. I used this as a reference : http://in.mathworks.com/help/stats/gaussian-mixture-models.html Here is my initial co

Gaussian mixture model - Matlab parameter training

Hillel I am running a speech enhancement algorithm based on Gaussian mixture model. The problem is that the estimation algorithm underflows during training. XI am trying to calculate the product of the PDF of each frequnecy component of the Gaussian cluster gi

Get PDF from Gaussian Mixture Model in sklearn

learner I have fitted a Gaussian Mixture Model (GMM) to the data series I have. Using GMM, I am trying to get the probability of another vector, element-wise. Matlab achieves this with the following lines of code. a = reshape(0:1:15, 14, 1); gm = fitgmdist(a,

PyMC3 Gaussian Mixture Model

Anjum Sayed I've been following the Gaussian Mixture Model example for PyMC3 here: https://github.com/pymc-devs/pymc3/blob/master/pymc3/examples/gaussian_mixture_model.ipynb , and it works perfectly with the artificial dataset . I've tried using real datasets,