python opencv画一张图的最小外接矩形(二)

# -*- coding : UTF-8 -*-
# @file   : img_seg2line.py
# @Time   : 2021/6/10 18:14
# @Author : wmz

# coding=utf-8
import cv2
import numpy as np
import matplotlib.pyplot as plt
import os


def draw_bbox(img_path, result, color=(255, 0, 0), thickness=8):
    if isinstance(img_path, str):
        img_path = cv2.imread(img_path)
        # img_path = cv2.cvtColor(img_path, cv2.COLOR_BGR2RGB)
    img_path = img_path.copy()
    for point in result:
        point = point.astype(int)
        cv2.polylines(img_path, [point], True, color, thickness)
    return img_path


def show_img(imgs: np.ndarray, title='img'):
    color = (len(imgs.shape) == 3 and imgs.shape[-1] == 3)
    imgs = np.expand_dims(imgs, axis=0)
    for i, img in enumerate(imgs):
        plt.figure()
        plt.title('{}_{}'.format(title, i))
        plt.imshow(img, cmap=None if color else 'gray')
    plt.show()


def getFiles(path, suffix):
    return [os.path.join(root, file) for root, dirs, files in os.walk(path) for file in files if file.endswith(suffix)]


if __name__ == '__main__':
    # 读取输入图片
    file_path = "./test/input"
    dst_path = "./test/output"
    img_filelist = getFiles(file_path, '.jpg')
    for img_file in img_filelist:
        # img_path = "./test/input/0001016.jpg"
        img_path = img_file
        img0 = cv2.imread(img_path)
        rows, cols, c = img0.shape
        print(rows, cols, c)
        if rows > 800:
            img = cv2.resize(img0, dsize=(0, 0), fx=0.125, fy=0.125, interpolation=cv2.INTER_NEAREST)
        # 将彩色图片转换为灰度图片
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        height, width = img.shape
        dest_height, dest_width = rows, cols

        # 创建一个LSD对象
        # fld = cv2.ximgproc.createFastLineDetector()
        # # 执行检测结果
        # dlines = fld.detect(img)
        # # 绘制检测结果
        # # drawn_img = fld.drawSegments(img0,dlines, )
        # for dline in dlines:
        #     x0 = int(round(dline[0][0]))
        #     y0 = int(round(dline[0][1]))
        #     x1 = int(round(dline[0][2]))
        #     y1 = int(round(dline[0][3]))
        #     cv2.line(img0, (x0, y0), (x1, y1), (0, 255, 0), 1, cv2.LINE_AA)

        # 最小外接矩形
        ret, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
        contours, _ = cv2.findContours(binary.astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
        num_contours = len(contours)
        boxes = np.zeros((num_contours, 4, 2), dtype=np.int16)
        for index in range(num_contours):
            contour = contours[index].squeeze(1)
            bounding_box = cv2.minAreaRect(contour)
            points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])
            index_1, index_2, index_3, index_4 = 0, 1, 2, 3
            if points[1][1] > points[0][1]:
                index_1 = 0
                index_4 = 1
            else:
                index_1 = 1
                index_4 = 0
            if points[3][1] > points[2][1]:
                index_2 = 2
                index_3 = 3
            else:
                index_2 = 3
                index_3 = 2

            box = [points[index_1], points[index_2], points[index_3], points[index_4]]
            box = list(list(x) for x in box)
            box = np.array(box)

            box[:, 0] = np.clip(np.round(box[:, 0] / width * dest_width), 0, dest_width)
            box[:, 1] = np.clip(np.round(box[:, 1] / height * dest_height), 0, dest_height)
            boxes[index, :, :] = box.astype(np.int16)
            box = [box.astype(int)]
            # print(box)
        # img = draw_bbox(cv2.imread(img_path)[:, :, ::-1], boxes)
        # show_img(img, title=os.path.basename(img_path))

        # 显示并保存结果
        # rect = cv2.minAreaRect(cnt)
        # box = cv2.boxPoints(bounding_box)
        # box = np.int0(box)
        listbox = boxes.tolist()
        length = len(listbox)
        # array = np.array(listbox[0]).reshape(4, 1, 2)
        listarraybox = []
        for i in range(length):
            array = np.array(listbox[i]).reshape(4, 1, 2)
            listarraybox.append(array)
        img0 = cv2.drawContours(img0, listarraybox, -1, (0, 0, 255), 2)
        # cv2.imshow('drawimg', img0)
        # cv2.waitKey(0)
        # cv2.destroyAllWindows()
        dst_file = img_file.replace(file_path, dst_path)
        dst_dir = dst_file.rsplit('\\', 1)[0]
        if not os.path.exists(dst_dir):
            os.makedirs(dst_dir)
        cv2.imwrite(dst_file, img0)
        # cv2.imshow("LSD", img0)
        # cv2.waitKey(0)
        # cv2.destroyAllWindows()







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落花逐流水

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值