在OpenCV中旋转图像

时间:2014-09-30 10:07:48

标签: python opencv trigonometry

我正在尝试编写一个Python函数来裁剪,旋转和调整面的大小。它适用于面部识别应用程序。 我将眼睛的坐标传递给函数,并且函数处理图像(旋转它使得眼睛的平面平行于图像的水平轴并缩放/裁剪/调整它的大小)。 问题是面部根本不旋转。他们只是被裁剪。 修改以下功能以返回旋转图像和旋转前完成的图像副本。它们完全相同。

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)

1 个答案:

答案 0 :(得分:3)

问题在于

cv2.getRotationMatrix2D(center, angle, scale)

angle参数以度(opencv documentation

为单位

而Python,

angle = math.atan2(y, x)

以弧度为单位返回角度。 (Python documentation

因此,当OpenCV期望度数时,rotation指定的角度为弧度。