【问题标题】:How to find the maximum element value across multiple arrays?如何在多个数组中找到最大元素值?
【发布时间】:2019-09-11 20:48:01
【问题描述】:

我正在尝试手动将 BGR 图像转换为 HSV。我需要找到 3 个图像通道(numPy 数组)中每个通道的最大像素值,并创建一个包含 3 个通道中最大值的新数组。

def convertBGRtoHSV(image):

    # normalize image
    scaledImage = image // 256

    # split image into 3 channels
    B, G, R = cv2.split(scaledImage)

    # find the shape of each array
    heightB, widthB = B.shape

    V = []
    for h_i in range(0, height):
        for w_i in range(0, width):
            V[h_i][w_i] = max(B[h_i][w_i], G[h_i][w_i], R[h_i][w_i])

我收到此错误:IndexError: list index out of range

我知道这个循环是不正确的。我知道要访问数组中像素的值,您必须说出位置,例如x[:,:],但我不确定如何遍历每个图像的所有像素并使用max 值创建一个新数组每个数组元素。

如果可能的话,我想知道如何使用 numPy "Vectorized Operation" 以及 for 循环来完成此操作。

【问题讨论】:

  • 您正在尝试为最后一行的一维列表的第二维赋值。
  • 嗨,你能解释一下你的意思吗?我仍然想知道如何使用 for 循环来解决这个问题...
  • 我会添加一个答案解释。
  • 我想我想通了...V 应该与B 具有相同的形状,这意味着V = np.zeros_like(B) 将使其具有相同的形状。当您谈到多维数组时,您指的是列表中的列表,对吗?例如V[h_i][w_i] 正在访问列表的列表?但是,是的,希望看到另一个答案。谢谢。

标签: arrays python-3.x numpy for-loop


【解决方案1】:

有一个按元素最大值的内置函数:

V = np.maximum(np.maximum(R, G), B)

...你就完成了

【讨论】:

    【解决方案2】:

    跟进我的评论:

    import cv2
    import numpy as np
    
    image = cv2.imread(image)
    
    height, width, _ = image.shape
    
    # initialize your output array 'v'
    v = np.zeros((height, width))
    
    # loop over each index in ranges dictated by the image shape
    for row in range(height):
        for col in range(width):
            # assign the maximum value across the 3rd dimension (color channel)
            # from the original image to your output array 
            v[row, col] = max(image[row, col, :])
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-03
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      相关资源
      最近更新 更多