Skip to content

Instantly share code, notes, and snippets.

@frank9615
Created October 3, 2019 21:25
Show Gist options
  • Save frank9615/9fe16750bc72048f6a4a8566823bb02c to your computer and use it in GitHub Desktop.
Save frank9615/9fe16750bc72048f6a4a8566823bb02c to your computer and use it in GitHub Desktop.
Detecting colors (Hsv Color Space) - Opencv with Python
# USAGE
# python distance_to_camera.py
# import the necessary packages
from imutils import paths
import numpy as np
import imutils
import cv2
cap = cv2.VideoCapture(0)
while(1):
# Take each frame
_, image = cap.read()
# convertiamo in hsv
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
hsv = cv2.GaussianBlur(hsv, (5, 5), 0)
# #
'''
sensitivity = 15
lower_green = np.array([60 - sensitivity, 100, 100])
upper_green = np.array([60 + sensitivity, 255, 255])
'''
lower_green = np.array([25, 52, 72])
upper_green = np.array([102, 255, 255])
# Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower_green, upper_green)
edged = cv2.Canny(mask, 35, 125)
cv2.imshow("mask",edged)
try :
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
c = max(cnts, key=cv2.contourArea)
rect = cv2.minAreaRect(c)
box = np.int0(cv2.boxPoints(cv2.minAreaRect(c)))
cv2.drawContours(image, [box], -1, (255, 0, 0), 2)
cv2.imshow("image", image)
except:
pass
# Display
#cv2.imshow('image', image)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment