Skip to content

Instantly share code, notes, and snippets.

@IanMcT
Created January 15, 2017 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IanMcT/015f64ee60ac1ac28ddea5921d662daa to your computer and use it in GitHub Desktop.
Save IanMcT/015f64ee60ac1ac28ddea5921d662daa to your computer and use it in GitHub Desktop.
Sample python program to take a picture and output the colour within a specified range.
import cv2
import numpy as np
#note the libraries that need importing
# Camera 0 is the integrated web cam on my netbook
camera_port = 0
#Number of frames to throw away while the camera adjusts to light levels
ramp_frames = 30
# Now we can initialize the camera capture object with the cv2.VideoCapture class.
# All it needs is the index to a camera port.
camera = cv2.VideoCapture(camera_port)
# Captures a single image from the camera and returns it in PIL format
def get_image():
# read is the easiest way to get a full image out of a VideoCapture object.
retval, im = camera.read()
return im
# Ramp the camera - these frames will be discarded and are only used to allow v4l2
# to adjust light levels, if necessary
for i in range(ramp_frames):
temp = get_image()
print("Taking image...")
# Take the actual image we want to keep
camera_capture = get_image()
#convert to hsv
hsv = cv2.cvtColor(camera_capture, cv2.COLOR_BGR2HSV)
#set limits for colour to identify
lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])
#create a mask based on the colour
mask = cv2.inRange(hsv, lower_blue, upper_blue)
#combine so the masked area will be visible
res = cv2.bitwise_and(camera_capture,camera_capture, mask= mask)
#file locations for the test files
file = "images/test_image.png"
file_hsv = "images/hsvtest_image.png"
file_res = "images/restest_image.png"
# A nice feature of the imwrite method is that it will automatically choose the
# correct format based on the file extension you provide. Convenient!
cv2.imwrite(file, camera_capture)
cv2.imwrite(file_hsv, hsv)
cv2.imwrite(file_res,res)
# You'll want to release the camera, otherwise you won't be able to create a new
# capture object until your script exits
del(camera)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment