基于python和opencv的图像分割旋转裁剪

转自https://blog.csdn.net/sinat_36458870/article/details/78825571,有修改

1.代码

# encoding:utf-8
import math
import cv2
import numpy as np
import matplotlib.pyplot as plt


def get_image(path):  # 获取图片
    img = cv2.imread(path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    return img, gray


def Gaussian_Blur(gray):  # 高斯去噪(去除图像中的噪点)
    blurred = cv2.GaussianBlur(gray, (9, 9), 0)
    return blurred


def Sobel_gradient(blurred):  # 计算梯度
    gradX = cv2.Sobel(blurred, ddepth=cv2.CV_32F, dx=1, dy=0)
    gradY = cv2.Sobel(blurred, ddepth=cv2.CV_32F, dx=0, dy=1)
    gradient = cv2.subtract(gradX, gradY)
    gradient = cv2.convertScaleAbs(gradient)
    return gradX, gradY, gradient


def Thresh_and_blur(gradient):  # 设定阈值
    blurred = cv2.GaussianBlur(gradient, (9, 9), 0)
    (_, thresh) = cv2.threshold(blurred, 90, 255, cv2.THRESH_BINARY)
    return thresh


def image_morphology(thresh):  # 图形形态学
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (25, 25))
    closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
    closed = cv2.erode(closed, None, iterations=4)
    closed = cv2.dilate(closed, None, iterations=4)
    return closed


def findcnts_and_box_point(closed):  # 计算最大轮廓的旋转包围box
    (cnts, test) = cv2.findContours(closed.copy(),
                                    cv2.RETR_LIST,
                                    cv2.CHAIN_APPROX_SIMPLE)
    c = sorted(cnts, key=cv2.contourArea, reverse=True)[0]

    rect = cv2.minAreaRect(c)
    box = np.int0(cv2.boxPoints(rect))
    print(box)
    return box


def drawcnts_and_cut(original_img, box):  # 目标图像裁剪
    draw_img = cv2.drawContours(original_img.copy(), [box], -1, (0, 0, 255), 3)
    Xs = [i[0] for i in box]
    Ys = [i[1] for i in box]
    angle = round(-math.atan((Ys[1] - Ys[0]) / (abs(Xs[1] - Xs[0]))) * 360 / (2 * np.pi), 1)
    print(angle)
    rows, cols = draw_img.shape[:2]

    # 计算框中心
    center = ((Xs[1]+Xs[3]) / 2.0, (Ys[1]+Ys[3]) / 2.0)
    # 计算框长宽
    xx = ((Ys[2]-Ys[3])**2 + (Xs[2]-Xs[3])**2)**0.5
    yy = ((Ys[2]-Ys[1])**2 + (Xs[2]-Xs[1])**2)**0.5

    M = cv2.getRotationMatrix2D(center, 360 - round(angle, 1), 1)
    dst = cv2.warpAffine(draw_img, M, (cols, rows))
    crop_img = cv2.getRectSubPix(dst, (int(xx), int(yy)), center)
    return draw_img, crop_img


def work():
    img_path = r'./01.bmp'
    save_path = r'./01_save.bmp'
    # original_img, gray = get_image(img_path)
    gray = cv2.imread("01.bmp", 0)
    original_img = gray.copy()
    blurred = Gaussian_Blur(gray)
    gradX, gradY, gradient = Sobel_gradient(blurred)
    thresh = Thresh_and_blur(gradient)
    closed = image_morphology(thresh)
    box = findcnts_and_box_point(closed)
    draw_img, crop_img = drawcnts_and_cut(original_img, box)

    img_list = [original_img, blurred, gradX, gradY, gradient,
                thresh, closed,draw_img, crop_img]
    img_name = ["原图像", "高斯模糊", "x方向梯度", "y方向梯度", "梯度",
                "二值化", "图像形态学", "图片分割", "旋转切割结果"]
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    _, axs = plt.subplots(3, 3, figsize=(12, 12))

    for i in range(3):
        for j in range(3):
            axs[i][j].imshow(img_list[i * 3 + j], cmap='gray')
            axs[i][j].set_title(img_name[i * 3 + j])
            axs[i][j].axes.get_xaxis().set_visible(False)
            axs[i][j].axes.get_yaxis().set_visible(False)
    plt.show()


work()

2.现象

现象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值