查找图像的最小和最大

时间:2019-04-27 09:36:59

标签: python cv2

我将一些图像(带有cv2.imread_color)加载到列表中,并尝试使用函数rgb_to_hsv从其中获取hsv(色相,饱和度,值)值。

我有红色,绿色和蓝色值,但是当我尝试获取hsv值时,我得到 关于参数的错误

Traceback (most recent call last):
  File "C:\Users\Downloads\preprocessing\program.py", line 69, in <module>
    hue_images[i], saturnation_images[i], value_images[i] = rgb_to_hsv(hsv_red[i], hsv_green[i], hsv_blue[i])

File "C:\Users\Downloads\preprocessing\program.py", line 24, in rgb_to_hsv
    mx = max(r, g, b)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

这是我正在使用的代码:

hue_images = list(range(len(image)))
saturnation_images = list(range(len(image)))
value_images = list(range(len(image)))

hsv_red = list(range(len(image)))
hsv_green = list(range(len(image)))
hsv_blue = list(range(len(image)))

def rgb_to_hsv(r, g, b):
    r, g, b = r/255.0, g/255.0, b/255.0
    mx = max(r, g, b)
    mn = min(r, g, b)
    df = mx-mn
    if mx == mn:
        h = 0
    elif mx == r:
        h = (60 * ((g-b)/df) + 360) % 360
    elif mx == g:
        h = (60 * ((b-r)/df) + 120) % 360
    elif mx == b:
        h = (60 * ((r-g)/df) + 240) % 360
    if mx == 0:
        s = 0
    else:
        s = (df/mx)*100
    v = mx*100
    return h, s, v

def hsv_get_red(img):
    red = img.copy()
    red[:, :, 0] = 0
    red[:, :, 1] = 0

    return red[:, :, 2]

def hsv_get_green(img):
    green = img.copy()
    green[:, :, 0] = 0
    green[:, :, 2] = 0

    return green[:, :, 1]

def hsv_get_blue(img):
    blue = img.copy()
    blue[:, :, 2] = 0
    blue[:, :, 1] = 0

    return blue[:, :, 0]

for i in range(len(image)):
    hsv_red[i] = hsv_get_red(image[i])
    hsv_green[i] = hsv_get_green(image[i])
    hsv_blue[i] = hsv_get_blue(image[i])

for i in range(len(image)):
    hue_images[i], saturnation_images[i], value_images[i] = rgb_to_hsv(hsv_red[i], hsv_green[i], hsv_blue[i])

我的问题是:如何在函数中使用列表值作为参数(它与int数字一起使用)以获取结果(另一个列表值)?

1 个答案:

答案 0 :(得分:0)

您传递的r g b参数是opencv库的Mat“数组”

内置的minmax函数不知道如何处理-您必须使用numpy库的min和max函数

import numpy as np
np.max([r,g,b])

或手动遍历所有r,g,b值以找到最小值和最大值,如果您不希望numpy依赖,即类似

import itertools
maximum = max( x for x in itertools.chain(r.reshape(r.size),g.reshape(g.size),b.reshape(b.size)))

不幸的是cv2.min不能像numpy min一样工作,在这里没有用