IndexError:只有整数,切片(`:`),省略号(`...`),numpy.newaxis(`None`)和整数或布尔数组才是有效索引。

时间:2018-06-26 01:09:31

标签: python python-3.x python-2.7

while True:

# Stage 1: Read an image from our webcam
image = webcam.get_current_frame()

# Stage 2: Detect edges in image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5,5), 0)
edges = cv2.Canny(gray, 100, 200)

# Stage 3: Find contours
contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv2.contourArea, reverse=True)[:10]

for contour in contours:

    # Stage 4: Shape check
    perimeter = cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, 0.01*perimeter, True)

    if len(approx) == QUADRILATERAL_POINTS:

        # Stage 5: Perspective warping
        topdown_quad = get_topdown_quad(gray, approx.reshape(4, 2))

        # Stage 6: Border check
        if topdown_quad[(topdown_quad.shape[0]/100.0)*5, 
                        (topdown_quad.shape[1]/100.0)*5] > BLACK_THRESHOLD: continue

在线

if topdown_quad [(topdown_quad.shape [0] /100.0) * 5, (topdown_quad.shape [1] /100.0) * 5]> BLACK_THRESHOLD: 
    continue

是发生错误的地方

为什么会这样?

1 个答案:

答案 0 :(得分:2)

(topdown_quad.shape [0] /100.0) * 5(topdown_quad.shape [1] /100.0) * 5是浮点值。

您不能在Python中使用浮点值作为索引。

这就是错误消息(可能很冗长)告诉您的内容:NumPy扩展了Python索引,以处理整个范围的不同种类的索引,但是它们仍然都是整数,整数切片或特殊值

目前尚不清楚您实际想要的内容是什么。假设topdown_quad.shape[0]是75,所以topdown_quad.shape[0] / 100 * 5是3.75,您要第3行还是第4行?您可能想要截断为0(如果值可以为负,则截断为负无穷大),或者舍入为最接近的整数,或者舍入为IEEE样式,将0.5向上或向下舍入,具体取决于整数部分是偶数还是其他形式。其他。

无论您想要什么,都必须显式地编写。例如,如果要截断:

    if topdown_quad[int((topdown_quad.shape[0]/100.0)*5),