Simon Penn Simon Penn -4 years ago 231
Python Question

Detect different color blob opencv

I'm new to opencv and for a school project i need to detect a red and a green circle with a camera, so i've use blobdetection, but it detect me the two colors, i think that my mask is bad, each color is linked to a specific action.

At the moment my code detect well red and green circle on the same page but i want it to detect only red circle on a white page.

Thank for your help

# Standard imports
import cv2
import numpy as np;

# Read image
im = cv2.VideoCapture(0)

# Setup SimpleBlobDetector parameters.
params = cv2.SimpleBlobDetector_Params()

# Change thresholds
params.minThreshold = 100;
params.maxThreshold = 200;

# Filter by Area.
params.filterByArea = True
params.minArea = 200
params.maxArea = 20000

# Filter by Circularity
params.filterByCircularity = True
params.minCircularity = 0.1

# Filter by Convexity
params.filterByConvexity = True
params.minConvexity = 0.1

# Filter by Inertia
params.filterByInertia = True
params.minInertiaRatio = 0.1

blueLower = (0,85,170) #100,130,50
blueUpper = (140,110,255) #200,200,130


# resize the frame, blur it, and convert it to the HSV
# color space
#frame = imutils.resize(frame, width=600)
# blurred = cv2.GaussianBlur(frame, (11, 11), 0)


#hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)

mask = cv2.inRange(frame, blueLower, blueUpper)
mask = cv2.erode(mask, None, iterations=0)
mask = cv2.dilate(mask, None, iterations=0)
frame = cv2.bitwise_and(frame,frame,mask = mask)

# Set up the detector with default parameters.
detector = cv2.SimpleBlobDetector_create(params)

# Detect blobs.
keypoints = detector.detect(mask)

# Draw detected blobs as red circles.
# cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS ensures the size of the circle corresponds to the size of blob
im_with_keypoints = cv2.drawKeypoints(mask, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

# Display the resulting frame

frame = cv2.bitwise_and(frame,im_with_keypoints,mask = mask)


if cv2.waitKey(1) & 0xFF == ord('q'):

# When everything done, release the capture

EDIT 1: Code update

Now i got a issue where my full circle isn't detected.

No Blob Detection

Answer Source

You need to work out what the BGR numbers for your green are (let's say for arguments sake [0, 255, 0]), then create a mask that ignores any colours outside a tolerance around your green:

mask = cv2.inRange(image, lower, upper)

Play around with lower and upper to get the right behaviour. Then use cv2.bitwise_and(image, image, mask = mask) to combine with image.

Take a look at this tutorial for a step by step.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download