I'm currently working on a project which uses color detection (OpenCV). I'm very new to Python and OpenCV so I'm not getting it work exactly as I want it to.
I have a class ColourDetection(any suggestions for fine tuning the HSV values?) which contains the static method detect_color which we use to detect a certain color. Here it is:
#!/usr/bin/env python
import cv2
import numpy as np
class ColourDetection(object):
#HSV 180-255-255 max values openCV (recalculate from GIMP)
#these need adjusting
BOUNDARIES = {
'red': ([170, 160, 60], [180, 255, 255]),
'blue': ([110, 50, 50], [130, 255, 255]),
'green': ([38, 50, 50], [75, 255, 255]),
'yellow':([103, 50, 50], [145, 255, 255])
}
@staticmethod
def detect_color(detection_image):
img_hsv = cv2.cvtColor(detection_image, cv2.COLOR_BGR2HSV)
#loop for all defined colours
for k,v in ColourDetection.BOUNDARIES.iteritems():
#convert to numpy arrays
lower_color = np.array(v[0])
upper_color = np.array(v[1])
#create mask from colour bounds
mask = cv2.inRange(img_hsv, lower_color, upper_color)
#count found colour pixels
amount_not_zero = cv2.countNonZero(mask)
if amount_not_zero > 9000:
return k
else:
return "No colour found"
The first 2 tests are working correctly. However the last test should return red using these RGB values. It seems I need some fine tuning with the HSV values. Can anyone help me?
from unittest import TestCase
from ColourDetection import ColourDetection
import numpy as np
__author__ = 'user'
class TestColourDetection(TestCase):
def test_detect_color_not_found(self):
image = np.zeros((512, 512, 3), np.uint8)
color = ColourDetection.detect_color(image)
self.assertEqual("No colour found", color)
def test_detect_color_is_red(self):
image = np.zeros((512, 512, 3), np.uint8)
image[:,0:512] = (0, 0, 255)
color = ColourDetection.detect_color(image)
self.assertEqual("red", color)
def test_detect_color_is_blue(self):
image = np.zeros((512, 512, 3), np.uint8)
image[:,0:512] = (255, 0, 0)
color = ColourDetection.detect_color(image)
self.assertEqual("blue", color)
def test_detect_color_is_green(self):
image = np.zeros((512, 512, 3), np.uint8)
image[:,0:512] = (0, 255, 0)
color = ColourDetection.detect_color(image)
self.assertEqual("green", color)
def test_detect_color_is_yellow(self):
image = np.zeros((512, 512, 3), np.uint8)
image[:,0:512] = (0, 255, 255)
color = ColourDetection.detect_color(image)
self.assertEqual("yellow", color)