I have a color detection code using the Pi Camera and OpenCV. I need help with W
ID: 3867793 • Letter: I
Question
I have a color detection code using the Pi Camera and OpenCV. I need help with WHILE and ELSE or IF and ELSE statements in the code on recognizing a particular color. I want to know how to write the statement that results in a reaction after the code is detected. Part of the code is below;
#thresh = cv2.inRange(hsv,np.array((0, 200, 200)), np.array((20, 255, 255)))
lower = np.array([4,10,120],dtype="uint8")
upper = np.array([90,100,255], dtype="uint8")
thresh = cv2.inRange(blur, lower, upper)
thresh2 = thresh.copy()
# find contours in the threshold image
image, contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
# finding contour with maximum area and store it as best_cnt
max_area = 0
best_cnt = 1
for cnt in contours:
area = cv2.contourArea(cnt)
if area > max_area:
max_area = area
best_cnt = cnt
# finding centroids of best_cnt and draw a circle there
M = cv2.moments(best_cnt)
cx,cy = int(M['m10']/M['m00']), int(M['m01']/M['m00'])
#if best_cnt>1:
cv2.circle(blur,(cx,cy),10,(100,100,255),-1)
cv2.putText(blur, "Red Detected", (cx - 20, cy - 20),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
# show the frame
cv2.imshow("Frame", blur)
#cv2.imshow('thresh',thresh2)
key = cv2.waitKey(1) & 0xFF
# clear the stream in preparation for the next frame
rawCapture.truncate(0)
*while (thresh = cv2.inRange(blur, lower, upper)):
Thrusters_control.forward()
else:
Thrusters_control.turn_right()*
# if the `q` key was pressed, break from the loop
if key == ord("q"):
break
Explanation / Answer
Option 1:
You can get the bounds for the colours you need:
upper = np.array([210,90,70], dtype="uint8")
lower = np.array([76,31,4],dtype="uint8")
red_upper =np.array([0,0,255],dtype="uint8")
red_lower = np.array([30,30,200],dtype="uint8")
green_upper =np.array([0,255,0],dtype="uint8")
green_lower = np.array([30,200,30],dtype="uint8")
blue_upper =np.array([2550,0,0],dtype="uint8")
blue_lower = np.array([200,30,30],dtype="uint8")
Now you can detect each color using a function.
Option 2:
Alternatively, you can use Python to define your colours and then detect them:
colourLimits =
[
([17, 15, 100], [50, 56, 200]),
([86, 31, 4], [220, 88, 50]),
([25, 146, 190], [62, 174, 250]),
([103, 86, 65], [145, 133, 128])
]
Now you can employ colour detection -
# loop over the colour limits
for (lower, upper) in the limits:
# create NumPy arrays from the colour limits
upper = np.array(upper, dtype = "uint8")
lower = np.array(lower, dtype = "uint8")
# now apply a mask for the colours
mask = cv2.inRange(image, lower, upper)
output = cv2.bitwise_and(image, image, mask = mask)
# now have the images shown
cv2.imshow("images", np.hstack([image, output]))
cv2.waitKey(0)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.