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

为何灰度图中非白色像素读取值为255?技术求助

OpenCV读取线段像素值异常问题

我用OpenCV处理图像时碰到个问题:参考图像里某线段区域明明有不同灰度色调,但自己实现的Bresenham算法获取该线段坐标对应的像素时,所有像素值全返回255。我试过绘制线段验证坐标是对的,但问题还是没解决。

相关代码如下:

import cv2

# 获取线段坐标的Bresenham算法
def bresenham(x1, y1, x2, y2):
    dx = abs(x2 - x1)
    dy = abs(y2 - y1)
    x, y = x1, y1
    sx = -1 if x1 > x2 else 1
    sy = -1 if y1 > y2 else 1
    error = dx - dy

    coords = []
    while True:
        coords.append((x, y))
        if x == x2 and y == y2:
            break
        e2 = 2 * error
        if e2 > -dy:
            error -= dy
            x += sx
        if e2 < dx:
            error += dx
            y += sy
    return coords

# 读取并转换图像
originalImage = cv2.imread("image.jpg",3)
gray = cv2.cvtColor(originalImage, cv2.COLOR_BGR2GRAY)

# 线段坐标
x1, y1 = 300, 120
x2, y2 = 400, 200

# 获取线段上的坐标点
coords = bresenham(x1, y1, x2, y2)

# 读取每个坐标的像素值
for i in range(len(coords)-1):
    imagex,imagey=coords[i]
    pixel = gray[imagex,imagey]
    print(imagex,imagey)
    print(pixel)

# 显示图像
cv2.namedWindow("black", cv2.WINDOW_NORMAL)
cv2.imshow("black", gray)

cv2.waitKey()
cv2.destroyAllWindows()

问题原因

OpenCV中灰度图像的数组索引规则是**[行, 列],对应图像坐标系统的(y, x)**,你代码里用gray[imagex, imagey]读取像素时,把x和y的顺序搞反了,实际读取的是图像中错误位置的像素,刚好这些位置都是255(比如图像的空白区域)。

解决方案

  1. 修正像素读取的索引顺序,将pixel = gray[imagex,imagey]改为pixel = gray[imagey, imagex]
  2. 遍历所有坐标点,把range(len(coords)-1)改为range(len(coords)),避免漏掉线段的最后一个点

修正后的像素读取代码片段:

# 读取每个坐标的像素值
for coord in coords:
    imagex, imagey = coord
    pixel = gray[imagey, imagex]
    print(imagex, imagey)
    print(pixel)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 01:15:50