import os
import cv2
import numpy as np
def opencv_rotate(img, angle):
"""
图片旋转,默认应该是逆时针转动
:param img:
:param angle:
:return:
"""
h, w = img.shape[:2] # 图像的(行数,列数,色彩通道数)
borderValue = (0, 0, 0, 0)
# 颜色空间转换?
if img.shape[-1] == 3:
img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
elif img.shape[-1] == 1:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
center = (w / 2, h / 2)
scale = 1.0
# cv2.getRotationMatrix2D(获得仿射变化矩阵)
M = cv2.getRotationMatrix2D(center, angle, scale)
# 2.2 新的宽高,radians(angle) 把角度转为弧度 sin(弧度)
new_H = int(
w * np.fabs(np.sin(np.radians(angle))) + h * np.fabs(np.cos(np.radians(angle)))
)
new_W = int(
h * np.fabs(np.sin(np.radians(angle))) + w * np.fabs(np.cos(np.radians(angle)))
)
# 2.3 平移
M[0, 2] += (new_W - w) / 2
M[1, 2] += (new_H - h) / 2
# cv2.warpAffine(进行仿射变化)
rotate = cv2.warpAffine(img, M, (new_W, new_H), borderValue=borderValue)
return rotate
import cv2
def img_resize(image, width_new, height_new):
""""""
height, width = image.shape[0], image.shape[1]
# 判断图片的长宽比率
if width / height >= width_new / height_new:
img_new = cv2.resize(image, (width_new, int(height * width_new / width)))
else:
img_new = cv2.resize(image, (int(width * height_new / height), height_new))
return img_new
if __name__ == "__main__":
now_path = os.getcwd()
print(f"now_path = {now_path}")
# file_name = 'xiaowei.png'
file_name = '000000.png'
origin_local_path = os.path.join(now_path, file_name) # 原图
print(f"origin_local_path = {origin_local_path}")
resize_local_path = os.path.join(now_path, f"resize_{file_name}") # 重置后图片
print(f"resize_local_path = {resize_local_path}")
rotation_local_path = os.path.join(now_path, f"rotation_{file_name}") # 旋转后图片
print(f"rotation_local_path = {rotation_local_path}")
img = cv2.imread(origin_local_path)
# 显示图片查看
# cv2.imshow('imshow', img)
# cv2.waitKey(1)
# cv2.destroyAllWindows()
# 显示图片查看
# 重置大小
print(f"重置大小")
w, h = 200, 200
img_new = img_resize(img, w, h)
cv2.imwrite(resize_local_path, img_new)
# print(img_new.shape)
# cv2.imshow('win', img_new)
# cv2.waitKey(0)
# 旋转
print(f"旋转")
# img_new = cv2.imread(resize_local_path)
angle = -45
res = opencv_rotate(img_new, angle)
cv2.imwrite(rotation_local_path, res)
print(f"---end---")
python opencv 重置图片大小,旋转图片
最新推荐文章于 2025-05-08 15:30:42 发布
这篇博客介绍了如何使用Python的OpenCV库进行图片旋转和重置大小的操作。首先,定义了`opencv_rotate`函数,它接受图片和旋转角度作为参数,通过`getRotationMatrix2D`和`warpAffine`函数实现图片旋转。然后,`img_resize`函数用于调整图片尺寸,根据图片的长宽比使用`resize`函数进行重置。在主函数中,这两个函数被应用到实际图片上,分别保存了旋转和重置大小后的图片。
1万+

被折叠的 条评论
为什么被折叠?



