【问题标题】:getting key and value from a dictionary从字典中获取键和值
【发布时间】:2019-02-16 12:13:25
【问题描述】:

我正在研究图像处理。在那里打印 RGB 值。我将这些图像转换为灰度图像。所以它返回黑色,而像这样的值(左 = {0: 58, 255: 182})。这里 0 代表黑色,255 代表白色。我需要得到那些黑色和white 值分开,并检查白色或黑色是否具有更高的值。

 unique, counts = np.unique(cropped_right, return_counts=True)
 mapColorCounts = dict(zip(unique, counts))
 print("right=",mapColorCounts)

它返回的字典值。因为我需要单独的键和值

回报:

{0: 218, 255: 426}
{255: 196}
{0: 51, 255: 189}
{0: 406, 255: 314}
{0: 47, 255: 193}
{0: 28, 255: 278}
{0: 286, 255: 632}
{255: 306}
{0: 15, 255: 85}
{0: 91, 255: 229}

我需要找出返回了多少组键值。因为有时它会返回 2 个值和 1 个值

【问题讨论】:

  • 那么您到底在期待什么?作为输出
  • 我需要将 0 和 255 值分开
  • 我很难相信您自己编写了您在此处提供的这段代码,但却难以从字典中简单地提取键
  • 我可以从数组和列表中做到这一点。我不知道如何处理字典

标签: python arrays


【解决方案1】:

如果您将值作为字典,则可以使用 mapColorCounts.values() 返回 255 和 0 值。为了可视化,dicts 像 yourDict = {key: value, key: value} 这样存储,为了返回键或值,您只需在 dict 上运行相应的 keys()values() 方法

您可以从这里创建一个简单的方法来测试值:

def whichColorGreater(inputDict):
    values = inputDict.values()

    for value in values:
        if len(value) > 1:
            if value[0] > value[1]:
                print("Black is greater")
            else:
                print("White is greater")
        else:
            print("White is greater")

【讨论】:

  • 它返回整个值。我需要单独的值
【解决方案2】:

假设cropped_right 是二进制的,我认为你可以简化为:

has_more_white = (np.count_nonzero(cropped_right) / cropped_right.size) > 0.5

如果需要元素数量:

nb_white_pixels = np.count_nonzero(cropped_right)
nb_black_pixels = cropped_right.size - nb_white_pixels

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多