rrrrrrrrrrrrrrrr
rrrrrrrrrrrrrrrr

Reputation: 342

Rotating an image in OpenCV

I'm trying to write a Python function to crop, rotate and resize faces. It is for a facial recognition application. I pass the coordinates of the eyes to the function and the function processes the image (rotate it so the plane of the eyes is parallel to the horizontal axis of the image and scale/crop/resize it). The problem is that the faces are not rotating at all. They are only being cropped. The following function is modified to return both the rotated image and a copy of the image done before the rotation. They are identical.

def CropFace(image, eye_left=(0,0), eye_right=(0,0), offset_pct=(0.25,0.25), dest_sz = (250,250)):

    offset_h = math.floor(float(offset_pct[0])*dest_sz[0])
    offset_v = math.floor(float(offset_pct[1])*dest_sz[1])

    eye_direction = (eye_right[0] - eye_left[0], eye_right[1] - eye_left[1])

    rotation = -math.atan2(float(eye_direction[1]), float(eye_direction[0]))

    dist = Distance(eye_left, eye_right)

    reference = dest_sz[0] - 2.0*offset_h

    scale = float(dist) / float(reference)

    sz = image.shape
    if len(sz) > 2: sz = sz[:2]

    print rotation

    image2 = image.copy()

    mat = cv2.getRotationMatrix2D(eye_left, rotation, 1.0)
    result = cv2.warpAffine(image, mat, sz, flags = cv2.INTER_CUBIC)

    crop_xy = (eye_left[0] - scale*offset_h, eye_left[1] - scale*offset_v)
    crop_size = (dest_sz[0]*scale, dest_sz[1]*scale)
    result = result[int(crop_xy[1]):int(crop_xy[1]+crop_size[1]), int(crop_xy[0]):int(crop_xy[0]+crop_size[0])]
    image2 = image2[int(crop_xy[1]):int(crop_xy[1]+crop_size[1]), int(crop_xy[0]):int(crop_xy[0]+crop_size[0])]

    return (result, image2)

Upvotes: 1

Views: 3291

Answers (1)

beaker
beaker

Reputation: 16821

The problem is that for

cv2.getRotationMatrix2D(center, angle, scale)

the angle argument is in degrees (opencv documentation)

while Python,

angle = math.atan2(y, x)

returns the angle in radians. (Python documentation)

So the angle specified by rotation was in radians when OpenCV was expecting degrees.

Upvotes: 3

Related Questions