Colordetc Documentation

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

from picamera.

array import PiRGBArray


from picamera import PiCamera
import os, sys, inspect, time
import cv2
import numpy as np
from PiStorms import PiStorms
# Initialisation of PiStorms and picamera
psm = PiStorms()

try:
picam = PiCamera()
#in case the camera is not enabled or not loaded properly excute this message
except:
m = ["color detction ", "Camera not enabled.", "Run raspi-config and enable
camera"]
psm.screen.askQuestion(m, ["OK"])
exit()

# check for button press to exit


if psm.isKeyPressed():
psm.screen.clearScreen()
psm.screen.termPrintAt(9, "Exiting to menu")
time.sleep(1)
exitNow = True
#main loop: we keep looping until the go buton is pressed so we exit
exitNow = False
time.sleep(1)
while not exitNow:
# we take acvapture of an image to do te processing
picam.capture('/tmp/pic.jpg')
psm.screen.fillBmp(0, 0, 320, 240, path="/tmp/pic.jpg")#we display the image
and we save it to a temporary location
psm.screen.termPrintAt(8, "Detecting colors...")#prini this message on display

img = cv2.imread('/tmp/pic.jpg')#this read the image captured


hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) #we convert it to hsv for better
result and accuracy
psm.screen.termPrintAt( "color range in hsv space :.",hsv_img)

# color ranges in the hsv color space for each pixel


#hue type of color
#saturation from 0 grayscale to 100 saturaryted
#value(britgthness from black 0 to white 100)
# color range for red
#it setss the the pixel to 255 if the colors are un the ranges if the color
captured
lower_red = np.array([0, 100, 100]) #hue saturation
upper_red = np.array([10, 255, 255])
# color range for green
lower_green = np.array([40, 100, 100])
upper_green = np.array([80, 255, 255])
# color range for blue
lower_blue = np.array([100, 100, 100])
upper_blue = np.array([140, 255, 255])

# we compare the output of hsv_image if its in range of one of the colors


# (255 is white the 0 is black)
#it s basicaly counting each pixel color that is in the range of each of the
following color
mask_red = cv2.inRange(hsv_img, lower_red, upper_red)
mask_green = cv2.inRange(hsv_img, lower_green, upper_green)
mask_blue = cv2.inRange(hsv_img, lower_blue, upper_blue)

# Display the result on PiStorms screen


psm.screen.fillBmp(0, 0, 320, 240, path="/tmp/pic.jpg")
psm.screen.termPrintAt(8, "Colors Detected!")

# Add logic to determine the detected color and display it


#we check if there are more than 1000 white pixel in each mask
if cv2.countNonZero(mask_red) > 1000:
psm.screen.termPrintAt(8, "Color: Red")
elif cv2.countNonZero(mask_green) > 1000:
psm.screen.termPrintAt(8, "Color: Green")
elif cv2.countNonZero(mask_blue) > 1000:
psm.screen.termPrintAt(8, "Color: Blue")
else:
psm.screen.termPrintAt(8, "Color: Not Detected")

You might also like