np.sum不返回总计数 [英] np.sum Not returning total counts

查看:367
本文介绍了np.sum不返回总计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试此代码,但它不返回零[x] [y]的总计数,在这种情况下它应该返回5但是它显示255五次。

这个代码是用于连接组件和零是白色像素的一个组件

I am trying this code but it does not return total count for zero[x][y], in this case it should return 5 but all it displays 255 five time.
THIS CODE IS FOR CONNECTED COMPONENTS AND ZERO IS ONE COMPONENT FOR WHITE PIXEL

预期输出应为:5

但是什么我得到的是:

255

255

255

255

255

Expected Output should be:5
But what i am getting is:
255
255
255
255
255

for (x, y) in labels:
        component = uf.find(labels[(x, y)])
        # Update the labels with correct information
        labels[(x, y)] = component
        path='imagesNew/13/'
        if labels[(x, y)]==0:
            Zero[y][x]=int(255)
            Z=Zero[y][x]
            print Z
            if Z==5:
              print Zero[y][x]
              Zeroth = Image.fromarray(Zero)
              Zeroth.save(path+'Zero'+'.png','png')


推荐答案

我相信这就是你所追求的。此代码将遍历标记图像中的每个标签,创建一个布尔掩码,显示每个标签在图像中的位置,并对该掩码求和,以告诉您每个标签的总计数。

I believe this is what you're after. This code will loop through each label in the labeled image, create a boolean mask showing where each label is in the image, and sum that mask to tell you the total count of each label.

import numpy as np
labeled_img = np.array([
    [1, 1, 0, 0, 2],
    [1, 0, 0, 2, 2],
    [1, 0, 2, 2, 2],
    [1, 1, 1, 2, 2],
    [1, 1, 1, 2, 2]])

for label in np.unique(labeled_img):
    print('Quantity of', label, 'labels:', np.sum(labeled_img == label))




0个标签数量:5

1个标签数量:10 -
2个标签数量:10

Quantity of 0 labels: 5
Quantity of 1 labels: 10
Quantity of 2 labels: 10

请注意,如果你使用OpenCV查找连接的组件,的第一个返回值connectedComponents()是标签的数量,因此您只需循环遍历即可获得标签范围(n_labels)而不是 np.unique(),这会更快一些。

Note that if you used OpenCV to find the connected components, the first return value of connectedComponents() is the number of labels, so you can simply loop over for label in range(n_labels) instead of np.unique(), which would be a tad faster.

这篇关于np.sum不返回总计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