opencv轮廓检测+最小外接矩形

# -*- coding: utf-8 -*-
import cv2
import numpy as np
def Gray_img(src):
    gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)


    return gray

def threshold_img(src):
    ret, binary = cv2.threshold(src, 20, 255, cv2.THRESH_BINARY)

    return binary

imagepath = '/home/tao/1.jpg'
def rorate(imagepath):
    img = cv2.imread(imagepath)
    #image, contours, _ = cv2.findContours(img, 2, 2)
    gray_img = Gray_img(img)
    tresh_img = threshold_img(gray_img)
    im2, contours, hierarchy = cv2.findContours(tresh_img, cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_SIMPLE)
    for cnt in contours:

        # 最小外界矩形的宽度和高度
        width, height = cv2.minAreaRect(cnt)[1]
        if width* height > 100:
            # 最小的外接矩形
            rect = cv2.minAreaRect(cnt)
            box = cv2.boxPoints(rect)  # 获取最小外接矩形的4个顶点
            box = np.int0(box)
            #cv2.drawContours(img, [box], 0, (255, 0, 255), 2)
            if 0 not in box.ravel():

                '''绘制最小外界矩形
                for i in range(4):
                    cv2.line(image, tuple(box[i]), tuple(box[(i+1)%4]), 0)  # 5
                '''
                # 旋转角度
                theta = cv2.minAreaRect(cnt)[2]
                print(theta)
                if abs(theta) <= 45 and abs(theta)!=0:
                    print('图片的旋转角度为%s.'%theta)
                    angle = theta

    # 仿射变换,对图片旋转angle角度
    print(img.shape)
    h, w,k= img.shape
    center = (w//2, h//2)
    M = cv2.getRotationMatrix2D(center, -angle, 1.0)
    rotated = cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
    cv2.imwrite('rotated.png', rotated)
rorate(imagepath)
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值