예제 #1
0
def ellipse(landmarks):
    face = np.array([m[0] for m in landmarks if 'contour_' in m[1]])
    data = [face[:, 0], face[:, 1]]
    lsqe = el.LSqEllipse()
    lsqe.fit(data)
    center, width, height, phi = lsqe.parameters()
    return [center[0], center[1], width, height, phi]
예제 #2
0
def proc_ellipse(fm, roi):
    """Process an image stencil to an ellipse fitted dataset.

    Flipping x,y axes for the image."""
    try:
        data = np.where(fm)
        lsqe = el.LSqEllipse()
        lsqe.fit(data)
        center, width, height, phi = lsqe.parameters()
        res = [center[1], center[0], width * 2, 2 * height, np.rad2deg(phi)]
        return res
    except Exception as e:
        raise FitError(e)
예제 #3
0
def fit_ellipse(pts):
    if pts.shape[0] >= 6:  # circle
        n = pts.shape[0]
        data = [pts[0:n - 1, 0], pts[0:n - 1, 1]]
        lsqe = ellipses.LSqEllipse()
        lsqe.fit(data)
        center, width, height, phi = lsqe.parameters()
        ellpts = cv2.ellipse2Poly((int(center[0]), int(center[1])),
                                  (int(width), int(height)),
                                  int(phi / 3.14159 * 180), 0, 360, 5)
        ellpts = np.append(ellpts, [[pts[n - 1, 0], pts[n - 1, 1]]], axis=0)
        return ellpts
    else:  # rectangle
        return pts
예제 #4
0
def ellipses(listasx,listasy):
    #listasx = lista de los puntos en x
    #listasy = lista de los puntos en y
    data = np.ones(len(listasx)-2)
    centros = np.ones((len(listasx)-2, 2))
    anchos = np.ones(len(listasx)-2)
    altos = np.ones(len(listasx)-2)
    angulos = np.ones(len(listasx)-2)

    for i in range(2,len(listasx)):
        data = [listasx[i],listasy[i]]
        lsqe = el.LSqEllipse()
        lsqe.fit(data)
        center, width, height, phi = lsqe.parameters()
        centros[i-2] = np.asanyarray(center)
        anchos[i-2] = width
        altos[i-2] = height
        angulos[i-2] = phi
    allD = [data, centros, anchos, altos, angulos]
    #retorna una lista de arreglos [(x,y),(xo.yo),[semi_mayor],[semi_menor],[ángulos]]
    return allD
예제 #5
0
def EllipseFit_LS(xy):
    lsqe = el.LSqEllipse()
    lsqe.fit([xy[:, 0], xy[:, 1]])
    if np.iscomplex(lsqe.width):
        print "WARN: COMPLEX"
        lsqe.width = np.nan
    if np.iscomplex(lsqe.height):
        print "WARN: COMPLEX"
        lsqe.height = np.nan
    if np.iscomplex(lsqe.phi):
        print "WARN: COMPLEX"
        lsqe.phi = np.nan
    if np.iscomplex(lsqe.center).any():
        print "WARN: COMPLEX"
        lsqe.center = np.array([np.nan, np.nan])
    # "width" and "height" are really half-width and half-height.
    smaja = np.max((lsqe.width, lsqe.height))
    smina = np.min((lsqe.width, lsqe.height))
    angle = lsqe.phi  # CCW angle b/t x-axis and "width"
    if smaja == lsqe.height:
        if angle <= 0:
            angle += np.pi / 2.
        else:
            angle -= np.pi / 2.
    angle *= 180 / np.pi
    # Assuming N-S is direction straight to river
    ls_width = 2 * (lsqe.width**2 * np.cos(np.pi / 2. - lsqe.phi)**2 +
                    lsqe.height**2 * np.sin(np.pi / 2. - lsqe.phi)**2)**.5
    ls_length = 2 * (lsqe.width**2 * np.sin(np.pi / 2. - lsqe.phi)**2 +
                     lsqe.height**2 * np.cos(np.pi / 2. - lsqe.phi)**2)**.5
    """
    if np.abs(angle) < np.pi/4.:
        width = 2 * lsqe.height # semi-minor axis
    else:
        width = 2 * lsqe.width # semi-major axis
    """
    return lsqe.center[0], lsqe.center[1], smaja, smina, angle, ls_width, \
           ls_length
예제 #6
0
            load_dict = json.load(load_f)
        img = cv2.imread(os.path.join(root, load_dict["imagePath"]))
        if img is None:
            print('image file does not exist')
        ih, iw, ic = img.shape
        smallImg = cv2.resize(
            img,
            (int(img.shape[1] / show_scale), int(img.shape[0] / show_scale)))
        objectNum = len(load_dict['shapes'])
        for i, shape in enumerate(load_dict['shapes']):
            pts = np.array(shape['points'])

            if pts.shape[0] >= 6:  # circle
                n = pts.shape[0]
                data = [pts[0:n - 1, 0], pts[0:n - 1, 1]]
                lsqe = ellipses.LSqEllipse()
                lsqe.fit(data)
                center, width, height, phi = lsqe.parameters()
                cv2.ellipse(smallImg, (int(center[0]), int(center[1])),
                            (int(width), int(height)), phi / 3.14159 * 180, 0,
                            360, (255, 0, 0), 2)
                ellpts = cv2.ellipse2Poly((int(center[0]), int(center[1])),
                                          (int(width), int(height)),
                                          int(phi / 3.14159 * 180), 0, 360, 5)
                ellpts = np.append(ellpts, [[pts[n - 1, 0], pts[n - 1, 1]]],
                                   axis=0)
                x2, y2 = np.max(ellpts, 0)
                x1, y1 = np.min(ellpts, 0)

            else:  # rectangle
                x2, y2 = np.max(pts, 0)
