SuperPixel 的样例代码

总说

这个给自己看的,对读者应该没啥用。。
超像素的例子

import sys
import os
import cv2
import numpy as np
import math

img = cv2.imread('people.png')

#------------- SP Generation -------------------------
num_superpixels = 50  # 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 = img.shape



converted_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
t_h, t_w, t_c = converted_img.shape
seeds = cv2.ximgproc.createSuperpixelSEEDS(t_w, t_h, t_c, num_superpixels, num_levels, prior, num_histogram_bins)
seeds.iterate(converted_img, num_iterations)
num_of_superpixels_result = seeds.getNumberOfSuperpixels()
print('Final number of superpixels: %d' % num_of_superpixels_result)

# draw contour
mask = seeds.getLabelContourMask(False)
cv2.imwrite('mask.png', mask)
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.imwrite('result.png', result)
cv2.imshow('ColorCodedWindow', result)
cv2.waitKey(0)


cv2.destroyAllWindows()

你可能感兴趣的:(SuperPixel 的样例代码)