环境:Python3.8 和 OpenCV
内容:图像外接矩形、最小外接矩形、凸包、外接圆、拟合椭圆的绘制
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
# 封装图片显示函数
def image_show(image):
if image.ndim == 2:
plt.imshow(image, cmap='gray')
else:
image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
plt.imshow(image)
plt.show()
if __name__ == '__main__':
# 读取原图
img_desk = cv.imread('desk.png')
# 转换为灰度图
img_gray = cv.cvtColor(img_desk, cv.COLOR_RGB2GRAY)
# 二值化
[thresh, img_bin] = cv.threshold(img_gray, -1, 255, cv.THRESH_OTSU)
# 获取轮廓
[cnt, hir] = cv.findContours(img_bin, cv.RETR_CCOMP, cv.CHAIN_APPROX_NONE)
# 绘制轮廓 (绘制第九个轮廓-矩形)
cv.drawContours(img_desk, cnt, 8, (0, 0, 255), 1)
# 获取外接矩形的坐标点
cns = cnt[8]
X, Y, W, H = cv.boundingRect(cns)
# 绘制外接矩形
img_rec = cv.rectangle(img_desk.copy(), (X, Y), (X + W, Y + H), (255, 255, 0), 3)
# 显示图像
image_show(img_rec)
# 获取最小外接矩形
min_rec = cv.boxPoints(cv.minAreaRect(cns)).astype(np.int32)
# 绘制最小外接矩形
img_min_rec = cv.drawContours(img_desk.copy(), [min_rec], 0, (255, 0, 255), 3)
# 显示图像
image_show(img_min_rec)
# 获取凸包坐标
hull = cv.convexHull(cns)
# 绘制凸包图形
img_hull = cv.drawContours(img_desk.copy(), [hull], 0, (0, 255, 255), 3)
# 显示图像
image_show(img_hull)
# 获取最小外接圆
(X, Y), R = cv.minEnclosingCircle(cns)
# 绘制最小外接圆
img_circle = cv.circle(img_desk.copy(), (int(X), int(Y)), int(R), (125, 255, 0), 3)
# 显示图像
image_show(img_circle)
# 获取拟合椭圆坐标
ellipse = cv.fitEllipse(cns)
# 绘制拟合椭圆
img_ellipse = cv.ellipse(img_desk.copy(), ellipse, (255, 125, 0), 3)
# 显示图像
image_show(img_ellipse)