首页 > 解决方案 > 关于分析图像数组的唯一值

问题描述

读取图像有以下函数,我添加了几行重新输出图像,并输出图像数组的不同像素值。图像看起来像这样。然而 a,indices =np.unique(img,return_index=True)

[0 1]

指数 [0 879385]

看起来图像数组有两个唯一值,[0 1],这是有道理的,但索引表示什么?

def _get_image_data_pil(image_id, image_type, return_exif_md=False, return_shape_only=False):
    fname = get_filename(image_id, image_type)
    try:
        img_pil = Image.open(fname)
    except Exception as e:
        assert False, "Failed to read image : %s, %s. Error message: %s" % (image_id, image_type, e)

    if return_shape_only:
        return img_pil.size[::-1] + (len(img_pil.getbands()),)
    # -----
    # this is what I adde
    # -----

    img = np.asarray(img_pil)
    plt.imshow(img)
    plt.show()
    a,indices =np.unique(img,return_index=True)
    print('a ',a)
    print('indices ',indices)

    assert isinstance(img, np.ndarray), "Open image is not an ndarray. Image id/type : %s, %s" % (image_id, image_type)
    if not return_exif_md:
        return img
    else:
        return img, img_pil._getexif()

在此处输入图像描述

标签: pythonnumpyimage-processingscipypillow

解决方案


索引给出了扁平化输入数组中唯一值的第一次出现。要将这些索引转换为二维索引到输入,您可以使用np.unravel_index.

例如,假设 的形状img为 (1000, 1600):

In [110]: shape = (1000, 1600)

In [111]: indices = [0, 879385]

In [112]: np.unravel_index(indices, shape)
Out[112]: (array([  0, 549]), array([  0, 985]))

np.unravel_indices返回两个数组,每个维度一个。也就是说,第一个数组保存第一维(即行)的索引,第二个数组保存第二维(即列)的索引。要将它们放入坐标数组中,您可以使用np.column_stack

In [113]: np.column_stack(np.unravel_index(indices, shape))
Out[113]: 
array([[  0,   0],
       [549, 985]])

推荐阅读