def rotate_image(img, angle, interp=cv2.INTER_LINEAR):
rows, cols = img.shape[:2]
rotation_matrix = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle, 1)
return cv2.warpAffine(img, rotation_matrix, (cols, rows), flags=interp)
python类getRotationMatrix2D()的实例源码
def DetectEyes(Image):
Theta = 0
rows, cols = Image.shape
glass = glass_cas.detectMultiScale(Image) # This ditects the eyes
for (sx, sy, sw, sh) in glass:
if glass.shape[0] == 2: # The Image should have 2 eyes
if glass[1][0] > glass[0][0]:
DY = ((glass[1][1] + glass[1][3] / 2) - (glass[0][1] + glass[0][3] / 2)) # Height difference between the glass
DX = ((glass[1][0] + glass[1][2] / 2) - glass[0][0] + (glass[0][2] / 2)) # Width difference between the glass
else:
DY = (-(glass[1][1] + glass[1][3] / 2) + (glass[0][1] + glass[0][3] / 2)) # Height difference between the glass
DX = (-(glass[1][0] + glass[1][2] / 2) + glass[0][0] + (glass[0][2] / 2)) # Width difference between the glass
if (DX != 0.0) and (DY != 0.0): # Make sure the the change happens only if there is an angle
Theta = math.degrees(math.atan(round(float(DY) / float(DX), 2))) # Find the Angle
print "Theta " + str(Theta)
M = cv2.getRotationMatrix2D((cols / 2, rows / 2), Theta, 1) # Find the Rotation Matrix
Image = cv2.warpAffine(Image, M, (cols, rows))
# cv2.imshow('ROTATED', Image) # UNCOMMENT IF YOU WANT TO SEE THE
Face2 = face.detectMultiScale(Image, 1.3, 5) # This detects a face in the image
for (FaceX, FaceY, FaceWidth, FaceHeight) in Face2:
CroppedFace = Image[FaceY: FaceY + FaceHeight, FaceX: FaceX + FaceWidth]
return CroppedFace
def im_rotate(im, landmark):
"""Rotate the image according to the angle of two eyes.
Args:
landmark: 5 points, left_eye, right_eye, nose, leftmouth, right_mouth
im: image matrix
Returns:
A rotated image matrix.
Rotated angle.
Rotated landmark points.
"""
ang = math.atan2(landmark[3] - landmark[1], landmark[2] - landmark[0])
angle = ang / math.pi * 180
center = tuple(np.array((im.shape[1] / 2.0, im.shape[0] / 2.0)))
scale = 1.0
rot_mat = cv2.getRotationMatrix2D(center, angle, scale)
dst = cv2.warpAffine(im, rot_mat, (im.shape[1], im.shape[0]))
# rotate 5 landmark points
left_eye = point_trans(landmark[0:2], -ang, im.shape, im.shape)
right_eye = point_trans(landmark[2:4], -ang, im.shape, im.shape)
nose = point_trans(landmark[4:6], -ang, im.shape, im.shape)
left_mouth = point_trans(landmark[6:8], -ang, im.shape, im.shape)
right_mouth = point_trans(landmark[8:10], -ang, im.shape, im.shape)
n_landmark = np.concatenate([left_eye, right_eye, nose, left_mouth, right_mouth])
return dst, ang, n_landmark
def rotate(image, angle, center = None, scale = 1.0):
(h, w) = image.shape[:2]
if center is None:
center = (w / 2, h / 2)
# Perform the rotation
M = cv2.getRotationMatrix2D(center, angle, scale)
rotated = cv2.warpAffine(image, M, (w, h))
return rotated
def dumpRotateImage(img,degree,pt1,pt2,pt3,pt4):
height,width=img.shape[:2]
heightNew = int(width * fabs(sin(radians(degree))) + height * fabs(cos(radians(degree))))
widthNew = int(height * fabs(sin(radians(degree))) + width * fabs(cos(radians(degree))))
matRotation=cv2.getRotationMatrix2D((width/2,height/2),degree,1)
matRotation[0, 2] += (widthNew - width) / 2
matRotation[1, 2] += (heightNew - height) / 2
imgRotation = cv2.warpAffine(img, matRotation, (widthNew, heightNew), borderValue=(255, 255, 255))
pt1 = list(pt1)
pt3 = list(pt3)
[[pt1[0]], [pt1[1]]] = np.dot(matRotation, np.array([[pt1[0]], [pt1[1]], [1]]))
[[pt3[0]], [pt3[1]]] = np.dot(matRotation, np.array([[pt3[0]], [pt3[1]], [1]]))
imgOut=imgRotation[int(pt1[1]):int(pt3[1]),int(pt1[0]):int(pt3[0])]
height,width=imgOut.shape[:2]
return imgOut
def rotateImage(image, angle, center=None, scale=1.0):
h, w = image.shape[:2]
if center is None:
center = (w / 2, h / 2)
rot_mat = cv2.getRotationMatrix2D(center, angle, scale)
result = cv2.warpAffine(image, rot_mat, (w, h), flags=cv2.INTER_CUBIC)
return result
def rotate_image(self, image, angle):
image_center = tuple(np.array(image.shape) / 2)
rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
result = cv2.warpAffine(
image,
rot_mat,
image.shape,
flags=cv2.INTER_LINEAR)
return result
def random_rotate(image):
cols = image.shape[1]
rows = image.shape[0]
mean_color = np.mean(image, axis=(0, 1))
angle = random.uniform(0, 90)
M = cv2.getRotationMatrix2D((cols / 2, rows / 2), angle, 1)
if random.randint(0, 1) == 1:
dst = cv2.warpAffine(image, M, (cols, rows), borderValue=mean_color, borderMode=cv2.BORDER_REFLECT)
else:
dst = cv2.warpAffine(image, M, (cols, rows), borderValue=mean_color)
return dst
def augment_with_params(self, Xb, shift_x, shift_y, rotation, random_flip, zoom, hue, saturation, value):
# Define affine matrix
# TODO: Should be able to incorporate flips directly instead of through an extra call
M = cv2.getRotationMatrix2D((self.center_shift[0], self.center_shift[1]), rotation, zoom)
M[0, 2] += shift_x
M[1, 2] += shift_y
augment_partial = partial(augment_image,
M=M,
random_flip=random_flip,
random_hue=hue,
random_saturation=saturation,
random_value=value)
if self.multiprocess:
l = self.pool.map(augment_partial, Xb)
Xbb = np.array(l)
else:
Xbb = np.zeros(Xb.shape, dtype=np.float32)
for i in xrange(Xb.shape[0]):
Xbb[i] = augment_partial(Xb[i])
return Xbb
# Augments a single image, singled out for easier profiling
def rotate(image, theta):
(h, w) = image.shape[:2]
center = (w / 2, h / 2)
M = cv2.getRotationMatrix2D(center, theta, 1)
rotated = cv2.warpAffine(image, M, (int(w), int(h)), cv2.INTER_LINEAR,
borderMode=cv2.BORDER_CONSTANT, borderValue=(255, 255, 255))
return rotated
def pose_rotation(meta):
deg = random.uniform(-40.0, 40.0)
img = meta.img
center = (img.shape[1] * 0.5, img.shape[0] * 0.5)
rot_m = cv2.getRotationMatrix2D((center[0] - 0.5, center[1] - 0.5), deg, 1)
ret = cv2.warpAffine(img, rot_m, img.shape[1::-1], flags=cv2.INTER_AREA, borderMode=cv2.BORDER_CONSTANT)
if img.ndim == 3 and ret.ndim == 2:
ret = ret[:, :, np.newaxis]
neww, newh = RotationAndCropValid.largest_rotated_rect(ret.shape[1], ret.shape[0], deg)
neww = min(neww, ret.shape[1])
newh = min(newh, ret.shape[0])
newx = int(center[0] - neww * 0.5)
newy = int(center[1] - newh * 0.5)
# print(ret.shape, deg, newx, newy, neww, newh)
img = ret[newy:newy + newh, newx:newx + neww]
# adjust meta data
adjust_joint_list = []
for joint in meta.joint_list:
adjust_joint = []
for point in joint:
if point[0] < -100 or point[1] < -100:
adjust_joint.append((-1000, -1000))
continue
# if point[0] <= 0 or point[1] <= 0:
# adjust_joint.append((-1, -1))
# continue
x, y = _rotate_coord((meta.width, meta.height), (newx, newy), point, deg)
adjust_joint.append((x, y))
adjust_joint_list.append(adjust_joint)
meta.joint_list = adjust_joint_list
meta.width, meta.height = neww, newh
meta.img = img
return meta
def rotate(image, angle, center = None, scale = 1.0):
# Grab the dimensions of the image
(h, w) = image.shape[:2]
# If the center is None, initialize it as the center of
# the image
if center is None:
center = (w / 2, h / 2)
# Perform the rotation
M = cv2.getRotationMatrix2D(center, angle, scale)
rotated = cv2.warpAffine(image, M, (w, h))
# Return the rotated image
return rotated
def rotate(image, angle):
(h, w) = image.shape[:2]
(cX, cY) = (w // 2, h // 2)
M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))
M[0, 2] += (nW / 2) - cX
M[1, 2] += (nH / 2) - cY
return cv2.warpAffine(image, M, (nW, nH))
def rotate(image, angle, interpolation=cv2.INTER_CUBIC,
borderMode=cv2.BORDER_REFLECT, borderValue=0):
'''
angle [deg]
'''
s0, s1 = image.shape
image_center = (s0 - 1) / 2., (s1 - 1) / 2.
rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
result = cv2.warpAffine(image, rot_mat, image.shape,
flags=interpolation, borderMode=borderMode,
borderValue=borderValue)
return result
def _rotate(img, angle):
'''
angle [DEG]
'''
s = img.shape
if angle == 0:
return img
else:
M = cv2.getRotationMatrix2D((s[1] // 2,
s[0] // 2), angle, 1)
return cv2.warpAffine(img, M, (s[1], s[0]))
def skew(img):
"""
This function detects skew in images. It turn the image so that the baseline of image is straight.
:param img: the image
:return: rotated image
"""
# coordinates of bottom black pixel in every column
black_pix = np.zeros((2, 1))
# Look at image column wise and in every column from bottom to top pixel. It stores the location of the first black
# pixel in every column
for columns in range(img.shape[1]):
for pixel in np.arange(img.shape[0]-1, -1, -1):
if img[pixel][columns] == 255:
black_pix = np.concatenate((black_pix, np.array([[pixel], [columns]])), axis=1)
break
# Calculate linear regression to detect baseline
mean_x = np.mean(black_pix[1][:])
mean_y = np.mean(black_pix[0][:])
k = black_pix.shape[1]
a = (np.sum(black_pix[1][:] * black_pix[0][:]) - k * mean_x * mean_y) / (np.sum(black_pix[1][:] * black_pix[1][:]) - k * mean_x * mean_x)
# Calculate angle by looking at gradient of linear function + data augmentation
angle = np.arctan(a) * 180 / np.pi #+ random.uniform(-1, 1) #TODO dataug
# Rotate image and use Nearest Neighbour for interpolation of pixel
rows, cols = img.shape
M = cv.getRotationMatrix2D((cols / 2, rows / 2), angle, 1)
img_rot = cv.warpAffine(img, M, (cols, rows), flags=cv.INTER_NEAREST)
return img_rot
def skew(img):
"""
This function detects skew in images. It turns the image so that the baseline of image is straight.
:param img: the image
:return: rotated image
"""
# coordinates of bottom black pixel in every column
black_pix = np.zeros((2, 1))
# Look at image column wise and in every column from bottom to top pixel. It stores the location of the first black
# pixel in every column
for columns in range(img.shape[1]):
for pixel in np.arange(img.shape[0]-1, -1, -1):
if img[pixel][columns] == 255:
black_pix = np.concatenate((black_pix, np.array([[pixel], [columns]])), axis=1)
break
# Calculate linear regression to detect baseline
mean_x = np.mean(black_pix[1][:])
mean_y = np.mean(black_pix[0][:])
k = black_pix.shape[1]
a = (np.sum(black_pix[1][:] * black_pix[0][:]) - k * mean_x * mean_y) / (np.sum(black_pix[1][:] * black_pix[1][:]) - k * mean_x * mean_x)
# Calculate angle by looking at gradient of linear function + data augmentation
angle = np.arctan(a) * 180 / np.pi + random.uniform(-0.5, 0.5) #TODO dataug
# Rotate image and use Nearest Neighbour for interpolation of pixel
rows, cols = img.shape
M = cv.getRotationMatrix2D((cols / 2, rows / 2), angle, 1)
img_rot = cv.warpAffine(img, M, (cols, rows), flags=cv.INTER_NEAREST)
return img_rot
def rotate(image, angles=DEFAULT_ANGLES):
rotated = []
for angle in angles:
center = tuple(np.array(image.shape[:2]) / 2)
R = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated_image = cv2.warpAffine(image, R, image.shape[:2], flags=cv2.INTER_CUBIC)
rotated.append(rotated_image)
return rotated
def rotateImg(img, deg):
h, w = img.shape[:2]
M = cv2.getRotationMatrix2D((w / 2, h / 2), deg, 1.0)
rotated_img = cv2.warpAffine(img, M, (w, h))
return rotated_img
def rotate_image(img, radians):
(rows, cols, channels) = img.shape
degrees = math.degrees(radians)
M = cv2.getRotationMatrix2D((cols/2, rows/2), degrees, 1)
return cv2.warpAffine(img, M, (cols, rows))