使用DBSCAN

时间:2016-10-19 22:57:55

标签: opencv scikit-learn image-segmentation vision dbscan

我正在尝试使用scikitlearn的DBSCAN来根据颜色分割图像。我得到的结果是plot of image。如您所见,有3个集群。我的目标是将图片中的浮标分成不同的簇。但显然它们显示为同一个集群。我尝试了各种各样的eps值和min_samples,但这两件事总是聚集在一起。我的代码是:

img= cv2.imread("buoy1.jpg) 
labimg = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)

n = 0
while(n<4):
    labimg = cv2.pyrDown(labimg)
    n = n+1

feature_image=np.reshape(labimg, [-1, 3])
rows, cols, chs = labimg.shape

db = DBSCAN(eps=5, min_samples=50, metric = 'euclidean',algorithm ='auto')
db.fit(feature_image)
labels = db.labels_

plt.figure(2)
plt.subplot(2, 1, 1)
plt.imshow(img)
plt.axis('off')
plt.subplot(2, 1, 2)
plt.imshow(np.reshape(labels, [rows, cols]))
plt.axis('off')
plt.show()

我认为这是采取欧氏距离,因为它在实验室空间中欧几里德距离在不同颜色之间会有所不同。如果有人能给我这方面的指导,我真的很感激。

更新: 以下答案有效。由于DBSCAN需要一个不超过2维的数组,我将列连接到原始图像并重新整形以生成n x 5矩阵,其中n是x维度乘以y维度。这似乎对我有用。

indices = np.dstack(np.indices(img.shape[:2]))
xycolors = np.concatenate((img, indices), axis=-1) 
np.reshape(xycolors, [-1,5])

2 个答案:

答案 0 :(得分:3)

您需要使用两种颜色和位置

目前,您只使用颜色。

答案 1 :(得分:0)

  

能否在答案中添加enitre码?我无法理解我该在哪里添加对您有用的那三行– user8306074 9月4日8:58

让我为您解答,这是代码的完整版本:

import numpy as np
import cv2
import matplotlib.pyplot as plt
from sklearn.cluster import DBSCAN

img= cv2.imread('your image') 
labimg = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)

n = 0
while(n<4):
    labimg = cv2.pyrDown(labimg)
    n = n+1

feature_image=np.reshape(labimg, [-1, 3])
rows, cols, chs = labimg.shape

db = DBSCAN(eps=5, min_samples=50, metric = 'euclidean',algorithm ='auto')
db.fit(feature_image)
labels = db.labels_

indices = np.dstack(np.indices(labimg.shape[:2]))
xycolors = np.concatenate((labimg, indices), axis=-1) 
feature_image2 = np.reshape(xycolors, [-1,5])
db.fit(feature_image2)
labels2 = db.labels_

plt.figure(2)
plt.subplot(2, 1, 1)
plt.imshow(img)
plt.axis('off')

# plt.subplot(2, 1, 2)
# plt.imshow(np.reshape(labels, [rows, cols]))
# plt.axis('off')

plt.subplot(2, 1, 2)
plt.imshow(np.reshape(labels2, [rows, cols]))
plt.axis('off')
plt.show()