Skip to content

Instantly share code, notes, and snippets.

@smeschke
Created March 22, 2017 23:39
Show Gist options
  • Save smeschke/81ef3138f762384268a3716a7dbd84ec to your computer and use it in GitHub Desktop.
Save smeschke/81ef3138f762384268a3716a7dbd84ec to your computer and use it in GitHub Desktop.
displays hue value histogram from webcam feed
#import cv2 for vision
#numpy to generate backgrounds
import cv2
import numpy as np
#capture video from the webcam
cap = cv2.VideoCapture(0)
#read one frame
_, img = cap.read()
#define two points, used to make a mask
x1 = 100
y1 = 100
x2 = 200
y2 = 200
# create a mask
mask = np.zeros(img.shape[:2], np.uint8)
mask[y1:y2, x1:x2] = 255
#define the height of the graph
graph_height = 200
graph_length = 640
#main loop of
while True:
#read image from the webcam
_, img = cap.read()
#convert image to hsv color space
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
#calculate the histogram for the hue value in the masked area
hist_mask = cv2.calcHist([img_hsv], [0], mask, [255], [0,256])
#create a mask of the image
masked_img = cv2.bitwise_and(img,img,mask = mask)
#create gray background for graph
graph = np.zeros((graph_height,graph_length,3),np.uint8)
graph[::] = (123,123,123)
#define values for graphing for graphing
x_value = 0
previous_x = 0
previous_y = 640
#scale the histogram
hist_scaled = hist_mask*(graph.shape[0]/max(hist_mask))
#make graph
for y_value in hist_scaled:
#tedious method to convert values to get color
test = np.zeros((1,1,3), np.uint8)
test[::] = int(x_value/3.0), 255,255
test = cv2.cvtColor(test, cv2.COLOR_HSV2BGR)
cvc = int(test[0][0][0]), int(test[0][0][1]), int(test[0][0][2])
#spacing issues
x_value+=3
y_value = graph_height-y_value
#graph
cv2.line(graph, (x_value, y_value),
(previous_x, previous_y), cvc, 8)
#update previous values
previous_x = x_value
previous_y = y_value
#put a rectangle on the image to show where the mask
cv2.rectangle(img,(x1,y1), (x2,y2), (123,123,123), 2)
#show image
cv2.imshow('img', img)
cv2.imshow('graph', graph)
cv2.waitKey(1)
cv2.destroyAllWindows()
cap.release()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment