简体   繁体   中英

How to find ellipse coordinates from indexed image (Python)?

I have this kind of image:

在此处输入图像描述

which represents concentric ellipses. This image is contained in a numpy matrix with ones in the index of the different ellipses perimeter and zeros elsewhere.

Since I want to find the centers of each one of these ellipses, I found these two functions:

def fitEllipse(x,y):
   x = x[:,np.newaxis]
   y = y[:,np.newaxis]
   D =  np.hstack((x*x, x*y, y*y, x, y, np.ones_like(x)))
   S = np.dot(D.T,D)
   C = np.zeros([6,6])
   C[0,2] = C[2,0] = 2; C[1,1] = -1
   E, V =  eig(np.dot(inv(S), C))
   n = np.argmax(np.abs(E))
   a = V[:,n]
return a

def ellipse_center(a):
   b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0]
   num = b*b-a*c
   x0=(c*d-b*f)/num
   y0=(a*f-b*d)/num
return np.array([x0,y0])

which can fit an ellipse curve and find the center of the given ellipse, respectively. The problem is that If I can able to draw by myself different ellipses "objects" I can know what the coordinates of the different points are. But in my case I have only access to the index where the values are ones, without knowing what indexes belong to a certain ellipse and what indexes to another..

So is there a way I can separate those different ellipses, individually storing their index coordinates?

Finally, the idea would be to fit an ellipse to all of the these ellipse objects and find their centers. Thanks in advance:)

So is there a way I can separate those different ellipses, individually storing their index coordinates?

You can use scikit-image label to label your ellipses like so:

import skimage.io
import skimage.measure
import numpy as np

im = (skimage.io.imread("so67279689.png", as_gray=True)>.3).astype(int)
labeled_im, n = skimage.measure.label(im, return_num=True)

and then access ellipse number 6 for instance as:

el6 = np.where(labeled_im==6, im, 0)

In total you'll get labels 1 ... n , label 0 is the background.

(this is the image I copied from your question for testing:

在此处输入图像描述 )

To visualize the labeled ellipses:

import matplotlib.pyplot as plt
fig,ax=plt.subplots(3,5)
for i in range(n):
    ax.flat[i].imshow(np.where(labeled_im==i+1, im, 0))
    ax.flat[i].set_title(f"{i+1}")
    ax.flat[i].axis("off")
ax.flat[13].axis("off")
ax.flat[14].axis("off")

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM