如何使用OpenCV绘图函数在识别到的矩形区域内生成网格
OpenCV外接矩形内绘制网格实现方法
实现逻辑
- 定义网格间距参数控制网格疏密
- 在识别到蓝色物体外接矩形的
x(左上角横坐标)、y(左上角纵坐标)、w(矩形宽度)、h(矩形高度)参数后,分别绘制垂直、水平两个方向的网格线 - 垂直网格线从矩形左边界开始,每隔设定的间距绘制一条贯穿矩形上下的直线,直到覆盖整个矩形宽度
- 水平网格线从矩形上边界开始,每隔设定的间距绘制一条贯穿矩形左右的直线,直到覆盖整个矩形高度
完整修改后代码
import cv2 import numpy as np cap = cv2.VideoCapture(0) width = cap.get(3) # float height = cap.get(4) # float print(width, height) while (1): _, img = cap.read() if _ is True: hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) else: continue # 蓝色阈值 blue_lower = np.array([86,0,90], np.uint8) blue_upper = np.array([163, 64, 145], np.uint8) blue = cv2.inRange(hsv, blue_lower, blue_upper) kernal = np.ones((9, 9), "uint8") blue = cv2.dilate(blue, kernal) res_blue = cv2.bitwise_and(img, img, mask=blue) # 追踪蓝色物体 (_, contours, hierarchy) = cv2.findContours(blue, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for pic, contour in enumerate(contours): area = cv2.contourArea(contour) if (area > 2000): print(area) x, y, w, h = cv2.boundingRect(contour) img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) cv2.putText(img, "Blue Colour", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0)) # 新增:绘制矩形内部网格 grid_step = 20 # 网格间距,可自行调整数值控制疏密 # 绘制垂直方向网格线 for v_x in range(x, x + w, grid_step): cv2.line(img, (v_x, y), (v_x, y + h), (255, 0, 0), 1) # 绘制水平方向网格线 for h_y in range(y, y + h, grid_step): cv2.line(img, (x, h_y), (x + w, h_y), (255, 0, 0), 1) cv2.imshow("Color Tracking", img) if cv2.waitKey(10) & 0xFF == ord('q'): cap.release() cv2.destroyAllWindows() break
参数调整说明
你可以根据实际使用需求自定义以下参数:
- grid_step:数值越大网格越稀疏,数值越小网格越密集
- 网格线颜色:修改
cv2.line中的(255, 0, 0)参数,BGR格式对应蓝、绿、红三个通道的数值,比如(0,255,0)对应绿色网格 - 网格线粗细:修改
cv2.line的最后一个参数,默认值为1,数值越大线条越粗
内容的提问来源于stack exchange,提问作者Redhwan
相关产品推荐
相关产品推荐

