旋转之后截取图像

1. prompt

请用python写程序:
1、输入一个-180180之间的整数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()  
  
    # 如果需要保存截取后的图像  
    # cv2.imwrite('cropped_image.jpg', cropped)  
  
# 示例使用  
image_path = 'path_to_your_image.jpg'  # 替换为您的图像文件路径  
angle = int(input("请输入一个-180到180之间的整数a: "))  
rotate_and_crop_image(image_path, angle)

相关推荐

  1. 旋转之后截取图像

    2024-06-06 00:02:02       8 阅读
  2. 旋转图像【矩阵】

    2024-06-06 00:02:02       39 阅读
  3. leetcode48. 旋转图像

    2024-06-06 00:02:02       17 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-06 00:02:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-06 00:02:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-06 00:02:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-06 00:02:02       20 阅读

热门阅读

  1. 服务器硬件基础知识

    2024-06-06 00:02:02       9 阅读
  2. 【Redis】本地锁和分布式锁的区别

    2024-06-06 00:02:02       8 阅读
  3. Kafka 请求处理揭秘:从入门到精通

    2024-06-06 00:02:02       9 阅读
  4. 如何发现并解决 Redis 热点 Key 问题

    2024-06-06 00:02:02       9 阅读
  5. 字幕转换: vtt转为srt

    2024-06-06 00:02:02       8 阅读
  6. 都可以写好后端接口

    2024-06-06 00:02:02       6 阅读
  7. 服务器环境搭建

    2024-06-06 00:02:02       9 阅读
  8. Sass详解

    2024-06-06 00:02:02       8 阅读
  9. React@16.x(19)事件的处理

    2024-06-06 00:02:02       11 阅读
  10. Mysql详解

    2024-06-06 00:02:02       10 阅读