• Python Opencv实践 - 矩形轮廓绘制(直边矩形,最小外接矩形)


    1. import cv2 as cv
    2. import numpy as np
    3. import matplotlib.pyplot as plt
    4. img = cv.imread("../SampleImages/stars.png")
    5. plt.imshow(img[:,:,::-1])
    6. img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    7. #通过cv.threshold转换为二值图
    8. ret,thresh = cv.threshold(img_gray, 127, 255, 0)
    9. plt.imshow(thresh, cmap=plt.cm.gray)
    10. #轮廓检测
    11. contours,hierarchy = cv.findContours(thresh, 1, 2)
    12. #绘制轮廓
    13. img_contours_org = img.copy()
    14. img_contours_org = cv.drawContours(img_contours_org, contours, -1, (0,255,0), 2)
    15. plt.imshow(img_contours_org[:,:,::-1])
    16. img_rect_contour = img.copy()
    17. for contour in contours:
    18. #1. 绘制直边界矩形
    19. #x,y,w,h = cv.boundingRect(contour)
    20. #contour: 轮廓信息
    21. #x,y,w,h: 矩形左上角(x,y)坐标,以及矩形的宽度和高度
    22. #参考资料:https://blog.csdn.net/hjxu2016/article/details/77833984
    23. x,y,w,h = cv.boundingRect(contour)
    24. img_rect_contour = cv.rectangle(img_rect_contour, (x,y), (x+w,y+h), (0,255,0), 2)
    25. #2. 绘制旋边界矩形结果
    26. #rect = cv.minAreaRect(contour)
    27. #contour:轮廓信息
    28. #rect: 最小外接矩阵的信息(中心(x,y),(w,h),旋转角度)
    29. #参考资料:https://blog.csdn.net/lanyuelvyun/article/details/76614872
    30. rect = cv.minAreaRect(contour)
    31. #使用boxPoints获得最小外接矩阵的4个顶点坐标
    32. box = cv.boxPoints(rect)
    33. #转换为int类型
    34. box = np.intp(box)
    35. #使用cv.polylines绘制外接矩形
    36. cv.polylines(img_rect_contour, [box], True, (0,0,255), 2)
    37. plt.imshow(img_rect_contour[:,:,::-1])

     

  • 相关阅读:
    scala
    十三、SpringBoot错误处理底层组件和异常处理流程分析
    备忘录模式(Memento Pattern)
    Redis如何查看KEY的数据类型
    进程和线程、协程的区别
    [题] 改革春风吹满地 #图论 #多边形面积
    Linux环境配置
    增强group by的使用
    如何选择一款快速可靠的文件自动同步软件?
    10步开启SAFe敏捷发布列车
  • 原文地址:https://blog.csdn.net/vivo01/article/details/132646535