This will filter the green and count the detected pixels, if lower than a set threshold will light a led, or drive a relay etc, through the gpio specified. You need to investigate the interface to 24v.
You may also need to workout when / how to trigger the camera when the roller is in the required position.
Code: Select all
#!/usr/bin/env python3
import cv2
import numpy as np
import RPi.GPIO as GPIO
# set threshold (no of pixels detected)
threshold = 6000
# setup GPIO outputs
out_gpio = 16
GPIO.setwarnings(False)
GPIO.setmode (GPIO.BOARD)
GPIO.setup (out_gpio,GPIO.OUT)
GPIO.output(out_gpio,GPIO.LOW)
font = cv2.FONT_HERSHEY_SIMPLEX
def callback(x):
pass
cap = cv2.VideoCapture(0)
cv2.namedWindow('image')
# startup values
lowH = 54
highH = 96
lowS = 52
highS = 255
lowV = 54
highV = 160
# create trackbars for color change
cv2.createTrackbar('lowH','image',lowH,255,callback)
cv2.createTrackbar('highH','image',highH,200,callback)
cv2.createTrackbar('lowS','image',lowS,255,callback)
cv2.createTrackbar('highS','image',highS,255,callback)
cv2.createTrackbar('lowV','image',lowV,255,callback)
cv2.createTrackbar('highV','image',highV,255,callback)
while True:
# grab the frame
ret, frame = cap.read()
# get trackbar positions
lowH = cv2.getTrackbarPos('lowH', 'image')
highH = cv2.getTrackbarPos('highH', 'image')
lowS = cv2.getTrackbarPos('lowS', 'image')
highS = cv2.getTrackbarPos('highS', 'image')
lowV = cv2.getTrackbarPos('lowV', 'image')
highV = cv2.getTrackbarPos('highV', 'image')
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_hsv = np.array([lowH, lowS, lowV])
higher_hsv = np.array([highH, highS, highV])
mask = cv2.inRange(hsv, lower_hsv, higher_hsv)
frame2 = cv2.bitwise_and(frame, frame, mask=mask)
gray_frame = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
# convert gray_frame to 0/1s
gray_frame[gray_frame < 50] = 0
gray_frame[gray_frame >= 50] = 1
# sum number of pixels
total = np.sum(gray_frame)
# trigger the output
if total < threshold:
GPIO.output(out_gpio,GPIO.HIGH)
cv2.putText(frame2,str(total), (10, 15), font, .5, (0, 0, 255), 1)
else:
GPIO.output(out_gpio,GPIO.LOW)
cv2.putText(frame2,str(total), (10, 15), font, .5, (0, 255, 0), 1)
# show the images
dim = (320, 240)
resize1 = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
resize2 = cv2.resize(frame2, dim, interpolation = cv2.INTER_AREA)
output = np.hstack((resize1,resize2))
cv2.imshow('image', output)
k = cv2.waitKey(10)
# press esc to quit
if k == 27:
break
cv2.destroyAllWindows()
cap.release()