In the previous blogs, we discussed various thresholding methods such as Otsu, adaptive, BHT, etc. In this blog, we will learn how to segment out a particular region or color from an image. This is naively equivalent to multiple thresholding where we assign a particular value to the region falling in between the two thresholds. Remaining region is assigned a different value. OpenCV provides an inbuilt function for this as shown below
1 |
cv2.inRange(src, lowerb, upperb) |
Here, src is the input image. ‘lowerb’ and ‘upperb’ denotes the lower and upper boundary of the threshold region. A pixel is set to 255 if it lies within the boundaries specified otherwise set to 0. This way it returns the thresholded image.
A nice way to understand any method is to play with the arguments and for that, trackbars come very handily. Let’s segment the image based on the color as any color (and its shades) mostly covers some range of intensity values. Thus for segmentation any color this function will be very useful. Below is the code where I have created trackbars to segment any color in a live webcam feed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
import cv2 import numpy as np def nothing(x): pass # Open the camera cap = cv2.VideoCapture(0) # Create a window cv2.namedWindow('image') # create trackbars for color change cv2.createTrackbar('lowH','image',0,179,nothing) cv2.createTrackbar('highH','image',179,179,nothing) cv2.createTrackbar('lowS','image',0,255,nothing) cv2.createTrackbar('highS','image',255,255,nothing) cv2.createTrackbar('lowV','image',0,255,nothing) cv2.createTrackbar('highV','image',255,255,nothing) while(True): ret, frame = cap.read() # get current positions of the trackbars ilowH = cv2.getTrackbarPos('lowH', 'image') ihighH = cv2.getTrackbarPos('highH', 'image') ilowS = cv2.getTrackbarPos('lowS', 'image') ihighS = cv2.getTrackbarPos('highS', 'image') ilowV = cv2.getTrackbarPos('lowV', 'image') ihighV = cv2.getTrackbarPos('highV', 'image') # convert color to hsv because it is easy to track colors in this color model hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) lower_hsv = np.array([ilowH, ilowS, ilowV]) higher_hsv = np.array([ihighH, ihighS, ihighV]) # Apply the cv2.inrange method to create a mask mask = cv2.inRange(hsv, lower_hsv, higher_hsv) # Apply the mask on the image to extract the original color frame = cv2.bitwise_and(frame, frame, mask=mask) cv2.imshow('image', frame) # Press q to exit if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() |
Play around with the trackbars to get a feel of cv2.inRange function. Hope you enjoy reading.
If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.