【发布时间】:2016-08-30 19:14:38
【问题描述】:
我目前开始从事一个对图像类别进行分类的研究项目。研究的第一部分是使用随机森林算法进行图像分割。我在用这种算法分割图像时遇到了巨大的困难。有人可以帮助我了解如何使用 随机森林 算法使用 Python 分割图像吗?
我已经尝试过使用 K-means 聚类。但我需要随机森林的方式来做到这一点。
import time
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction import image
from sklearn.cluster import spectral_clustering
from sklearn.utils.testing import SkipTest
from sklearn.utils.fixes import sp_version
if sp_version < (0, 12):
raise SkipTest("Skipping because SciPy version earlier than 0.12.0 and "
"thus does not include the scipy.misc.face() image.")
# load the raccoon face as a numpy array
try:
face = sp.face(gray=True)
except AttributeError:
# Newer versions of scipy have face in misc
from scipy import misc
face = misc.face(gray=True)
# Resize it to 10% of the original size to speed up the processing
face = sp.misc.imresize(face, 0.10) / 255.
rm = RandomForestClassifier
# Convert the image into a graph with the value of the gradient on the
# edges.
graph = image.img_to_graph(face)
# Take a decreasing function of the gradient: an exponential
# The smaller beta is, the more independent the segmentation is of the
# actual image. For beta=1, the segmentation is close to a voronoi
beta = 5
eps = 1e-6
graph.data = np.exp(-beta * graph.data / graph.data.std()) + eps
# Apply spectral clustering (this step goes much faster if you have pyamg
# installed)
N_REGIONS = 25
#############################################################################
# Visualize the resulting regions
for assign_labels in ('kmeans', 'discretize'):
t0 = time.time()
labels = spectral_clustering(graph, n_clusters=N_REGIONS,
assign_labels=assign_labels, random_state=1)
t1 = time.time()
labels = labels.reshape(face.shape)
plt.figure(figsize=(5, 5))
plt.imshow(face, cmap=plt.cm.gray)
for l in range(N_REGIONS):
plt.contour(labels == l, contours=1,
colors=[plt.cm.spectral(l / float(N_REGIONS))])
plt.xticks(())
plt.yticks(())
title = 'Spectral clustering: %s, %.2fs' % (assign_labels, (t1 - t0))
print(title)
plt.title(title)
plt.show()
【问题讨论】:
-
欢迎来到 Stackoverflow Lasitha,请添加更多详细信息,说明您迄今为止所尝试的内容?
-
@iratzhash 我已经尝试过使用 k-means 聚类。但我需要使用带有随机森林算法的 Python 分割图像。
-
K-means 是无监督的,而 RFs 是有监督的(分类/回归)——你有针对这个问题的一组标记数据吗?如果没有,我认为不可能使用 RF。
-
@user1669710 不,我没有标记数据集。我是这方面的初学者。我只需要知道有没有一种方法可以用 RF 分割图像。
-
在这种情况下,您不能使用 RF。
标签: python algorithm random-forest image-segmentation