1. prompt
请用python写程序:
1、输入一个-180到180之间的整数a
2、在当前图片内截取一个矩形
3、矩形相对于原始图像旋转角度为a
4、输出该矩形内的图片
2. 实现代码
import cv2
import numpy as np
def rotate_and_crop_image(image_path, angle):
image = cv2.imread(image_path)
if image is None:
raise FileNotFoundError("无法找到或读取图像文件。")
(h, w) = image.shape[:2]
rect_x = w // 4
rect_y = h // 4
rect_width = w // 2
rect_height = h // 2
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image, M, (w, h))
rotated_rect_x = rect_x - center[0] + w // 2
rotated_rect_y = rect_y - center[1] + h // 2
rotated_rect_x = max(0, rotated_rect_x)
rotated_rect_y = max(0, rotated_rect_y)
rotated_rect_width = min(rect_width, w - rotated_rect_x)
rotated_rect_height = min(rect_height, h - rotated_rect_y)
cropped = rotated[rotated_rect_y:rotated_rect_y+rotated_rect_height, rotated_rect_x:rotated_rect_x+rotated_rect_width]
cv2.imshow("Original Image", image)
cv2.imshow("Rotated and Cropped Image", cropped)
cv2.waitKey(0)
cv2.destroyAllWindows()
image_path = 'path_to_your_image.jpg'
angle = int(input("请输入一个-180到180之间的整数a: "))
rotate_and_crop_image(image_path, angle)