opencv最小外接矩形

import cv2
import numpy as np
img1 = cv2.imread(r'D:\test\pigs\20200518132334816.jpg.jpg',0)
_,thresh = cv2.threshold(img1,200,255,0)
image,contours = cv2.findContours(thresh,2,1)
area = 0
for c in image:
    rect = cv2.minAreaRect(c)
    box = np.int0(cv2.boxPoints(rect))
    y_max = np.max(box[:,1])
    x_max = np.max(box[:,0])
    y_min = np.min(box[:, 1])
    x_min = np.min(box[:, 0])
    if (y_max - y_min) * (x_max - x_min) > area:
        area = (y_max - y_min) * (x_max - x_min)
        bbox = box
        yy_max = y_max
        xx_max = x_max
        yy_min = y_min
        xx_min = x_min
print(bbox)
cv2.drawContours(img1,[bbox],0,(100,100,100),4)
cv2.imshow('a',img1)
cv2.waitKey(0)
mport cv2
import numpy as np
from math import *
import os
for dir in os.listdir(r'D:\tests\paper'):
    img1 = cv2.imread(os.path.join(r'D:\tests\paper',dir),0)
    _,thresh = cv2.threshold(img1,200,255,0)
    image,contours = cv2.findContours(thresh,2,1)
    area = 0
    for c in image:
        rect = cv2.minAreaRect(c)
        box = np.int0(cv2.boxPoints(rect))
        y_max = np.max(box[:,1])
        x_max = np.max(box[:,0])
        y_min = np.min(box[:, 1])
        x_min = np.min(box[:, 0])
        if (y_max - y_min) * (x_max - x_min) > area:
            area = (y_max - y_min) * (x_max - x_min)
            bbox = box
            yy_max = y_max
            xx_max = x_max
            yy_min = y_min
            xx_min = x_min
    flag = 0#0代表不是最标准的长方形
    if bbox[0][0] == bbox[1][0] or bbox[0][0] == bbox[2][0] or bbox[0][0] == bbox[3][0]:
        flag = 1#表示是横屏竖直
    if flag != 1:
        x1y1 = bbox[bbox[:,0] == xx_min][0]
        x2y2 = bbox[bbox[:,1] == yy_min][0]
        x3y3 = bbox[bbox[:,0] == xx_max][0]
        x4y4 = bbox[bbox[:,1] == yy_max][0]
        a = x4y4[1] - x1y1[1]
        b = x4y4[0] - x1y1[0]
        c = x3y3[0] - x4y4[0]
        d = x4y4[1] - x3y3[1]
        w = sqrt(a**2 + b**2) if sqrt(a**2 + b**2) < sqrt(c**2 + d**2) else sqrt(c**2 + d**2)
        h = sqrt(a**2 + b**2) if sqrt(a**2 + b**2) > sqrt(c**2 + d**2) else sqrt(c**2 + d**2)
        print(w/h)
    else:
        w = (xx_max - xx_min) if (xx_max - xx_min) < (yy_max - yy_min) else (yy_max - yy_min)
        h = (xx_max - xx_min) if (xx_max - xx_min) > (yy_max - yy_min) else (yy_max - yy_min)
        print(w/h)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值