반응형
** Opencv에서 제공하는 superpixel segmentation algorithm, SEEDS 사용법 **
Background: Ubuntu16.04LTS + Anaconda3 + Python3.6 + Opencv3.x
The algorithm SEEDS (which is originated by MV Bergh et al, 'SEEDS: Superpixels Extracted vis Energy-Driven Sampling') is a built-in function for image superpixel segmentation.
// CODES //////////////////////////////
import cv2
import numpy as np
# image path
dir = '/home/dooseop/PycharmProjects/Proj04/test_images/test4.bmp'
# image read
img = cv2.imread(dir) # BRG order, uint8 type
cv2.imshow('ImageWindow', img)
cv2.waitKey(0)
# convert color space
converted_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# set parameters for superpixel segmentation
num_superpixels = 400 # desired number of superpixels
num_iterations = 4 # number of pixel level iterations. The higher, the better quality
prior = 2 # for shape smoothing term. must be [0, 5]
num_levels = 4
num_histogram_bins = 5 # number of histogram bins
height, width, channels = converted_img.shape
# initialize SEEDS algorithm
seeds = cv2.ximgproc.createSuperpixelSEEDS(width, height, channels, num_superpixels, num_levels, prior, num_histogram_bins)
# run SEEDS
seeds.iterate(converted_img, num_iterations)
# get number of superpixel
num_of_superpixels_result = seeds.getNumberOfSuperpixels()
print('Final number of superpixels: %d' % num_of_superpixels_result)
# retrieve the segmentation result
labels = seeds.getLabels() # height x width matrix. Each component indicates the superpixel index of the corresponding pixel position
# draw contour
mask = seeds.getLabelContourMask(False)
cv2.imshow('MaskWindow', mask)
cv2.waitKey(0)
# draw color coded image
color_img = np.zeros((height, width, 3), np.uint8)
color_img[:] = (0, 0, 255)
mask_inv = cv2.bitwise_not(mask)
result_bg = cv2.bitwise_and(img, img, mask=mask_inv)
result_fg = cv2.bitwise_and(color_img, color_img, mask=mask)
result = cv2.add(result_bg, result_fg)
cv2.imshow('ColorCodedWindow', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
The final results are
'Opencv' 카테고리의 다른 글
how to read/save an image as bmp in python (0) | 2017.08.11 |
---|---|
how to put text message on images using opencv library on C (0) | 2017.08.10 |
how to put text message on images using opencv library on python (0) | 2017.07.27 |
[opencv] how to install opencv on ubuntu (0) | 2017.07.18 |
[opencv] how to install opencv for python under anaconda+window10 (0) | 2017.07.18 |