如果直接套用PIL和OpenCV3图像处理库的旋转函数,旋转后保存的图像会留黑边,下面给出我实际测试后旋转图像不留黑边的代码:
Opencv3库代码
代码语言:javascript复制# 方法一:将图像向右旋转90度
file1 = 'E:/Kaggle Competiton/Humpback Whale Identification/train_fluke/w_0a0c768/aae1be7aaEDITED2.JPG'
img = cv2.imread(file1)
cv2.imshow("normal", img)
print('Before rotate image shape is',img.shape)
cv2.waitKey(0)
img90 = np.rot90(img, -1) # 对图像矩阵顺时针旋转90度
cv2.imshow("rotate", img90)
print('After rotate image shape is',img90.shape)
# cv2.imwrite(file1, img90) # 保存旋转后的图像
cv2.waitKey(0)
代码语言:javascript复制# 方法二:将图像向右旋转90度
file1 = 'E:/Kaggle Competiton/Humpback Whale Identification/train_fluke/w_0a0c768/aae1be7aaEDITED2.JPG'
img = cv2.imread(file1)
cv2.imshow("Before rotate 90 to the right", img)
print('Before rotate image shape is',img.shape)
cv2.waitKey(0)
img90 = cv2.flip(img, 0) # 垂直翻转图像
img90 = cv2.transpose(img90)# 转置图像
cv2.imshow("After rotate 90 to the right", img90)
print('After rotate image shape is',img90.shape)
# cv2.imwrite(file1, img90) # 保存旋转后的图像
cv2.waitKey(0)
程序运行结果:
PIL库代码
代码语言:javascript复制# 将图像转化为灰度图后向右旋转90度
file1 = 'E:/Kaggle Competiton/Humpback Whale Identification/train_fluke/w_0a0c768/aae1be7aaEDITED2.JPG'
img = pil_image.open(file1).convert('L')
img = np.asarray(img)
cv2.imshow("Before rotate 90 to the right", img)
print('Before rotate image shape is',img.shape)
cv2.waitKey(0)
img90 = cv2.flip(img, 0) # 垂直翻转图像
img90 = cv2.transpose(img90)# 转置图像
cv2.imshow("After rotate 90 to the right", img90)
print('After rotate image shape is',img90.shape)
# cv2.imwrite(file1, img90) # 保存旋转后的图像
cv2.waitKey(0)
程序运行后结果: