def rotate_image(img, angle, pivot):
pivot = pivot.astype(np.int32)
# double size of image while centering object
pads = [[img.shape[0] - pivot[0], pivot[0]], [img.shape[1] - pivot[1], pivot[1]]]
if len(img.shape) > 2:
pads.append([0, 0])
imgP = np.pad(img, pads, 'constant')
# reduce size of matrix to rotate around the object
if len(img.shape) > 2:
total_y = np.sum(imgP.any(axis=(0, 2))) * 2.4
total_x = np.sum(imgP.any(axis=(1, 2))) * 2.4
else:
total_y = np.sum(imgP.any(axis=0)) * 2.4
total_x = np.sum(imgP.any(axis=1)) * 2.4
cropy = int((imgP.shape[0] - total_y)/2)
cropx = int((imgP.shape[1] - total_x)/2)
imgP[cropy:-cropy, cropx:-cropx] = ndimage.rotate(imgP[cropy:-cropy, cropx:-cropx], angle,
reshape=False, prefilter=False)
return imgP[pads[0][0]: -pads[0][1], pads[1][0]: -pads[1][1]]
评论列表
文章目录