Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
35 views

Lab05 Object Segmentation

This document contains code for image segmentation tasks including: 1. Functions for displaying images, filling holes in masks, applying morphological operations, resizing images, and segmenting images using k-means clustering. 2. A function to segment a color image based on a mask. 3. Functions for thresholding based on Otsu's method, labeling objects in an image mask, and selecting masks based on minimum and maximum area thresholds.

Uploaded by

Dũng Hi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Lab05 Object Segmentation

This document contains code for image segmentation tasks including: 1. Functions for displaying images, filling holes in masks, applying morphological operations, resizing images, and segmenting images using k-means clustering. 2. A function to segment a color image based on a mask. 3. Functions for thresholding based on Otsu's method, labeling objects in an image mask, and selecting masks based on minimum and maximum area thresholds.

Uploaded by

Dũng Hi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

7/20/2020 Lab05-Object Segmentation

LAB05 - Image Segmentation

Dr. Tran Anh Tuan,

Faculty of Mathematics and Computer Science,

University of Science, HCMC ¶


In [1]: import numpy as np
import cv2
from matplotlib import pyplot as plt
from skimage.color import rgb2gray
from skimage.filters import threshold_otsu
from skimage.measure import label, regionprops
from skimage.segmentation import mark_boundaries
from scipy import ndimage as ndi
import pandas as pd
import json
import os
import timeit
import random

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 1/27


7/20/2020 Lab05-Object Segmentation

In [2]: def ShowImage(ImageList, nRows = 1, nCols = 2, WidthSpace = 0.00, HeightSpace = 0.00):


from matplotlib import pyplot as plt
import matplotlib.gridspec as gridspec

gs = gridspec.GridSpec(nRows, nCols)
gs.update(wspace=WidthSpace, hspace=HeightSpace) # set the spacing between axes.
plt.figure(figsize=(20,20))
for i in range(len(ImageList)):
ax1 = plt.subplot(gs[i])
ax1.set_xticklabels([])
ax1.set_yticklabels([])
ax1.set_aspect('equal')

plt.subplot(nRows, nCols,i+1)

image = ImageList[i].copy()
if (len(image.shape) < 3):
plt.imshow(image, plt.cm.gray)
else:
plt.imshow(image)
plt.title("Image " + str(i))
plt.axis('off')

plt.show()

In [3]: def FillHoles(Mask):


Result = ndi.binary_fill_holes(Mask)
return Result

def morphology(Mask, Size):


from skimage.morphology import erosion, dilation, opening, closing, white_tophat
from skimage.morphology import disk
selem = disk(abs(Size))
if(Size > 0):
result = dilation(Mask, selem)
else:
result = erosion(Mask, selem)
return result

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 2/27


7/20/2020 Lab05-Object Segmentation

In [4]: import os
import pandas as pd

def get_subfiles(dir):
"Get a list of immediate subfiles"
return next(os.walk(dir))[2]

In [5]: def SegmentColorImageByMask(IM, Mask):


Mask = Mask.astype(np.uint8)
result = cv2.bitwise_and(IM, IM, mask = Mask)
return result

In [6]: def SegmentationByOtsu(image, mask):


image_process = image.copy()
image_mask = mask.copy()

image_process[image_mask == 0] = 0
ListPixel = image_process.ravel()
ListPixel = ListPixel[ListPixel > 0]

from skimage.filters import threshold_otsu


otsu_thresh = threshold_otsu(ListPixel)

return otsu_thresh

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 3/27


7/20/2020 Lab05-Object Segmentation

In [7]: def ResizeImage(IM, DesiredWidth, DesiredHeight):


from skimage.transform import rescale, resize

OrigWidth = float(IM.shape[1])
OrigHeight = float(IM.shape[0])
Width = DesiredWidth
Height = DesiredHeight

if((Width == 0) & (Height == 0)):


return IM

if(Width == 0):
Width = int((OrigWidth * Height)/OrigHeight)

if(Height == 0):
Height = int((OrigHeight * Width)/OrigWidth)

dim = (Width, Height)


# print(dim)
resizedIM = cv2.resize(IM, dim, interpolation = cv2.INTER_NEAREST)
# imshows([IM, resizedIM], ["Image", "resizedIM"],1,2)
return resizedIM

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 4/27


7/20/2020 Lab05-Object Segmentation

In [8]: def SegmentByKmeans(image_orig, nClusters = 3):


img = image_orig.copy()
Z = img.reshape((-1,3))

