(Opencv07)绘制边框

(Opencv07)绘制边框

cv2.boundingRect(img) 这个函数可以获得一个图像的最小矩形边框一些信息

cv2.rectangle()可以画出该最小矩形边框

x, y ,w, h = cv2.boungingRect(img)

  • img : 需要是一个二值图像。

  • x,y : 可以包围这个img的最小矩形的左上角的坐标。

  • w,h: 可以包围这个img的最小矩形的长,宽。

img = cv2.rectangle(img.copy(), (x, y), (x+w, y+h),(0, 255, 0), 2)

  • img.copy() : 需要拷贝一份传入,不然原图像会变喔!

  • (x,y) : 需要绘制矩形的左上角的坐标。

  • (x+w, y+h) : 要绘制矩形的右下角点。

  • (0, 255, 0) : 线条颜色,BGR

  • 2 : 线宽

示例图片

示例代码

 import cv2
 
 
 def cv_show(image, name):
    cv2.imshow(name, image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
 
 
 img = cv2.imread('triangle.jpg')
 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
 # 转换为二值图像
 ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
 # 轮廓信息(列表),层级
 contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
 cnt = contours[0]
 # (bounding rectangle 边框) 水平位置,竖直位置,长,高
 x, y, w, h = cv2.boundingRect(cnt)
 print('x:{}, y:{}, w:{}, h:{}'.format(x, y, w, h))
 img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
 cv_show(img, 'img')

示例结果




 

posted on 2021-02-03 17:43  华子哈  阅读(232)  评论(0编辑  收藏  举报

导航