You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何复原旋转后带黑边的图像并去除黑边?

解决方法

要将带黑边的旋转图像恢复为原角度并去除黑边,可按以下步骤操作:

步骤1:读取旋转后的图像

首先读取带有黑边的旋转图像,使用OpenCV的cv2.imread()方法加载文件。

步骤2:旋转回原角度

调用你已有的rotate_image函数,将图像旋转**-35度**(与之前的旋转角度方向相反),此时图像内容会回到原始方向,但仍保留四周黑边。

步骤3:裁剪去除黑边

通过识别图像中的非黑像素区域,确定有效内容的边界,然后裁剪掉四周的黑边:

  • 将图像转为灰度图,简化阈值处理逻辑
  • 用二值化操作分离黑边(像素值为0)与有效内容(非0像素)
  • 定位非零像素的最小/最大行、列坐标,锁定有效区域范围
  • 对旋转后的图像执行裁剪,得到无黑边的原始内容

完整代码示例

import cv2
import numpy as np

def rotate_image(mat, angle):
    """
    Rotates an image (angle in degrees) and expands image to avoid cropping
    """
    height, width = mat.shape[:2] 
    image_center = (width/2, height/2) 

    rotation_mat = cv2.getRotationMatrix2D(image_center, angle, 1.)

    abs_cos = abs(rotation_mat[0,0]) 
    abs_sin = abs(rotation_mat[0,1])

    bound_w = int(height * abs_sin + width * abs_cos)
    bound_h = int(height * abs_cos + width * abs_sin)

    rotation_mat[0, 2] += bound_w/2 - image_center[0]
    rotation_mat[1, 2] += bound_h/2 - image_center[1]

    rotated_mat = cv2.warpAffine(mat, rotation_mat, (bound_w, bound_h))
    return rotated_mat

# 读取带黑边的旋转图像
rotated_img = cv2.imread("lenarot.jpg")

# 旋转回原角度(-35度)
rotated_back = rotate_image(rotated_img, -35)

# 裁剪黑边
gray = cv2.cvtColor(rotated_back, cv2.COLOR_BGR2GRAY)
# 二值化分离黑边与有效内容
_, thresh = cv2.threshold(gray, 1, 255, cv2.THRESH_BINARY)
# 定位非零像素的边界坐标
non_zero = np.where(thresh != 0)
y_min, y_max = np.min(non_zero[0]), np.max(non_zero[0])
x_min, x_max = np.min(non_zero[1]), np.max(non_zero[1])
# 执行裁剪
cropped_img = rotated_back[y_min:y_max+1, x_min:x_max+1]

# 保存恢复后的图像
cv2.imwrite("recovered_lena.jpg", cropped_img)

代码说明

  • 复用你原有的rotate_image函数,保证逆变换的坐标逻辑一致性
  • 二值化阈值设为1,是因为黑边像素值为0,有效内容的像素值至少为1
  • 通过np.where精准定位有效区域边界,确保裁剪后的图像仅保留原始内容

内容的提问来源于stack exchange,提问作者Katerina T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 14:35:16