# convert to np.float32
Z = np.float32(Z)

# define criteria, number of clusters(K) and apply kmeans()


criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 1.0)
K = nClusters
ret,labellist,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)

# Now convert back into uint8, and make original image


center = np.uint8(center)
res = center[labellist.flatten()]
res2 = res.reshape((img.shape))
label2 = labellist.reshape((img.shape[:2]))

image_index = label2
image_kmeans = res2

# Sort to make sure the index is stable


AreaList = []
for idx in range(image_index.max() + 1):
mask = image_index == idx
AreaList.append(mask.sum().sum())

sort_index = np.argsort(AreaList)[::-1]
index = 0
image_index1 = image_index * 0
for idx in sort_index:
image_index1[image_index == idx] = index
index = index + 1

image_index = image_index1.copy()

return image_index, image_kmeans

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 5/27


7/20/2020 Lab05-Object Segmentation

In [9]: def LabelObjectByMask(image_input, image_mask, type = "BBox", color = (0,255,0), thick = 2):
# image_input = image_orig.copy()
image_output = image_input.copy()

label_img = label(image_mask)
regions = regionprops(label_img)
for props in regions:
minr, minc, maxr, maxc = props.bbox
left_top = (minc, minr)
right_bottom = (maxc, maxr)
at_row, at_col = props.centroid

if(type == "Center"):
cv2.drawMarker(image_output, (int(at_col), int(at_row)),color, markerType=cv2.MARKER_STAR, marker
Size=15, thickness= 1, line_type=cv2.LINE_AA)
if(type == "BBox"):
cv2.rectangle(image_output,left_top, right_bottom, color ,thick)

if(type == "Boundary"):
color = [(number / 255) for number in color]
image_mask = morphology(image_mask, 1)
image_output = mark_boundaries(image_output, image_mask, color = color, mode='thick')

if(type == "Fill"):
image_output[image_mask > 0] = color

return image_output

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 6/27


7/20/2020 Lab05-Object Segmentation

In [10]: def SelectMaskByThreshArea(Mask, minArea = 300, maxArea = 100000):


import pandas as pd
from skimage.measure import label, regionprops

mask = Mask.copy()
mask_output = mask * 0
bboxList = []

label_img = label(mask)
regions = regionprops(label_img)
for props in regions:
area = props.area
label = props.label
if((area > minArea) and (area < maxArea)):
mask_output = mask_output + (label_img == label).astype(int)

return mask_output

Graph-Based Segmentation

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 7/27


7/20/2020 Lab05-Object Segmentation

In [12]: class Node:


def __init__(self, parent, rank=0, size=1):
self.parent = parent
self.rank = rank
self.size = size

def __repr__(self):
return '(parent=%s, rank=%s, size=%s)' % (self.parent, self.rank, self.size)

class Forest:
def __init__(self, num_nodes):
self.nodes = [Node(i) for i in range(num_nodes)]
self.num_sets = num_nodes

def size_of(self, i):


return self.nodes[i].size

def find(self, n):


temp = n
while temp != self.nodes[temp].parent:
temp = self.nodes[temp].parent

self.nodes[n].parent = temp
return temp

def merge(self, a, b):


if self.nodes[a].rank > self.nodes[b].rank:
self.nodes[b].parent = a
self.nodes[a].size = self.nodes[a].size + self.nodes[b].size
else:
self.nodes[a].parent = b
self.nodes[b].size = self.nodes[b].size + self.nodes[a].size

if self.nodes[a].rank == self.nodes[b].rank:
self.nodes[b].rank = self.nodes[b].rank + 1

self.num_sets = self.num_sets - 1

def print_nodes(self):
for node in self.nodes:
print(node)

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 8/27


7/20/2020 Lab05-Object Segmentation

def create_edge(img, width, x, y, x1, y1, diff):


vertex_id = lambda x, y: y * width + x
w = diff(img, x, y, x1, y1)
return (vertex_id(x, y), vertex_id(x1, y1), w)

def build_graph(img, width, height, diff, neighborhood_8=False):


graph_edges = []
for y in range(height):
for x in range(width):
if x > 0:
graph_edges.append(create_edge(img, width, x, y, x-1, y, diff))

if y > 0:
graph_edges.append(create_edge(img, width, x, y, x, y-1, diff))

if neighborhood_8:
if x > 0 and y > 0:
graph_edges.append(create_edge(img, width, x, y, x-1, y-1, diff))

if x > 0 and y < height-1:


