【问题标题】:How to map a function to every pixel in an image that is represented as a numpy array?如何将函数映射到表示为 numpy 数组的图像中的每个像素?
【发布时间】:2021-03-19 16:15:10
【问题描述】:

当您使用 opencv-python (cv2) 并从 VideoCapture 设备读取时,它会返回一个表示图像的 numpy 数组,在我的情况下,尺寸为 (480, 640, 3)。我读过关于矢量化的文章,但我还没有真正理解它。

这是我要映射的函数

def RGBtoRGChromaticity(pixel):
    r, g, b = pixel

    total = r + g + b
    return r/total, g/total, b/total

这是我对它进行矢量化的尝试,但它不起作用:(

def RGBtoRGChromaticity(pixel):
    r, g, b = pixel

    total = ufunc.add(r, g, b)
    return ufunc.true_divide(r, total), ufunc.true_divide(g, total), ufunc.true_divide(b, total)

我正在尝试拍摄图像并找到绿色像素。我在一个名为RG Chromaticity 的颜色空间中找到了这篇文章,据我了解,它可以很容易地找到每个像素中的主色。文章上的数学似乎遵循了这个想法。我的主要问题是如何在 numpy 数组上映射函数,但如果有人对色彩空间和处理这个项目的更好方法有任何建议,请不要犹豫分享!!

【问题讨论】:

    标签: python numpy opencv


    【解决方案1】:

    矢量化的重点是您一次将其应用于整个数组,而不是每个像素。

    假设你有

    img = np.random.randint(255, size=(480, 640, 3), dtype=np.uint8)
    

    你的功能然后变成

    def RGBtoRGC(img):
        return img / img.sum(axis=-1, keepdims=True)
    

    如果你希望输出为uint8,我建议四舍五入:

    def RGBtoRGC(img):
        return np.rint(img / img.sum(axis=-1, keepdims=True), dtype=np.uint8)
    

    【讨论】:

      【解决方案2】:

      如何在 map_function args 中拆分通道?像这样

      import numpy as np
      
      
      def RGBtoRGChromaticity(r, g, b):
          total = r + g + b
          return r / total, g / total, b / total
      
      
      vfunc = np.vectorize(RGBtoRGChromaticity)
      image = np.random.uniform(size=(480, 640, 3))
      res = vfunc(image[:, :, 0], image[:, :, 1], image[:, :, 2])
      

      【讨论】:

        猜你喜欢
        • 2023-03-12
        • 1970-01-01
        • 1970-01-01
        • 2022-10-04
        • 1970-01-01
        • 2021-12-17
        • 2019-09-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多