简体   繁体   English

获取图像中的唯一像素

[英]Get unique pixels in image

The following:以下:

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

if giving:如果给:

(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]]]

How do I get the unique pixels?如何获得独特的像素? For example, [255 255 255] should be one of the unique pixel values.例如,[255 255 255] 应该是唯一的像素值之一。

As per comments, one of the ways to do that is np.unique(image.reshape(-1,3), axis=0) but this is can be improved significantly using dimensionality reduction with numba根据评论,其中一种方法是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]])

In case you have large images, you might like to try np.bincount -like methods for further speed ups.如果您有大图像,您可能想尝试np.bincount的方法以进一步加快速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM