Segment an image using python and PIL to calculate centroid and rotations of multiple rectangular objects

后端 未结 2 396
梦谈多话
梦谈多话 2021-02-02 04:24

I am using python and PIL to find the centroid and rotation of various rectangles (and squares) in a 640x480 image, similar to this one

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-02 05:05

    Here is an example of how you can do this by labelling the image, and then taking the centroid for the centers, this is all built in to ndimage in scipy (along with a bunch of other cool image things). For the angles, I've used the rectangle corner intercepts with the edges of the bounding slices.

    import numpy as np
    import scipy
    from scipy import ndimage
    
    im = scipy.misc.imread('6JYjd.png',flatten=1)
    im = np.where(im > 128, 0, 1)
    label_im, num = ndimage.label(im)
    slices = ndimage.find_objects(label_im)
    centroids = ndimage.measurements.center_of_mass(im, label_im, xrange(1,num+1))
    
    angles = []
    for s in slices:
        height, width = label_im[s].shape
        opp = height - np.where(im[s][:,-1]==1)[0][-1] - 1
        adj = width - np.where(im[s][-1,:]==1)[0][0] - 1
        angles.append(np.degrees(np.arctan2(opp,adj)))
    print 'centers:', centroids
    print 'angles:', angles
    

    Output:

    centers: [(157.17299748926865, 214.20652790151453), (219.91948280928594, 442.7146635321775), (363.06183745583041, 288.57169725293517)]
    angles: [7.864024795499545, 26.306963825741803, 7.937188000622946]
    

提交回复
热议问题