![](/img/trans.png)
[英]How can i get the RGB values of an image as numpy array using OpenCV, Python
[英]How to correctly test RGB values using images(OpenCV & Python)?
我目前正在研究一個使用顏色檢測(OpenCV)的項目。 我是Python和OpenCV的新手,所以我無法完全按照自己的意願工作。
我有一個ColourDetection類(是否有任何微調HSV值的建議?),它包含用於檢測某種顏色的靜態方法detect_color。 這里是:
#!/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"
前兩個測試正常運行。 但是,最后一次測試應使用這些RGB值返回紅色。 似乎我需要對HSV值進行一些微調。 誰能幫我?
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)
之所以只檢測藍色,可能是由於detect_color
函數中的錯誤detect_color
。
@staticmethod
def detect_color(detection_image):
for k,v in ColourDetection.BOUNDARIES.iteritems():
# . . .
if amount_not_zero > 9000:
return k
else:
return "No colour found"
請注意,您將始終在k,v對上的第一次迭代中返回一個值。
也就是說,要么是iteritems()給出的第一個k
,要么是“未找到顏色”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.