一、效果

OpenCv版本4.0.0
Python版本3.7.2
编译环境: PyCharm
二、代码
import cv2 as cv
import numpy as np
from scipy.spatial import distance as dist
# 定义中点坐标运算
def midpoint(ptA, ptB):
return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)
def measure(img):
# 转灰度
gray = cv.cvtColor(img, cv.COLOR_RGB2GRAY)
# 图像二值化
ret, thresh = cv.threshold(gray, 127, 255, 0)
# 计算黑色方块的4个角点坐标
contours, hierarchy = cv.findContours(thresh, 1, 2)
for cnt in contours:
# 求取轮廓的几何距
M = cv.moments(cnt)
# 获取轮廓的外接矩形,x,y是绿框左上角的像数坐标点,w,h是绿框的长,宽
x, y, w, h = cv.boundingRect(cnt)
# 计算最小轮廓,红框
rect = cv.minAreaRect(cnt)
# 计算红框4个角的像数坐标
box = c