ValueError:无法将大小为1251936的数组重塑为形状(1118,1118)

问题描述 投票:1回答:1

这似乎是一个经常被问到的问题,但是问题是我理解了这个错误,但是要获得尺寸为2的形状的1251936,则需要(1118.89945929024,1118.89945929024),但此数字必须是整数,然后是1118。给1249924,那是个问题。

def create_features(img):

    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    features, _ = train.create_features(img, img_gray, label=None, train=False)

    return features

def compute_prediction(img, model):

    border = 5 # (haralick neighbourhood - 1) / 2

    img = cv2.copyMakeBorder(img, top=border, bottom=border, \
                                  left=border, right=border, \
                                  borderType = cv2.BORDER_CONSTANT, \
                                  value=[0, 0, 0])

    features = create_features(img)
    predictions = model.predict(features.reshape(-1, features.shape[1]))
    pred_size = int(math.sqrt(features.shape[0]))
    inference_img = predictions.reshape(pred_size, pred_size)

    return inference_img

def infer_images(image_dir, model_path, output_dir):

    filelist = glob(os.path.join(image_dir,'*.png'))

    print ('[INFO] Running inference on %s test images' %len(filelist))

    model = pkl.load(open( model_path, "rb" ) )

    for file in filelist:
        print ('[INFO] Processing images:', os.path.basename(file))
        inference_img = compute_prediction(cv2.imread(file, 1), model)
        cv2.imwrite(os.path.join(output_dir, os.path.basename(file)), inference_img)

python cv2
1个回答
0
投票

您的错误已连接到线路:

predictions = model.predict(features.reshape(-1, features.shape[1]))

这里您的数组predictions不是正方形数组,大小为1251936。这就是为什么当你做

pred_size = int(math.sqrt(features.shape[0]))
inference_img = predictions.reshape(pred_size, pred_size)

您有错误。因此,您应该在进行重塑之前检查形状。我可以猜测错误的来源是添加了边框。因此,请检查边框尺寸。您要在此处添加边框:

border = 5 # (haralick neighbourhood - 1) / 2
img = cv2.copyMakeBorder(img, top=border, bottom=border, \
                              left=border, right=border, \
                              borderType = cv2.BORDER_CONSTANT, \
                              value=[0, 0, 0])
© www.soinside.com 2019 - 2024. All rights reserved.