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.
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 đồ?
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.
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]
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.
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