这似乎是一个经常被问到的问题,但问题是我理解了这个错误,但是要获得尺寸为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)

最佳答案

您的错误已连接到线路:

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])

09-20 10:42