• 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])

     

  • 相关阅读:
    C# 第五章『面向对象』◆第3节:构造函数(方法)
    R/S nomenclature for chiral center
    天玑9000+和骁龙8gen1+哪个性能更强 两者配置对比
    CKA、CKAD、CKS、KCNA、CFCD考试
    机器学习入门(1)
    v-show 与 v-if 有什么区别?
    java基础的复习
    【C++】C++面向对象编程三大特性之一——多态
    mixly扩展库Ethernet库
    【Mybatis源码】源码分析
  • 原文地址:https://blog.csdn.net/vivo01/article/details/132646535