graph_edges.append(create_edge(img, width, x, y, x-1, y+1, diff))

return graph_edges

def remove_small_components(forest, graph, min_size):


for edge in graph:
a = forest.find(edge[0])
b = forest.find(edge[1])

if a != b and (forest.size_of(a) < min_size or forest.size_of(b) < min_size):


forest.merge(a, b)

return forest

def segment_graph(graph_edges, num_nodes, const, min_size, threshold_func):


# Step 1: initialization
forest = Forest(num_nodes)
weight = lambda edge: edge[2]
sorted_graph = sorted(graph_edges, key=weight)
threshold = [ threshold_func(1, const) for _ in range(num_nodes) ]

# Step 2: merging
for edge in sorted_graph:
file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 9/27
7/20/2020 Lab05-Object Segmentation

parent_a = forest.find(edge[0])
parent_b = forest.find(edge[1])
a_condition = weight(edge) <= threshold[parent_a]
b_condition = weight(edge) <= threshold[parent_b]

if parent_a != parent_b and a_condition and b_condition:


forest.merge(parent_a, parent_b)
a = forest.find(parent_a)
threshold[a] = weight(edge) + threshold_func(forest.nodes[a].size, const)

return remove_small_components(forest, sorted_graph, min_size)

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 10/27


7/20/2020 Lab05-Object Segmentation

In [110]: import argparse


import logging
import time
from random import random
from PIL import Image, ImageFilter
from skimage import io
import numpy as np

def diff(img, x1, y1, x2, y2):


_out = np.sum((img[x1, y1] - img[x2, y2]) ** 2)
return np.sqrt(_out)

def threshold(size, const):


return (const * 1.0 / size)

def generate_image(forest, width, height):


random_color = lambda: (int(random()*255), int(random()*255), int(random()*255))
colors = [random_color() for i in range(width*height)]

img = Image.new('RGB', (width, height))


im = img.load()
for y in range(height):
for x in range(width):
comp = forest.find(y * width + x)
im[x, y] = colors[comp]

return img.transpose(Image.ROTATE_270).transpose(Image.FLIP_LEFT_RIGHT)

def GraphBasedSegmentation(input_image, sigma = 1, neighbor = 8, K = 20, min_comp_size = 2000):


start_time = time.time()
input_image = Image.fromarray(input_image)
size = input_image.size # (width, height) in Pillow/PIL

# Gaussian Filter
smooth = input_image.filter(ImageFilter.GaussianBlur(sigma))
smooth = np.array(smooth)
graph_edges = build_graph(smooth, size[1], size[0], diff, neighbor==8)
forest = segment_graph(graph_edges, size[0]*size[1], K, min_comp_size, threshold)

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 11/27


7/20/2020 Lab05-Object Segmentation

image = generate_image(forest, size[1], size[0])


output_image = np.asarray(image)
return output_image

In [101]: def ConvertGrayToIndex(image_gray):


PixelList = list(np.unique(image_gray.flatten()))

random_color = lambda: (int(random()*255), int(random()*255), int(random()*255))


colors = [random_color() for i in range(len(PixelList))]

image_index = image_gray.copy()
for idx, value in enumerate(PixelList):
image_index = np.where(image_index==PixelList[idx], -(idx + 1), image_index)
image_index = -image_index

image_color = np.dstack((image_gray,image_gray,image_gray))
rows, cols = image_color.shape[:2]
for x in range(rows):
for y in range(cols):
index = PixelList.index(image_gray[x,y])
image_color[x, y, :] = colors[index]

# Sort to make sure the index is stable


AreaList = []
for idx in range(image_index.max() + 1):
mask = image_index == idx
AreaList.append(mask.sum().sum())

sort_index = np.argsort(AreaList)[::-1]
index = 0
image_index1 = image_index * 0
for idx in sort_index:
image_index1[image_index == idx] = index
index = index + 1
image_index = image_index1.copy()

return image_index, image_color

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 12/27


7/20/2020 Lab05-Object Segmentation

In [273]: DataPath = "D:\\MSI DATA (Previous Computer)\\Teaching And Training\\Image Segmentation\\Image Segmentation D
ataSet1\\"

path = DataPath
all_names = get_subfiles(path)
print("Number of Images:", len(all_names))
IMG = []
for i in range(len(all_names)):
tmp = cv2.imread(path + all_names[i])
IMG.append(tmp)

SegDataIMG1 = IMG.copy()
SegDataName1 = all_names

Number of Images: 45

