# -*- 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)