使用Python和OpenCV找出图像中的四边形或矩形
最编程
2024-02-14 10:49:59
...
F:opencv4.2_releaseopencvsourcessamplespythonsquares.py
本文稍作修改,做简要说明。目标是找到下图中的矩形轮廓和四边形轮廓:
矩形的检测包含检测轮廓是四个顶点,同时两条边的夹角接近90°,代码和效果如下:
import numpy as np
import cv2 as cv
# 设置putText函数字体
font=cv.FONT_HERSHEY_SIMPLEX
#计算两边夹角额cos值
def angle_cos(p0, p1, p2):
d1, d2 = (p0-p1).astype('float'), (p2-p1).astype('float')
return abs( np.dot(d1, d2) / np.sqrt( np.dot(d1, d1)*np.dot(d2, d2) ) )
def find_squares(img):
squares = []
img = cv.GaussianBlur(img, (3, 3), 0)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
bin = cv.Canny(gray, 30, 100, apertureSize=3)
contours, _hierarchy = cv.findContours(bin, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
print("轮廓数量:%d" % len(contours))
index = 0
# 轮廓遍历
for cnt in contours:
cnt_len = cv.arcLength(cnt, True) #计算轮廓周长
cnt = cv.approxPolyDP(cnt, 0.02*cnt_len, True) #多边形逼近
# 条件判断逼近边的数量是否为4,轮廓面积是否大于1000,检测轮廓是否为凸的
if len(cnt) == 4 and cv.contourArea(cnt) > 1000 and cv.isContourConvex(cnt):
M = cv.moments(cnt) #计算轮廓的矩
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])#轮廓重心
cnt = cnt.reshape(-1, 2)
max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in range(4)])
# 只检测矩形(cos90° = 0)
if max_cos < 0.1:
# 检测四边形(不限定角度范围)
#if True:
index = index + 1
cv.putText(img,("#%d"%index),(cx,cy),font,0.7,(255,0,255),2)
squares.append(cnt)
return squares, img
def main():
img = cv.imread("./test.png")
squares, img = find_squares(img)
cv.drawContours( img, squares, -1, (0, 0, 255), 2 )
cv.imshow('squares', img)
ch = cv.waitKey()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()
代码比较简单,核心步骤上面已添加注释,筛选条件自己可以改,如果只想检测四边形,不限制为矩形,则修改如下地方:
# 只检测矩形(cos90° = 0)
if max_cos < 0.1:
# 检测四边形(不限定角度范围)
#if True:
效果如下:
大家使用的时候根据具体情况进行修改,C++的demo路径如下:
F:opencv4.2_releaseopencvsourcessamplescppsquares.cpp
上一篇: 如何用ECharts绘制出酷炫的关系图?前端必看!
下一篇: 使用UML建模:如何绘制实用的用例图?
推荐阅读
-
[姿势估计] 实践记录:使用 Dlib 和 mediapipe 进行人脸姿势估计 - 本文重点介绍方法 2):方法 1:基于深度学习的方法:。 基于深度学习的方法:基于深度学习的方法利用深度学习模型,如卷积神经网络(CNN)或递归神经网络(RNN),直接从人脸图像中学习姿势估计。这些方法能够学习更复杂的特征表征,并在大规模数据集上取得优异的性能。方法二:基于二维校准信息估计三维姿态信息(计算机视觉 PnP 问题)。 特征点定位:人脸姿态估计的第一步是通过特征点定位来检测和定位人脸的关键点,如眼睛、鼻子和嘴巴。这些关键点提供了人脸的局部结构信息,可用于后续的姿势估计。 旋转表示:常见的旋转表示方法包括欧拉角和旋转矩阵。欧拉角通过三个旋转角度(通常是俯仰、偏航和滚动)描述头部的旋转姿态。旋转矩阵是一个 3x3 矩阵,表示头部从一个坐标系到另一个坐标系的变换。 三维模型重建:根据特征点的定位结果,三维人脸模型可用于姿势估计。通过将人脸的二维图像映射到三维模型上,可以估算出人脸的旋转和平移信息。这就需要建立人脸的三维模型,然后通过优化方法将模型与特征点对齐,从而获得姿势估计结果。 特征点定位 特征点定位是用于检测人脸关键部位的五官基础部分,还有其他更多的特征点表示方法,大家可以参考我上一篇文章中介绍的特征点检测方案实践:人脸校正二次定位操作来解决人脸校正的问题,客户在检测关键点的代码上略有修改,坐标转换部分客户见上图 def get_face_info(image). img_copy = image.copy image.flags.writeable = False image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = face_detection.process(image) # 在图像上绘制人脸检测注释。 image.flags.writeable = True image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) box_info, facial = None, None if results.detections: for detection in results. for detection in results.detections: mp_drawing.Drawing.detection = 无 mp_drawing.draw_detection(image, detection) 面部 = detection.location_data.relative_keypoints 返回面部 在上述代码中,返回的数据是五官(6 个关键点的坐标),这是用 mediapipe 库实现的,下面我们可以尝试用另一个库:dlib 来实现。 使用 dlib 使用 Dlib 库在 Python 中实现人脸关键点检测的步骤如下: 确保已安装 Dlib 库,可使用以下命令: pip install dlib 导入必要的库: 加载 Dlib 的人脸检测器和关键点检测器模型: 读取图像并将其灰度化: 使用人脸检测器检测图像中的人脸: 对检测到的人脸进行遍历,并使用关键点检测器检测人脸关键点: 显示绘制了关键点的图像: 以下代码将参数 landmarks_part 添加到要返回的关键点坐标中。
-
使用Python和OpenCV找出图像中的四边形或矩形