用Python和OpenCV提取2D矩阵的对角线值

2024-09-30 10:33:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图沿着这个图像的对角线检索以下像素密度值(边界框中的线显示了我要检索的像素)

enter image description here

如你所见,我试图找到从中心点延伸的值的像素密度

到目前为止,我的一般做法是:

  1. 创建与图像形状成比例的2d矩阵
  2. 使用请求的边界点,创建边界框
  3. 确定中心点,然后画出连接中心和每个边界点的线
  4. 遍历矩阵并检索相应的像素值,然后插入每个对角线的单独列表

代码如下:

# Iterate across image
for j in range(columnCount):
    for i in range(rowCount):
        pixelMatrix[i][j] = greyscaleImage[i][j]

# Find the width, height and area of the matrix
width, height, area = len(matrix[0]), len(matrix), len(matrix[0]) * len(matrix)
squareWidth, squareHeight = min([width, height]), min([width, height])

# Find boundary positions
leftTopCorner = [int((width - squareWidth)/2), int((height - squareHeight)/2)]
leftBottomCorner = [leftTopCorner[0], leftTopCorner[1] + squareHeight]
rightTopCorner = [leftTopCorner[0] + squareWidth, leftTopCorner[1]]
rightBottomCorner = [leftTopCorner[0] + squareWidth, leftBottomCorner[1]]
centre = [(leftTopCorner[0] + (squareWidth/2)), (squareHeight/2)]

# NB: Excluding code for graphics

# Iterate across matrix (right-corner - left-corner) and descend across rows
heightCounter = 0
for i in range((boundaryCoordinates[2][0] - boundaryCoordinates[0][0])):
    # Left-side => Descending/ascending from top-left and bottom-left corners to converge on centrePoint.
    XCoordLeft = boundaryCoordinates[0][0] + i
    topLeft.append(matrix[XCoordLeft][heightCounter])
    bottomCord = boundaryCoordinates[1][1] - heightCounter
    bottomLeft.append(matrix[XCoordLeft][bottomCord])
    print("LEFT_TOP_COORS: " + str(XCoordLeft) + ", " + str(heightCounter) + " LEFT_BOTTOM_COORS: " + str(XCoordLeft) + ", " + str(bottomCord))        
    heightCounter += 1

heightCounter = 0
for i in range((boundaryCoordinates[2][0] - boundaryCoordinates[0][0])/2):
    # Right-side => Descending/ascending from centrePoint to top-right and bottom-right.
    XCoordRight = centrePoint[0] + i
    topHeight = centrePoint[1] + heightCounter
    bottomHeight = centrePoint[1] - heightCounter
    topRight.append(matrix[topHeight][XCoordRight])
    bottomRight.append(matrix[bottomHeight][XCoordRight])
    heightCounter += 1


    return [topLeft, topRight, bottomLeft, bottomRight]

但是我一直收到IndexError: list index out of range

enter image description here

我只是不知道为什么。任何帮助都将不胜感激:)


Tags: andinforlenrange像素widthmatrix

热门问题