任务:给定这样一张图片求图片中白色区域的外接矩形、最小外接矩形、拟合多边形以及外接圆

外接矩形

x, y, w, h = cv2.boundingRect(points)

  • 输入:点集
  • 返回值:左上角点坐标以及宽高

实现代码:

import cv2

imgpath = '1.jpg'
# 读取图片
image = cv2.imread(imgpath)
# 转换为灰度图
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
# 将图片二值化
_, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)  
# 在二值图上寻找轮廓
contours, _ = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cont in contours:
	# 外接矩形
    x, y, w, h = cv2.boundingRect(cont)
    # 在原图上画出预测的矩形
    cv2.rectangle(image, (x, y), (x+w, y+h), (0, 0, 255), 10)

输出结果:

最小外接矩形

(cx,cy), (l,w), theta=cv2.minAreaRect(points)

  • 输入:点集
  • 返回值:中心点坐标->(cx,cy);长宽->(l,w);从x轴逆时针旋转到(w)的角度->theta
  • cv2.boxPoints()可以将minAreaRect的返回值转换为四个角点坐标

实现代码:

import cv2

imgpath = '1.jpg'
image = cv2.imread(imgpath)
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)  
contours, _ = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cont in contours:
	# 对每个轮廓点求最小外接矩形
    rect = cv2.minAreaRect(cont)
    # cv2.boxPoints可以将轮廓点转换为四个角点坐标
    box = cv2.boxPoints(rect)
    # 这一步不影响后面的画图,但是可以保证四个角点坐标为顺时针
    startidx = box.sum(axis=1).argmin()
    box = np.roll(box,4-startidx,0)
    # 在原图上画出预测的外接矩形
    box = box.reshape((-1,1,2)).astype(np.int32)
    cv2.polylines(image,[box],True,(0,255,0),10)

输出结果:

外接多边形

box = cv2.approxPolyDP(curve, epsilon, closed)

  • 输入:
    • curve:点集(折线图)
    • epsilon:点到相对应的切线的距离的阈值。(大于阈值舍弃,小于阈值保留,epsilon越小,折线的形状越“接近”曲线。)
    • closed:曲线是否闭合(True/False)
  • 返回值:
    • 多边形角点坐标

实现代码:

import cv2

imgpath = '1.jpg'
image = cv2.imread(imgpath)
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

_, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
contours, _ = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

for cont in contours:
	# 取轮廓长度的1%为epsilon
    epsilon = 0.01*cv2.arcLength(cont,True)
    # 预测多边形
    box = cv2.approxPolyDP(cont,epsilon,True)
    img = cv2.polylines(image,[box],True,(0,0,255),10)

输出结果:

外接圆

(x, y), radius = cv2.minEnclosingCircle(cont)

  • 输入:点集
  • 返回值:圆心 --> (x, y), 半径 --> radius
import cv2

image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
_, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
contours, _ = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cont in contours:
	# 外接圆
    (x, y), radius = cv2.minEnclosingCircle(cont)
    cv2.circle(image,(int(x),int(y)),int(radius), (0, 0, 255), 10)

输出结果:

GitHub 加速计划 / opencv31 / opencv
77.34 K
55.71 K
下载
OpenCV: 开源计算机视觉库
最近提交(Master分支:29 天前 )
e1fec156 features2d: fixed out of bounds access in SIFT 7 天前
63087396 - 7 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