使用Python for OpenCV检索二维矩阵中的对角线值

时间:2019-05-02 01:52:48

标签: python opencv

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

enter image description here

如您所见,我正在尝试查找从中心点延伸的值的像素密度。

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

  1. 创建与图像形状成比例的二维矩阵,
  2. 使用请求的边界点,创建边界框,
  3. 确定中心点,然后绘制将中心连接到每个边界点的线,
  4. 遍历矩阵并检索相应的pixelValue,并为每个对角线插入一个单独的列表中。

代码如下:

# 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

我似乎无法弄清楚为什么。任何帮助将不胜感激:)

0 个答案:

没有答案