seeds.py 2.35 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
#!/usr/bin/env python

'''
This sample demonstrates SEEDS Superpixels segmentation
Use [space] to toggle output mode

Usage:
  seeds.py [<video source>]

'''

import numpy as np
13
import cv2 as cv
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

# relative module
import video

# built-in module
import sys


if __name__ == '__main__':
    print __doc__

    try:
        fn = sys.argv[1]
    except:
        fn = 0

    def nothing(*arg):
        pass

33 34 35
    cv.namedWindow('SEEDS')
    cv.createTrackbar('Number of Superpixels', 'SEEDS', 400, 1000, nothing)
    cv.createTrackbar('Iterations', 'SEEDS', 4, 12, nothing)
36 37 38 39 40 41 42 43 44 45 46

    seeds = None
    display_mode = 0
    num_superpixels = 400
    prior = 2
    num_levels = 4
    num_histogram_bins = 5

    cap = video.create_capture(fn)
    while True:
        flag, img = cap.read()
47
        converted_img = cv.cvtColor(img, cv.COLOR_BGR2HSV)
48
        height,width,channels = converted_img.shape
49 50
        num_superpixels_new = cv.getTrackbarPos('Number of Superpixels', 'SEEDS')
        num_iterations = cv.getTrackbarPos('Iterations', 'SEEDS')
51 52 53

        if not seeds or num_superpixels_new != num_superpixels:
            num_superpixels = num_superpixels_new
54
            seeds = cv.ximgproc.createSuperpixelSEEDS(width, height, channels,
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
                    num_superpixels, num_levels, prior, num_histogram_bins)
            color_img = np.zeros((height,width,3), np.uint8)
            color_img[:] = (0, 0, 255)

        seeds.iterate(converted_img, num_iterations)

        # retrieve the segmentation result
        labels = seeds.getLabels()


        # labels output: use the last x bits to determine the color
        num_label_bits = 2
        labels &= (1<<num_label_bits)-1
        labels *= 1<<(16-num_label_bits)


        mask = seeds.getLabelContourMask(False)

        # stitch foreground & background together
74 75 76 77
        mask_inv = cv.bitwise_not(mask)
        result_bg = cv.bitwise_and(img, img, mask=mask_inv)
        result_fg = cv.bitwise_and(color_img, color_img, mask=mask)
        result = cv.add(result_bg, result_fg)
78 79

        if display_mode == 0:
80
            cv.imshow('SEEDS', result)
81
        elif display_mode == 1:
82
            cv.imshow('SEEDS', mask)
83
        else:
84
            cv.imshow('SEEDS', labels)
85

86
        ch = cv.waitKey(1)
87 88 89 90
        if ch == 27:
            break
        elif ch & 0xff == ord(' '):
            display_mode = (display_mode + 1) % 3
91
    cv.destroyAllWindows()