1from __future__ import print_function 2import cv2 as cv 3import numpy as np 4import argparse 5 6low = 20 7up = 20 8 9def callback_low(val): 10 global low 11 low = val 12 13def callback_up(val): 14 global up 15 up = val 16 17def pickPoint(event, x, y, flags, param): 18 if event != cv.EVENT_LBUTTONDOWN: 19 return 20 21 # Fill and get the mask 22 seed = (x, y) 23 newMaskVal = 255 24 newVal = (120, 120, 120) 25 connectivity = 8 26 flags = connectivity + (newMaskVal << 8 ) + cv.FLOODFILL_FIXED_RANGE + cv.FLOODFILL_MASK_ONLY 27 28 mask2 = np.zeros((src.shape[0] + 2, src.shape[1] + 2), dtype=np.uint8) 29 print('low:', low, 'up:', up) 30 cv.floodFill(src, mask2, seed, newVal, (low, low, low), (up, up, up), flags) 31 mask = mask2[1:-1,1:-1] 32 33 cv.imshow('Mask', mask) 34 Hist_and_Backproj(mask) 35 36def Hist_and_Backproj(mask): 37 h_bins = 30 38 s_bins = 32 39 histSize = [h_bins, s_bins] 40 h_range = [0, 180] 41 s_range = [0, 256] 42 ranges = h_range + s_range # Concat list 43 channels = [0, 1] 44 45 # Get the Histogram and normalize it 46 hist = cv.calcHist([hsv], channels, mask, histSize, ranges, accumulate=False) 47 cv.normalize(hist, hist, alpha=0, beta=255, norm_type=cv.NORM_MINMAX) 48 49 # Get Backprojection 50 backproj = cv.calcBackProject([hsv], channels, hist, ranges, scale=1) 51 52 # Draw the backproj 53 cv.imshow('BackProj', backproj) 54 55# Read the image 56parser = argparse.ArgumentParser(description='Code for Back Projection tutorial.') 57parser.add_argument('--input', help='Path to input image.', default='home.jpg') 58args = parser.parse_args() 59 60src = cv.imread(cv.samples.findFile(args.input)) 61if src is None: 62 print('Could not open or find the image:', args.input) 63 exit(0) 64 65# Transform it to HSV 66hsv = cv.cvtColor(src, cv.COLOR_BGR2HSV) 67 68# Show the image 69window_image = 'Source image' 70cv.namedWindow(window_image) 71cv.imshow(window_image, src) 72 73# Set Trackbars for floodfill thresholds 74cv.createTrackbar('Low thresh', window_image, low, 255, callback_low) 75cv.createTrackbar('High thresh', window_image, up, 255, callback_up) 76# Set a Mouse Callback 77cv.setMouseCallback(window_image, pickPoint) 78 79cv.waitKey() 80