Python对图像进行旋转,旋转后图像大小不变
时间: 2024-05-07 15:23:02 浏览: 11
要实现图像旋转后大小不变,可以使用OpenCV库中的函数cv2.warpAffine()。该函数可以对图像进行仿射变换,包括旋转、平移、缩放等操作。以下是一个示例代码:
```python
import cv2
# 读取图像
img = cv2.imread('image.jpg')
# 获取图像中心点坐标
height, width = img.shape[:2]
center = (width/2, height/2)
# 设置旋转角度和缩放比例
angle = 45
scale = 1
# 计算变换矩阵
M = cv2.getRotationMatrix2D(center, angle, scale)
# 进行仿射变换
img_rotated = cv2.warpAffine(img, M, (width, height))
# 显示旋转后的图像
cv2.imshow('Rotated Image', img_rotated)
cv2.waitKey(0)
```
其中,cv2.getRotationMatrix2D()函数用于计算变换矩阵,参数包括旋转中心点、旋转角度和缩放比例;cv2.warpAffine()函数用于对图像进行仿射变换,参数包括变换矩阵和输出图像大小。
相关问题
python使用cv2库旋转图像,保持图像大小不变
可以使用cv2.warpAffine函数来实现图像旋转,同时保持图像大小不变。具体的实现步骤如下:
1. 计算图像中心点坐标
```python
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
```
2. 构造旋转矩阵
```python
M = cv2.getRotationMatrix2D(center, angle, scale=1.0)
```
其中,angle是旋转角度,scale是缩放比例(默认为1.0)。
3. 对图像进行旋转
```python
rotated = cv2.warpAffine(image, M, (w, h))
```
这里的输出rotated即为旋转后的图像,它的大小与原图像相同。
完整代码如下:
```python
import cv2
# 加载图像
image = cv2.imread("image.jpg")
# 计算中心点坐标
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
# 构造旋转矩阵
angle = 45
M = cv2.getRotationMatrix2D(center, angle, scale=1.0)
# 对图像进行旋转
rotated = cv2.warpAffine(image, M, (w, h))
# 显示旋转后的图像
cv2.imshow("Rotated Image", rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
写入多张dicom图片,对图片进行刚性旋转并保持tag不变,用python解决
可以使用Python中的pydicom库来对DICOM图像进行读取、编辑和写入操作。下面是一段示例代码,首先读取多个DICOM图像,进行旋转并保存为新的DICOM文件:
```python
import pydicom
import numpy as np
def rotate_dicom(dicom_file_path, angle):
# Load DICOM file
ds = pydicom.dcmread(dicom_file_path)
# Get the image data as a numpy array
img = ds.pixel_array
# Rotate the image using numpy
img_rotated = np.rot90(img, k=angle//90)
# Update the image pixel data in the DICOM dataset
ds.PixelData = img_rotated.tobytes()
# Adjust the image orientation and position information
ds.ImageOrientationPatient = ds.ImageOrientationPatient[-2:] + ds.ImageOrientationPatient[:2]
ds.ImagePositionPatient = ds.ImagePositionPatient[-1::-1]
# Update the DICOM tag for the rotation angle
ds[0x0020, 0x0037] = ''.join(['[', str(np.cos(np.radians(angle))), '\\', str(-np.sin(np.radians(angle))), '\\0\\',
str(np.sin(np.radians(angle))), '\\', str(np.cos(np.radians(angle))), '\\0]'])
# Save the rotated DICOM file
ds.save_as(dicom_file_path.replace('.dcm', '_rotated.dcm'))
# Example usage
dicom_files = ['image1.dcm', 'image2.dcm', 'image3.dcm']
for file in dicom_files:
rotate_dicom(file, 90)
```
这段代码中,我定义了一个rotate_dicom函数,它接受一个DICOM文件路径和旋转角度作为输入。首先,它使用pydicom库中的dcmread函数加载DICOM文件并获取像素数组。然后,它使用numpy库旋转图像数组,并更新DICOM数据集中的像素数据。接下来,它使用DICOM标签更新图像的定位和方向信息以及旋转角度。最后,它使用save_as函数将旋转后的图像保存为新的DICOM文件。在示例中,函数被循环调用以对多个DICOM文件进行操作。