三维图像中的对象数

2024-06-16 10:51:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图计算3D图像中对象的数量,我在Python中发现了以下代码:

def count_objects(image):
    width, height = len(image[0]), len(image)
    objects_members = [(x, y) for x in range(width) for y in range(height) if image[y][x] == 1]
    objects_count = 0
    while objects_members != []:
       remove_object(objects_members, objects_members.pop(0))
       objects_count += 1
    return objects_count

def remove_object(objects_members, start_point):
    x, y = start_point
    connex = [(x - 1, y), (x, y - 1),
              (x + 1, y), (x, y + 1)]
    for point in connex:
        try:
            objects_members.remove(point)
            remove_object(objects_members, point)
        except ValueError:
            pass

if __name__ == "__main__":
    image = []
    while True:
        line = input()
        if line == "":
            break
        image.append([int(pixel) for pixel in line])
    print(count_objects(image))

该方法识别属于一个对象(设置为1)的像素,然后删除一个、其邻居和其邻居的邻居(删除一个对象),并重复该操作,直到所有的像素都被删除。你知道吗

我试图用c++转换这段代码,但我的递归函数似乎没有停止。下面是我的代码(RemoveObject函数):

void RemoveObject(vector<int> Vector, int start_point)
{
    int     *IndexNeighbor;
    unsigned char     *Neighbor;
    Neighbor=Neighborhood26(Image, start_point); //26-Connex neighborhood
    IndexNeighbor=IndexNeighborhood26(start_point);// the index of 26-Connex neighborhood
    vector<int> Connex;
    for(int i=0; i<26;i++)
    {
        bool isIN=false;
        if((int)Neighbor[i]==1)
        {
            for(int k=0; k<Vector.size();k++)
            {if(IndexNeighbor[i]==Vector[k]){isIN=true;}}   
         } 
        if(isIN==true){Connex.push_back(IndexNeighbor[i]);}
    }

    if(Connex.size()==0){cout<<"Vector empty"<<endl;}
    else
    {
        for(int j=0; j<Connex.size(); j++)
        {
            Vector.erase(std::remove(Vector.begin(), Vector.end(), Connex[j]), Vector.end());
            RemoveObject(Vector, Connex[j]);
        }
    }
}

有人能指出我犯的错误吗?你知道吗

谢谢


Tags: 对象inimageforifobjectscountstart