使用OpenCV Python实现图像网格单元格按序编号的问题咨询
OpenCV 网格单元格编号实现方案
你现有代码的核心问题如下:
- 内层遍历y轴的变量没有在外层x循环开始时重置,第一列绘制完成后y值已经超过图像高度,后续列的内层循环不会执行,只会生成第一列的编号
- 每次x循环都会重复绘制所有水平线,存在大量冗余操作
- 文字绘制坐标在网格线交点处,既和网格线重叠,也不在单元格可视范围内
修正后代码(列优先编号:从上到下、从左到右排序)
import cv2 # 提前定义字体参数 font = cv2.FONT_HERSHEY_SIMPLEX grid_step = 100 # 网格步长,可自行调整 k = 0 # 先一次性绘制所有水平线 y = 0 while y < self.img.shape[0]: cv2.line(self.img, (0, y), (self.img.shape[1], y), color=(220,220,220), lineType=cv2.LINE_AA, thickness=1) y += grid_step # 遍历每一列绘制垂直线 + 单元格编号 x = 0 while x < self.img.shape[1]: # 绘制当前垂直线 cv2.line(self.img, (x, 0), (x, self.img.shape[0]), color=(220,220,220), lineType=cv2.LINE_AA, thickness=1) # 重置y坐标,遍历当前列的所有单元格 y = 0 while y < self.img.shape[0]: k += 1 # 文字坐标调整到单元格左上角内侧,偏移量可根据需求修改 cv2.putText(self.img, str(k), (x + 10, y + 30), font, 1, (0, 255, 255), 1, cv2.LINE_AA) y += grid_step x += grid_step
如果需要行优先编号(从左到右、从上到下排序,更符合常规阅读顺序),调整循环顺序即可:
import cv2 font = cv2.FONT_HERSHEY_SIMPLEX grid_step = 100 k = 0 # 先绘制所有网格线 # 水平线 y = 0 while y < self.img.shape[0]: cv2.line(self.img, (0, y), (self.img.shape[1], y), color=(220,220,220), lineType=cv2.LINE_AA, thickness=1) y += grid_step # 垂直线 x = 0 while x < self.img.shape[1]: cv2.line(self.img, (x, 0), (x, self.img.shape[0]), color=(220,220,220), lineType=cv2.LINE_AA, thickness=1) x += grid_step # 行优先遍历编号 y = 0 while y < self.img.shape[0]: x = 0 while x < self.img.shape[1]: k += 1 cv2.putText(self.img, str(k), (x + 10, y + 30), font, 1, (0, 255, 255), 1, cv2.LINE_AA) x += grid_step y += grid_step
你可以根据需求调整文字的偏移量、字体大小、颜色参数,适配不同的网格尺寸。
内容的提问来源于stack exchange,提问作者Wilbrone Baron
相关产品推荐
相关产品推荐

