【问题标题】:Need Help in Fixing Error in Python: index out of bounds for axis 0需要帮助修复 Python 中的错误:轴 0 的索引超出范围
【发布时间】:2021-09-10 14:52:28
【问题描述】:

这段代码实际上是更早发布的,当时它有更多错误。

以前,字母的 unicode 错误,无法使用。此外,它在 numpy 上有一些小错误。

现在它已修复,导致代码出现最终(我希望)错误

import numpy as np
import math as mt
import cv2
import matplotlib.pyplot

I = cv2.imread()#plase image location

h, w, c = I.cv2.shape

largerLength = np.maximum(h, w)

power = np.ceil(mt.log2(largerLength))
lengthNum =2**power
grayIm = cv2.cvtColor(I, cv2.COLOR_BGR2GRAY)
ret, binaryIm = cv2.threshold(grayIm,125,256,cv2.THRESH_BINARY)

#get the amount of padding to add
padRow = lengthNum - I.shape
padCol = lengthNum − I.shape
#pad I with 0’s after its last row and column
I = np.padarray(I , [padRow , padCol], ’post’) 

boxCountstore = np.zeros(1 , power) 
#boxcountstore = zeros(1, power)
scalestore = np.zeros(1 , power) #??
#scalestore = zeros(1, power)
boxNum = 1

#use the for loop to shrink the box size
for i in range(1, power):
    boxCount=0
    for boxrow in range(1,2**i):#i was i-1
        for boxcol in range(1,2**i):
                #thefourtermsbelowaretheindexrange
                #ofthecurrentboxwearechecking
            var1 = lengthNum/boxNum
            var2 = boxrow-1
            minRow = 1 + var1∗var2
            minCol = 1 + var1∗var2
            maxRow = var1∗boxrow
            maxCol = var1∗boxcol
            contain=0
            for row in range(minRow,maxRow):
                for col in range(minCol,maxCol):
                    if I[row-1,col-1]: ###????
                    #ifture,thenthecurrentbox
                    #containstheobject
                        boxCount=boxCount+1
                        contain=1
                        break #breakfromthe”col”
                if contain:
                    break #breakfromthe”row”loop



scale=1/(lengthNum/boxNum)
boxNum =  2*boxNum #doublethenumberofboxes
#per dimension

#fit a line for the log − log plot in the least square
#sense


FD = np.polyfit(np.log(scalestore),np.log(boxCountstore),1)

错误信息是这样的:

Traceback(最近一次调用最后一次):

File "C:/Users/qkrgn/PycharmProjects/pythonProject/main.py", line 60, in <module>

if I[row-1, col-1]:  ###????

IndexError: index 32768 is out of bounds for axis 0 with size 32768

如你所见,

【问题讨论】:

  • 如果你有一个包含 N 个元素的数组,你可以使用的最大索引是 N-1
  • 顺便说一句,您的代码中仍然存在上一个问题中出现的奇怪错误,例如 而不是*,以及 而不是'跨度>
  • row 太大,表示它的迭代范围也太大了。审查minRow, maxRow。你从哪里得到这些数字?大多数情况下,这看起来像是一个簿记问题。在对一组复杂的范围进行迭代时,您需要小心,验证和测试所有值。没有猜测或希望这是有效的代码!

标签: python numpy matplotlib opencv3.0


【解决方案1】:

与matlab不同,python的数组以0开头,所以最后一个索引是32767

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-23
    • 2018-02-12
    • 2021-09-17
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    相关资源
    最近更新 更多