当前位置:   article > 正文

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

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







  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/148818
推荐阅读
相关标签
  

闽ICP备14008679号