In [276]: DataPath = "D:\\MSI DATA (Previous Computer)\\Teaching And Training\\Image Segmentation\\Image Segnemtation D
ataSet\\"

path = DataPath
all_names = get_subfiles(path)
print("Number of Images:", len(all_names))
IMG = []
for i in range(len(all_names)):
tmp = cv2.imread(path + all_names[i])
IMG.append(tmp)

SegDataIMG = IMG.copy()
SegDataName = all_names

Number of Images: 60

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 13/27


7/20/2020 Lab05-Object Segmentation

In [124]: FileName = 'Mask 01.jpg'


idx = SegDataName1.index(FileName)
print("Selected Image : ", "\nIndex ", idx, "\nName ", SegDataName1[idx])

image = SegDataIMG1[idx]
image = ResizeImage(image, DesiredWidth = 300, DesiredHeight = 0)

image_orig = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)


image_gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
image_ycbcr = cv2.cvtColor(image, cv2.COLOR_BGR2YCR_CB)
ShowImage([image_orig, image_gray, image_hsv, image_ycbcr], 1, 4)

Selected Image :
Index 25
Name Mask 01.jpg

In [111]: output_segment_rgb = GraphBasedSegmentation(image_orig)

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 14/27


7/20/2020 Lab05-Object Segmentation

In [112]: image_gray = image_gray = cv2.cvtColor(output_segment_rgb,cv2.COLOR_BGR2GRAY)


image_index, image_color = ConvertGrayToIndex(image_gray)
ShowImage([image_orig, image_index, image_color], 1, 3)

WaterShed Segmentation

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 15/27


7/20/2020 Lab05-Object Segmentation

In [155]: FileName = 'Skin 05.jpg'


idx = SegDataName.index(FileName)
print("Selected Image : ", "\nIndex ", idx, "\nName ", SegDataName[idx])

image = SegDataIMG[idx]
image = ResizeImage(image, DesiredWidth = 300, DesiredHeight = 0)

image_orig = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)


image_gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
image_ycbcr = cv2.cvtColor(image, cv2.COLOR_BGR2YCR_CB)
ShowImage([image_orig, image_gray, image_hsv, image_ycbcr], 1, 4)

Selected Image :
Index 59
Name Skin 05.jpg

In [181]: img = image_orig.copy()


gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
thresh = (gray < 150).astype(np.uint8)
ShowImage([thresh], 1, 5)

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 16/27


7/20/2020 Lab05-Object Segmentation

In [182]: # noise removal


kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)

# sure background area


sure_bg = cv2.dilate(opening,kernel,iterations=3)

ShowImage([thresh, sure_bg], 1, 5)

# Finding sure foreground area


dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5)
ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)

# Finding unknown region


sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg,sure_fg)

ShowImage([dist_transform, sure_fg, unknown], 1, 5)

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 17/27


7/20/2020 Lab05-Object Segmentation

In [183]: # Marker labelling


ret, markers = cv2.connectedComponents(sure_fg)
# Add one to all labels so that sure background is not 0, but 1
markers = markers+1
# Now, mark the region of unknown with zero
markers[unknown==255] = 0
_, image_color = ConvertGrayToIndex(markers)
ShowImage([markers, image_color], 1, 5)

In [184]: markers = cv2.watershed(img,markers)


_, image_color = ConvertGrayToIndex(markers)
img[markers == -1] = [255,0,0]

ShowImage([img, markers, image_color], 1, 5)

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 18/27


7/20/2020 Lab05-Object Segmentation

In [185]: def WaterShedSegmentation(image_rgb, init_mask):


image_gray = cv2.cvtColor(image_rgb,cv2.COLOR_BGR2GRAY)
thresh = init_mask.copy()

# noise removal
kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)

# sure background area


sure_bg = cv2.dilate(opening,kernel,iterations=3)

# Finding sure foreground area


dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5)
ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)

# Finding unknown region


sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg,sure_fg)

# Marker labelling
ret, markers = cv2.connectedComponents(sure_fg)
# Add one to all labels so that sure background is not 0, but 1
markers = markers+1
# Now, mark the region of unknown with zero
markers[unknown==255] = 0

image_index = markers.copy()
image_dist = dist_transform.copy()

return segment_mask, image_dist

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 19/27


7/20/2020 Lab05-Object Segmentation

In [201]: image_rgb = image_orig.copy()


image_gray = cv2.cvtColor(image_rgb,cv2.COLOR_BGR2GRAY)
init_mask = (image_gray < 150).astype(np.uint8)

