Experiments with some traditional segmentation methods. Outline:
- DBSCAN
- K-mean
- Meanshift
- Graphcut
- Watershed
Segmentation by DBSCAN¶
import cv2
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import DBSCAN
img = cv2.imread('images/lane.jpg')
Z = np.float32(img.reshape((-1,3)))
db = DBSCAN(eps=0.3, min_samples=100).fit(Z[:,:2])
plt.imshow(np.uint8(db.labels_.reshape(img.shape[:2])))
plt.show()
Segmentation by K-mean¶
import cv2
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import DBSCAN
img = cv2.imread('images/lane.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
Z = np.float32(img.reshape((-1,3)))
# Define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
ret, label, center = cv2.kmeans(Z, 5, None, criteria, 6, cv2.KMEANS_RANDOM_CENTERS)
# Now convert back into uint8, and make the original image
center = np.uint8(center)
res = center[label.flatten()]
res2 = np.uint8(label.reshape(img.shape[:2]))
res2.shape
plt.imshow(res2)
plt.show()
Segmentation by Meanshift¶
import cv2
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import MeanShift, estimate_bandwidth
from sklearn.datasets.samples_generator import make_blobs
img = cv2.imread('images/lane.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
Z = np.float32(img.reshape((-1,3)))
img = cv2.pyrMeanShiftFiltering(img, 20, 30, 2)
img = cv2.cvtColor(img, cv2.COLOR_HSV2RGB)
plt.imshow(img)
plt.show()
Segmentation by Graphcut¶
from skimage import data, segmentation, color
from skimage.future import graph
from matplotlib import pyplot as plt
img = cv2.imread('images/lane.jpg')
labels1 = segmentation.slic(img, compactness=1, n_segments=40)
out1 = color.label2rgb(labels1, img, kind='avg')
g = graph.rag_mean_color(img, labels1, mode='similarity')
labels2 = graph.cut_normalized(labels1, g)
out2 = color.label2rgb(labels2, img, kind='avg')
fig, ax = plt.subplots(nrows=1, sharex=True, sharey=True, figsize=(6, 8))
ax.imshow(out1)
ax.axis('off')
plt.show()
Segmentation by Watershed¶
from skimage.segmentation import quickshift as qs
from skimage import data, segmentation, color
from skimage.future import graph
from matplotlib import pyplot as plt
img = cv2.imread('images/lane.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = qs(img, convert2lab=True)
plt.imshow(img)
plt.show()
comments powered by Disqus