【问题标题】:How to solve problem of unhashable type: 'numpy.ndarray'如何解决不可哈希类型的问题:'numpy.ndarray'
【发布时间】:2020-04-06 13:47:48
【问题描述】:

我正在尝试这样做:

for myimage in Images:
    image = cv2.imread(myimage)  
    processed_image = Image_Preprocessing(image) 

    name = os.path.basename(myimage) # Get image name to save it as a Class
    class_name = str(name) 
    Image_count= Image_count+1

    # To divide the image to mxm patches
    for r in range(0,processed_image.shape[0],patch_size):
        for c in range(0,processed_image.shape[1],patch_size):
             value= processed_image[r:r+patch_size, c:c+patch_size]


             #Search for similar patch 
             #if the value already exists in dict only update the classes list
             #else add the value in dict and update the classes list 
             if any((value == patch).all() for patch in Patches_dic.keys()):
                if (class_name in Patches_dic[value] ):  
                    continue
                else:
                    Patches_dic[value].append(class_name) 
             else:
                 list_Of_Classes.append(class_name)
                 Patches_dic.update({value : list_Of_Classes })   #Key: image patch  Value: List of Classes

但是,我得到了这个错误

Patches_dic.update({tuple(value) : list_Of_Classes })

TypeError: unhashable type: 'numpy.ndarray'

我不知道我做错了什么以及如何解决这个问题:(

【问题讨论】:

  • 您可以使用ndarray(和许多其他复杂类型)作为字典中的键,作为值就可以了。
  • 您正在尝试将数组用作字典键。这是做不到的。

标签: python python-3.x numpy typeerror numpy-ndarray


【解决方案1】:

正如@hpaulj 所述。字典键不能是 ndarrayslist 等列表类型的对象。

根据提供的代码,我猜value 存储了图像的一部分,格式为ndarray。因此,如果您想将其保留为键,请尝试对其进行散列并将图像的散列作为键。请参考this 了解如何正确地将图像表示为键。

【讨论】:

    猜你喜欢
    • 2021-08-13
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    • 2023-02-10
    • 2020-06-13
    • 1970-01-01
    相关资源
    最近更新 更多