You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenCV Python获取Bounding Box中心像素强度值时索引越界问题解决

解决OpenCV访问像素时的索引越界问题

问题出在你搞反了OpenCV图像数组的索引顺序和绘图函数的坐标顺序:

  • cv2的绘图函数(比如cv2.rectangle、cv2.circle)使用的是**(x, y)**坐标,x对应图像水平方向(宽度),y对应垂直方向(高度)
  • 但cv2.imread读取的图像数组,维度是**(height, width, channels),访问像素时要按[y坐标, x坐标]**的顺序索引

你用center_x(x轴坐标)作为数组的第一个索引,相当于用宽度方向的数值去访问高度维度,自然会超出范围报错;而绘图函数因为坐标顺序正确,所以能正常运行。

修正方法

把访问像素的代码改成按**[y, x]**的顺序索引:

print('Pixel intensity at:', img_read[center_y][center_x])
# 也可以用逗号索引的方式
print('Pixel intensity at:', img_read[center_y, center_x])

完整修正后的代码

import cv2
import matplotlib.pyplot as plt

img_read= cv2.imread(r'image.png')
# 先打印图像形状(高度, 宽度, 通道数),方便排查索引范围
print(img_read.shape)
cv2.rectangle(img_read,(xmin,ymin),(xmax,ymax),(0,0,255),3)
center_x = int((xmin+xmax)//2)
center_y = int((ymin+ymax)//2)
print(center_x,center_y)
cv2.circle(img_read,(center_x,center_y),50,(0,0,255),3)
# 修正像素访问顺序
print('Pixel intensity at:', img_read[center_y][center_x])
plt.imshow(img_read[:,:,::-1])
plt.show()

内容的提问来源于stack exchange,提问作者appguy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 05:55:19