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

使用OpenCV获取像素颜色后绘制圆形颜色不匹配问题排查

问题原因与解决方法

你的代码核心问题是像素索引顺序错误:OpenCV中图像数组的索引规则是image[y, x](行坐标在前,列坐标在后),但你在读取像素时搞反了x和y的顺序,导致获取的是错误位置的BGR值,最终绘制的圆形颜色和目标区域不匹配。

修正后的代码

import cv2

def get_bgr(filename):
    image = cv2.imread(filename)
    # target格式为[x, y],x是列坐标,y是行坐标
    target = [int(image.shape[1] / 2), int(image.shape[0] / 2)]

    # 读取像素时要使用image[y, x],即target[1]是y,target[0]是x
    b, g, r = image[target[1], target[0]]
    # 绘制圆形的坐标参数是(x, y),这里target的顺序是对的
    image = cv2.circle(image, target, 5, (int(b), int(g), int(r)), 2)

    print(f'colour = {b}, {g}, {r}')

    cv2.imshow('image', image)
    cv2.waitKey(0)

if __name__ == '__main__':
    get_bgr('shapes.jpg')

关键修正点

  • 读取像素时将image[target[0], target[1]]改为image[target[1], target[0]],符合OpenCV的y, x索引规则
  • 绘制圆形的坐标参数target是[x, y],这部分是正确的,无需修改

修正后,获取的BGR值就是图像中心位置的真实颜色,绘制的圆形颜色会和下方黄色矩形匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 03:45:42