【问题标题】:Get unique pixels in image获取图像中的唯一像素
【发布时间】:2022-01-15 02:52:02
【问题描述】:

以下内容:

image = cv2.imread("image.png")
print(image.shape)
print(np.unique(image,axis=1))

如果给予:

(700, 500, 3)
[[[255 255 255]
  [255 255 255]
  [255 255 255]
  ...
  [255 255 255]
  [255 255 255]
  [255 255 255]]

 [[255 255 255]
  [255 255 255]
  [255 255 255]
  ...
  [255 255 255]
  [255 255 255]
  [255 255 255]]

 [[255 255 255]
  [255 255 255]
  [255 255 255]
  ...
  [255 255 255]
  [255 255 255]
  [255 255 255]]

 ...

 [[255 255 255]
  [255 255 255]
  [255 255 255]
  ...
  [255 255 255]
  [255 255 255]
  [255 255 255]]

 [[255 255 255]
  [255 255 255]
  [255 255 255]
  ...
  [255 255 255]
  [255 255 255]
  [255 255 255]]

 [[255 255 255]
  [255 255 255]
  [255 255 255]
  ...
  [255 255 255]
  [255 255 255]
  [255 255 255]]]

如何获得唯一像素?例如,[255 255 255] 应该是唯一的像素值之一。

【问题讨论】:

  • 将其重新整形为3列的二维数组,这样每一行代表一个像素,列是颜色分量。然后沿轴 0 获得唯一(即唯一行)。 -- np.unique(image.reshape(-1,3), axis=0)
  • 正如@DanMašek 所建议的那样很好——尽管这里有更快的方法...stackoverflow.com/a/59671950/2836621
  • @MarkSetchell 不是只计算唯一像素的数量,而不是列出它们吗?
  • @QuangHoang 是的,你是对的 - 我必须更加注意。我想他们可能没有被破坏,但在这里可能不值得付出努力。

标签: python numpy opencv png


【解决方案1】:

根据 cmets,其中一种方法是 np.unique(image.reshape(-1,3), axis=0),但这可以通过使用 numba 的降维来显着改善

import numpy as np
from numba import njit, prange

@njit(parallel=True)
def _numba_dot(arr, dimshape, len_arr, len_dimshape, su):
    for i in prange(len_arr):
        for j in range(len_dimshape):
            su[i] = su[i] + arr[i][j] * dimshape[j]
        
def numba_dimreduce(arr, dtype=int):
    dimshape = np.array([1, 256, 65536])
    su = np.zeros(len(arr), dtype=dtype)
    _numba_dot(arr, dimshape, len(arr), len(dimshape), su)
    return su

>>> image = np.array([[[255, 255, 255], [255, 254, 254]], [[255, 254, 254], [254, 254, 254]]])
>>> img = image.reshape(-1, 3))
>>> img
array([[255, 255, 255],
   [255, 254, 254],
   [255, 254, 254],
   [254, 254, 254]])
>>> u, idx = np.unique(numba_dimreduce(img), return_index=True)
>>> img[idx]
array([[254, 254, 254],
       [255, 254, 254],
       [255, 255, 255]])

如果您有大图像,您可能想尝试np.bincount-like 方法以进一步加快速度。

【讨论】:

    猜你喜欢
    • 2014-09-03
    • 2021-11-03
    • 2011-12-05
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    • 2012-12-20
    相关资源
    最近更新 更多