我正在尝试在sklearn中使用Ward方法来分割彩色图像。我一直在使用sklearn示例来分割灰度图像(http://scikit-learn.org/stable/auto_examples/cluster/plot_lena_ward_segmentation.html#example-cluster-plot-lena-ward-segmentation-py),但我似乎无法使用颜色。
以下是代码:
from PIL import Image
import numpy as np
from sklearn.feature_extraction.image import grid_to_graph
from sklearn.cluster import Ward
img = Image.open("test.jpg")
img = np.array(img)
X = img.reshape((-1, 3))
x, y, z = img.shape
connectivity = grid_to_graph(n_x=x, n_y=y, n_z=z)
ward = Ward(n_clusters=5, connectivity=connectivity).fit(X)
我得到的错误:
Traceback (most recent call last):
File "<pyshell#421>", line 1, in <module>
ward = Ward(n_clusters=5, connectivity=connectivity).fit(X)
File "C:\Python27\lib\site-packages\sklearn\cluster\hierarchical.py", line 370, in fit
raise ValueError("`connectivity` does not have shape "
ValueError: `connectivity` does not have shape (n_samples, n_samples)
我尝试过其他一些东西,但似乎没什么用。谢谢!
更新
我可以发誓我之前尝试过这个,但显然在调用grid_to_graph时省略了n_z参数解决了这个问题:
connectivity = grid_to_graph(n_x=x, n_y=y)
ward = Ward(n_clusters=5, connectivity=connectivity).fit(X)
如果有人能够证实或否认这仍然是我正在努力完成的事情,那就太棒了!