segment_mask, image_dist = WaterShedSegmentation(image_rgb, init_mask)


ShowImage([image_rgb, init_mask, segment_mask, image_dist], 1, 4)

image_index = init_mask.copy()
image_index[segment_mask == segment_mask.max()] = image_index.max() + 1
_, image_color = ConvertGrayToIndex(image_index)

ShowImage([image_index, image_color], 1, 3)

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 20/27


7/20/2020 Lab05-Object Segmentation

In [217]: image_dist = image_dist.astype(np.uint8)


_, image_color = ConvertGrayToIndex(image_dist)
ShowImage([image_dist, image_color], 1, 3)
ShowImage([image_dist > 5,image_dist > 10, image_dist > 15, image_dist > 20], 1, 4)

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 21/27


7/20/2020 Lab05-Object Segmentation

In [265]: DataPath = "D:\\MSI DATA (Previous Computer)\\Teaching And Training\\Image Segmentation\\Image Segmentation D
ataSet2\\Cell1\\"

path = DataPath
all_names = get_subfiles(path)
print("Number of Images:", len(all_names))
IMG = []
for i in range(len(all_names)):
tmp = cv2.imread(path + all_names[i])
IMG.append(tmp)

SegDataIMG2 = IMG.copy()
SegDataName2 = all_names

Number of Images: 52

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 22/27


7/20/2020 Lab05-Object Segmentation

In [266]: FileName = 'cluster2.bmp.jpg'


idx = SegDataName2.index(FileName)
print("Selected Image : ", "\nIndex ", idx, "\nName ", SegDataName2[idx])

image = SegDataIMG2[idx]
image = ResizeImage(image, DesiredWidth = 300, DesiredHeight = 0)

image_orig = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)


image_gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
image_ycbcr = cv2.cvtColor(image, cv2.COLOR_BGR2YCR_CB)
ShowImage([image_orig, image_gray, image_hsv, image_ycbcr], 1, 4)

Selected Image :
Index 11
Name cluster2.bmp.jpg

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 23/27


7/20/2020 Lab05-Object Segmentation

In [271]: image_rgb = image_orig.copy()


image_gray = cv2.cvtColor(image_rgb,cv2.COLOR_BGR2GRAY)
init_mask = (image_gray < 140)
init_mask = FillHoles(init_mask)
init_mask = init_mask.astype(np.uint8)

segment_mask, image_dist = WaterShedSegmentation(image_rgb, init_mask)


ShowImage([image_rgb, init_mask, segment_mask, image_dist], 1, 4)

image_dist = image_dist.astype(np.uint8)
_, image_color = ConvertGrayToIndex(image_dist)
ShowImage([image_dist, image_color, image_dist > 5,image_dist > 10], 1, 4)

Superpixel
file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 24/27
7/20/2020 Lab05-Object Segmentation

In [277]: FileName = 'DrivingPlate 05.jpg'


idx = SegDataName.index(FileName)
print("Selected Image : ", "\nIndex ", idx, "\nName ", SegDataName[idx])

image = SegDataIMG[idx]
image = ResizeImage(image, DesiredWidth = 300, DesiredHeight = 0)

image_orig = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)


image_gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
image_ycbcr = cv2.cvtColor(image, cv2.COLOR_BGR2YCR_CB)
ShowImage([image_orig, image_gray, image_hsv, image_ycbcr], 1, 4)

Selected Image :
Index 14
Name DrivingPlate 05.jpg

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 25/27


7/20/2020 Lab05-Object Segmentation

In [283]: # import the necessary packages


from skimage.segmentation import slic
from skimage.segmentation import mark_boundaries
from skimage.util import img_as_float
from skimage import io
import matplotlib.pyplot as plt

# load the image and convert it to a floating point data type


image = img_as_float(image_orig)
# loop over the number of segments
SegmentIndexList = []
SegmentColorList = []
for numSegments in (300, 400, 500):
# apply SLIC and extract (approximately) the supplied number
# of segments
segments = slic(image, n_segments = numSegments, sigma = 5)
SegmentIndexList.append(segments)
image_color = mark_boundaries(image, segments)
SegmentColorList.append(image_color)

ShowImage(SegmentIndexList, 1, 3)
ShowImage(SegmentColorList, 1, 3)

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 26/27


7/20/2020 Lab05-Object Segmentation

file:///D:/MSI DATA (Previous Computer)/Teaching And Training/Image Segmentation/Lab05-Object Segmentation.html 27/27

You might also like