Python+CV2实现黑色背景的旋转图片矫正回水平图片

目  录

一、思路

二、代码

三、效果


参考 https://blog.csdn.net/weixin_42259833/article/details/124398342

一、思路

因为黑色背景且旋转图片为矩形,找最长直线,计算直线角度,图片旋转,去掉多余黑色区域。

二、代码

import cv2
import numpy as np
import math

def get_long_line(img):
    C = cv2.Canny(cv2.cvtColor(img, cv2.COLOR_BGR2HSV), 10, 200, apertureSize=3)  # 边缘检测 #10
    lines = cv2.HoughLines(C, 1, np.pi / 180, 20)  # 直线检测
    # 滤波
    img = cv2.blur(img, (3, 3))  # 5,5
    img = cv2.medianBlur(img, 5)
    for line in lines:
        rho = line[0][0]  # 第一个元素是距离rho
        theta = line[0][1]  # 第二个元素是角度theta
        if (theta < (np.pi / 4.)) or (theta > (3. * np.pi / 4.0)):  # 垂直直线
            pt1 = (int(rho / np.cos(theta)) + 490, 0 + 372)  # 该直线与第一行的交点
            # 该直线与最后一行的焦点
            pt2 = (int((rho - img.shape[0] * np.sin(theta)) / np.cos(theta)) + 490, img.shape[0] + 372)
        else:  # 水平直线
            pt1 = (0, int(rho / np.sin(theta)))  # 该直线与第一列的交点
            # 该直线与最后一列的交点
            pt2 = (img.shape[1], int((rho - img.shape[1] * np.cos(theta)) / np.sin(theta)))
        return (pt1, pt2)
    pass

# 读取照片
L = cv2.imread('3.png')  # queryImage
# 高斯滤波
L = cv2.GaussianBlur(L, (3, 3), 1)
#获取最长直线
pt1, pt2 = get_long_line(L)
angle = 90-math.degrees(math.atan2(pt2[0]-pt1[0], pt2[1]-pt1[1]))
#图片旋转
rows,cols=L.shape[:2]
rotation_matrix=cv2.getRotationMatrix2D((cols//2,rows//2),angle,1)
image_rotation_0=cv2.warpAffine(L,rotation_matrix,(cols,rows))
# 得到新的位置
rows, cols = np.where(image_rotation_0[:, :, 0] != 0)
min_row, max_row = min(rows)+1, max(rows)-1
min_col, max_col = min(cols)+1, max(cols)-1
# 去除黑色无用部分
image_rotation_0 = image_rotation_0[min_row:max_row, min_col:max_col, :]

#图片显示
cv2.line(L, pt1, pt2,(0,0,255) , 2)  # 绘制一条蓝线
cv2.imshow('a',L)
cv2.imshow('B',image_rotation_0)
cv2.waitKey(0)
cv2.destroyAllWindows()

三、效果

*原图的最长直线

*校正后效果 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值