예제 #7
0
import ellipses as el
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

data = el.make_test_ellipse()

lsqe = el.LSqEllipse()
lsqe.fit(data)
center, width, height, phi = lsqe.parameters()

plt.close('all')
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111)
ax.axis('equal')
ax.plot(data[0], data[1], 'ro', label='test data', zorder=1)

ellipse = Ellipse(xy=center,
                  width=2 * width,
                  height=2 * height,
                  angle=np.rad2deg(phi),
                  edgecolor='b',
                  fc='None',
                  lw=2,
                  label='Fit',
                  zorder=2)

ax.add_patch(ellipse)

plt.legend()
plt.show()
예제 #8
0
    def callback(self, data):
        try:
            cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8")
        except CvBridgeError as e:
            print(e)

        #ROI cordinates
        y = 0
        x = 275
        h = 225
        w = 225
        crop_frame = cv_image[y:y + h, x:x + w]
        yellow_pix = 0
        #cv2.imshow('frame',crop_frame)
        #find the object (yellow) (not needed for pipline)
        # hsv_obj = cv2.cvtColor(crop_frame, cv2.COLOR_BGR2HSV)
        # lower_yellow = np.array([20,100,100]) #cvScalar(20, 100, 100), cvScalar(30, 255, 255)
        # upper_yellow = np.array([30,255,255])
        # mask_obj = cv2.inRange(hsv_obj, lower_yellow, upper_yellow)

        # res_obj = cv2.bitwise_and(crop_frame,crop_frame, mask= mask_obj)

        #find the shirt (white)
        hsv_shirt = cv2.cvtColor(crop_frame, cv2.COLOR_BGR2HSV)
        lower_white = np.array([0, 0, 160])
        upper_white = np.array([255, 25, 255])
        lower_yellow = np.array(
            [20, 100, 100])  #cvScalar(20, 100, 100), cvScalar(30, 255, 255)
        upper_yellow = np.array([30, 255, 255])

        mask_shirt = cv2.inRange(hsv_shirt, lower_white, upper_white)
        kernel = np.ones((3, 3), np.uint8)
        opening = cv2.morphologyEx(mask_shirt, cv2.MORPH_OPEN, kernel)
        #morphological opening to get rid of outlyer pixels
        res_shirt = cv2.bitwise_and(crop_frame, crop_frame, mask=opening)
        # fitt pixles in leastsquare ellipse format
        datax = []
        datay = []
        for x in range(np.array(opening).shape[0]):
            for y in range(np.array(opening).shape[0]):
                if (opening[x, y] == 255):
                    datax.append(x)
                    datay.append(y)
        data = []
        data.append(datax)
        data.append(datay)

        # debug
        # cv2.imshow('frame',crop_frame)
        # cv2.imshow('obj',res_obj)
        # cv2.imshow('shirt',opening)

        #do least square from: https://github.com/bdhammel/least-squares-ellipse-fitting
        #try:
        if (len(datax) > 0):
            lsqe = el.LSqEllipse()
            lsqe.fit(data)
            center, width, height, phi = lsqe.parameters()

            #add the ellipse to the crop_frame
            cv2.ellipse(crop_frame, (int(center[1]), int(center[0])),
                        (int(height), int(width)), np.rad2deg(-phi), 0, 360,
                        255, 5)
            #debug
            #cv2.ellipse(opening,(int(center[1]),int(center[0])),(int(height),int(width)),np.rad2deg(-phi),0,360,255,5)

            #get the insifde of ellipse mask
            e_mask = np.ones((w, h)) * 0
            e_mask = e_mask.astype('uint8')
            cv2.ellipse(e_mask, (int(center[1]), int(center[0])),
                        (int(height), int(width)), np.rad2deg(-phi), 0, 360,
                        255, -1)

            #filter
            res_elipse = cv2.bitwise_and(crop_frame, crop_frame, mask=e_mask)
            res_elipse_hsv_obj = cv2.cvtColor(res_elipse, cv2.COLOR_BGR2HSV)
            mask_obj_ellipse = cv2.inRange(res_elipse_hsv_obj, lower_yellow,
                                           upper_yellow)
            #count yellow pixels inside ellipse
            yellow_pix = cv2.countNonZero(mask_obj_ellipse)

            #add information to vision screen
            font = cv2.FONT_HERSHEY_SIMPLEX
            cv2.putText(crop_frame, str(yellow_pix), (10, 50), font, 1,
                        (255, 255, 255), 2, cv2.LINE_AA)
        else:
            font = cv2.FONT_HERSHEY_SIMPLEX
            cv2.putText(crop_frame, str(0), (10, 50), font, 1, (255, 255, 255),
                        2, cv2.LINE_AA)

            # Display the resulting frame (debug mode)
            #cv2.imshow('frame',crop_frame)
            #cv2.imshow('obj',res_obj)
            #cv2.imshow('shirt',opening)
            #cv2.imshow('emask',res_elipse)
            #cv2.imshow('mask_yellow_ellipse',mask_obj_ellipse)
            #if cv2.waitKey(1) & 0xFF == ord('q'):
            #    break
        #except:
        #    print("ERROR")

        # (rows,cols,channels) = cv_image.shape
        # if cols > 60 and rows > 60 :
        #   cv2.circle(cv_image, (50,50), 10, 255)
        # cv2.imshow("Image window", cv_image)
        # cv2.waitKey(3)

        try:
            self.image_pub.publish(
                self.bridge.cv2_to_imgmsg(crop_frame, "bgr8"))
            self.area_pub.publish(yellow_pix)
        except CvBridgeError as e:
            print(e)