python报错“TypeError: slice indices must be integers or None or have an __index__ method”

源代码

import cv2
import random

img = cv2.imread("lena.jpg")
width, height, depth = img.shape
img_width_box = width * 0.2
img_height_box = height * 0.2
for _ in range(9):
    start_pointX = random.uniform(0, img_width_box)
    start_pointY = random.uniform(0, img_height_box)
    # copyImg = img[int(start_pointX):int(200), int(start_pointY):int(200)]
    copyImg = img[start_pointX:200, start_pointY:200]
    cv2.imshow("textxaunzahun", copyImg)
    cv2.waitKey(0)

报错:
在这里插入图片描述

copyImg = img[start_pointX:200, start_pointY:200]

这行导致整个数组变成了浮点数格式的数组,而浮点数是不可以用来作为数组的下标的。
改成如下

copyImg = img[int(start_pointX):int(200), int(start_pointY):int(200)]

成功解决问题

猜你喜欢

转载自blog.csdn.net/weixin_37411471/article/details/89374569