numpy - TypeError:切片索引必须是整数或无或具有 __index__ 方法(Albumentations/NumPy)
问题描述
大家好,您能帮我解决一下随机作物增强的问题。TypeError:切片索引必须是整数或无或具有索引方法
代码如下。
!conda install -c conda-forge gdcm -y
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
import cv2 as cv
import albumentations as A
import pydicom
from pydicom.pixel_data_handlers.util import apply_voi_lut
from tqdm.auto import tqdm
def read_img(path, voi_lut=True, fix_monochrome=True):
dcm = pydicom.read_file(path)
if voi_lut:
img = apply_voi_lut(dcm.pixel_array, dcm)
else:
img = dcm.pixel_array
if fix_monochrome and dcm.PhotometricInterpretation == "MONOCHROME1":
img = np.amax(img) - img
img = img - np.min(img)
img = img / np.max(img)
img = (img * 255).astype(np.uint8)
return img
def resize_img(img, size, pad=True, resample=Image.LANCZOS):
img = np.array(img)
if pad:
max_width = 4891
max_height = 4891
img = np.pad(img, ((0, max_height - img.shape[0]), (0, max_width - img.shape[1]), (0, 0)))
img = img.resize((size, size), resample)
return img
def augment_img(img, clahe=True, albumentations=True):
if clahe:
clahe = cv.createCLAHE(clipLimit=15.0, tileGridSize=(8,8))
img = clahe.apply(img)
else:
img = cv.equalizeHist(img)
if albumentations:
img = np.stack((img, ) * 3, axis=-1)
transform = A.Compose([
A.RandomSunFlare(p=0.2),
A.RandomFog(p=0.2),
A.RandomBrightness(p=0.2),
A.RandomCrop(p=1.0, width=img.shape[0] / 2, height=img.shape[1] / 2),
A.Rotate(p=0.2, limit=90),
A.RGBShift(p=0.2),
A.RandomSnow(p=0.2),
A.HorizontalFlip(p=0.2),
A.VerticalFlip(p=0.2),
A.RandomContrast(p=0.2, limit=0.2),
A.HueSaturationValue(p=0.2, hue_shift_limit=20, sat_shift_limit=30, val_shift_limit=50)
])
img = transform(image=img)["image"]
return img
img = read_img('../input/siim-covid19-detection/test/00188a671292/3eb5a506ccf3/3dcdfc352a06.dcm') #You can replace this with any .dcm filepath on your system
img = augment_img(img)
img = resize_img(img, 1024)
plt.imshow(img, cmap='gray')
这是针对 SIIM Kaggle 比赛的。我不知道如何解决这个问题,问题只是随机裁剪。我尝试在线搜索,但我无法。
解决方案
我认为错误在这一行:
A.RandomCrop(p=1.0, width=img.shape[0] / 2, height=img.shape[1] / 2)
这里的问题是您的宽度和高度可能不是整数,但它们必须是。
检查Albumentations RandomCrop 文档。
这是解决方案。
- 将宽度和高度参数显式转换为整数:
A.RandomCrop(p=1.0, width=int(img.shape[0] / 2), height=int(img.shape[1] / 2))
- 使用整数除法:
A.RandomCrop(p=1.0, width=img.shape[0] // 2, height=img.shape[1] // 2)
让我知道它是否有帮助!
推荐阅读
- javascript - 动态创建的输入元素的 html 数组在 PHP Serverside 中未正确解释
- android - Android Studio 无法在 Linux Mint 中安装 GPU 调试工具
- r - 将表数据解析为 R 但它是空白的,javascript?
- visual-studio - 如何使用用户定义的参数/变量触发 SSIS 包的数据流元素?
- c# - 在 SIMD Avx.CompareEqual 中查找所有匹配位置,或在计算匹配时查找整个数组
- python - 不懂双重列表查找
- python - 如何从单个 tkinter Entry 小部件获取不同变量的整数输入?
- angular - 即时渲染复杂的结构化组件
- angular - 使用两种方式绑定 Angular2+ 连接 HTML 选择选项
- jquery - div 上的禁用属性仍会触发点击事件