我有寶石影像的資料集。我根據寶石的顏色將寶石分類到檔案夾中。(即紅色、藍色、粉紅色、紫色、黃色)。
我想做的是:
我想使用 hsv 模型和 opencv 訓練一個模型來檢測寶石的顏色。無論是藍色、紫色、粉紅色、黃色還是紅色,以及除了這 5 種顏色之外的任何其他顏色都定義為未定義顏色
原始碼:(參考https://www.kaggle.com)
import os
import matplotlib.pyplot as plt
import seaborn as sn
import cv2
from random import randint
import numpy as np
CLASSES, gems = [], [] # names of classes, count of images for each class
for root, dirs, files in os.walk('C:/Users/User/Desktop/Research Project/images'):
f = os.path.basename(root) # get class name - Red,Blue etc
if len(files) > 0:
gems.append(len(files))
if f not in CLASSES:
CLASSES.append(f) # add folder name
gems_count = len(CLASSES) # 6 = number of classes
print('{} classes with {} images in total'.format(len(CLASSES), sum(gems)))
img_w, img_h = 220, 220 # width and height of image
train_dir = 'C:/Users/User/Desktop/Gem/images/train'
def read_imgs_lbls(_dir):
Images, Labels = [], []
for root, dirs, files in os.walk(_dir):
f = os.path.basename(root) # get class name - Red, Blue, etc
for file in files:
Labels.append(f)
try:
image = cv2.imread(root '/' file) # read the image (OpenCV)
image = cv2.resize(image,(int(img_w*1.5), int(img_h*1.5))) # resize the image (images are different sizes)
image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # converts an image from BGR color space to HSV
Images.append(image)
except Exception as e:
print(e)
Images = np.array(Images)
return (Images, Labels)
def get_class_index(Labels):
for i, n in enumerate(Labels):
for j, k in enumerate(CLASSES): # foreach CLASSES
if n == k:
Labels[i] = j
Labels = np.array(Labels)
return Labels
Train_Imgs, Train_Lbls = read_imgs_lbls(train_dir)
Train_Lbls = get_class_index(Train_Lbls)
print('Shape of train images: {}'.format(Train_Imgs.shape))
print('Shape of train labels: {}'.format(Train_Lbls.shape))
dim = 4
f,ax = plt.subplots(dim,dim)
f.subplots_adjust(0,0,2,2)
for i in range(0,dim):
for j in range(0,dim):
rnd_number = randint(0,len(Train_Imgs))
cl = Train_Lbls[rnd_number]
ax[i,j].imshow(Train_Imgs[rnd_number])
ax[i,j].set_title(CLASSES[cl] ': ' str(cl))
ax[i,j].axis('off')
它從檔案夾名稱中讀取值。但我想將每種顏色的下限值和上限值添加到訓練模型中,如下面的鏈接所示。(參考如何知道在 opencv 上是否檢測到顏色)
import cv2
import numpy as np
img = cv2.imread("img.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_val = np.array([37,42,0])
upper_val = np.array([84,255,255])
# Threshold the HSV image - any green color will show up as white
mask = cv2.inRange(hsv, lower_val, upper_val)
# if there are any white pixels on mask, sum will be > 0
hasGreen = np.sum(mask)
if hasGreen > 0:
print('Green detected!')
我也找到了我想要的顏色的下限和上限 hsv 值
'red': [[9, 255, 255], [0, 50, 70]],
'blue': [[128, 255, 255], [90, 50, 70]],
'yellow': [[35, 255, 255], [25, 50, 70]],
'purple': [[158, 255, 255], [129, 50, 70]]
誰能告訴我如何將使用 hsv 值檢測顏色(如如何知道在 opencv 上是否檢測到顏色)與我的源代碼相結合。
我是影像處理的新手,不勝感激。
謝謝你。
uj5u.com熱心網友回復:
此代碼演示如何遍歷檔案夾中的所有檔案./images并回傳檢測到的顏色:
import os
import numpy as np
import cv2
# map colour names to HSV ranges
color_list = [
['red', [0, 160, 70], [10, 250, 250]],
['pink', [0, 50, 70], [10, 160, 250]],
['yellow', [15, 50, 70], [30, 250, 250]],
['green', [40, 50, 70], [70, 250, 250]],
['cyan', [80, 50, 70], [90, 250, 250]],
['blue', [100, 50, 70], [130, 250, 250]],
['purple', [140, 50, 70], [160, 250, 250]],
['red', [170, 160, 70], [180, 250, 250]],
['pink', [170, 50, 70], [180, 160, 250]]
]
def detect_main_color(hsv_image, colors):
color_found = 'undefined'
max_count = 0
for color_name, lower_val, upper_val in colors:
# threshold the HSV image - any matching color will show up as white
mask = cv2.inRange(hsv_image, np.array(lower_val), np.array(upper_val))
# count white pixels on mask
count = np.sum(mask)
if count > max_count:
color_found = color_name
max_count = count
return color_found
for root, dirs, files in os.walk('./images'):
f = os.path.basename(root)
for file in files:
img = cv2.imread(os.path.join(root, file))
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
print(f"{file}: {detect_main_color(hsv, color_list)}")
在子檔案夾中輸出三個示例影像images:
ruby_3.jpg: red
sapphire blue_18.jpg: blue
sapphire pink_18.jpg: pink
sapphire purple_28.jpg: purple
sapphire yellow_9.jpg: yellow
學分:
- HSV 顏色范圍
- 如何檢測顏色范圍
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/471839.html
