Python程序教程

您现在的位置是:首页 >  Python

当前栏目

Python如何将图像向右旋转90度

Python,如何,图像,旋转,90
2025-04-01 16:27:50 时间

如果直接套用PIL和OpenCV3图像处理库的旋转函数,旋转后保存的图像会留黑边,下面给出我实际测试后旋转图像不留黑边的代码:

Opencv3库代码

# 方法一:将图像向右旋转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)
# 方法二:将图像向右旋转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库代码

# 将图像转化为灰度图后向右旋转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)

程序运行后结果: