如何在不获取“TypeError:字符串索引必须是整数”的情况下对图像进行numpyslicing

2024-06-15 20:29:10 发布

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

我得到一个错误:

"TypeError: string indices must be integers"

当我试图裁剪图像时

我试着写一个函数,裁剪出一个矩形的图像,从而得到一个正方形的图像并居中。你知道吗

def squared_and_resized(img,resized_dim):
    image = cv2.imread(img)
    img_height,img_width = image.shape[:2]
    if (img_width > img_height):
            start_row = 0
            end_row = img_height
            start_col = math.floor((img_width - img_height) /2)
            end_col = math.floor((img_width + img_height) /2)
    else:
            start_col = 0
            end_col = img_width
            start_row = math.floor((img_height-img_width)/2)
            end_row = start_row + img_width

    squared_img = img[start_row:end_row , start_col:end_col]

    resized_img = cv2.resize(squared_img,(resized_dim, resized_dim))
    return resized_img

Tags: 图像imageimgcolmathwidthcv2start
2条回答

你知道吗数学地板返回浮点型变量。你可以用int(math.floor((img_height-img_width)/2))

错误在以下行:squared_img = img[start_row:end_row , start_col:end_col]。在代码检查时,似乎imgstr类型,它被传递给这个方法,然后用于图像切片。您可能需要使用squared_img = image[start_row:end_row , start_col:end_col]

为了在将来缓解此问题,请使用有意义的名称。在本例中,方法param可以命名为image_path。你知道吗

相关问题 更多 >