def sliding_window(image, model, overlapping_percentage, size_of_images): c1, c2 = 0, 0 a, b = image.size number_of_steps = int(b / (size_of_images * (1 - overlapping_percentage))) x, y = int(size_of_images / 2) + 1, int(size_of_images / 2) + 1 L = [] for i in range(0, number_of_steps - 1): y = int(size_of_images / 2) + 1 while x < b - size_of_images / 2 and y < a - size_of_images / 2: c1 += 1 cropped_image = image.crop( (y - size_of_images / 2, x - size_of_images / 2, y + size_of_images / 2, x + size_of_images / 2)) crop = data_transforms(cropped_image) crop = crop.unsqueeze(0) prob = model(crop) probability = round(sigmoid(float(prob[0][1])), 1) prediction = prob.data.numpy().argmax() # print(y) if prediction == 1: # print(c2) # print(c1) L.append([cropped_image, x, y, probability]) c2 += 1 y += int(size_of_images * (1 - overlapping_percentage)) x += int(size_of_images * (1 - overlapping_percentage)) return (L)
print('Using CPU') from data import data_transforms test_dir = args.data + '/test_images/mistery_category' def pil_loader(path): # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835) with open(path, 'rb') as f: with Image.open(f) as img: return img.convert('RGB') output_file = open(args.outfile, "w") output_file.write("Id,Category\n") for f in tqdm(os.listdir(test_dir)): if 'jpg' in f: data = data_transforms(pil_loader(test_dir + '/' + f)) data = data.view(1, data.size(0), data.size(1), data.size(2)) if use_cuda: data = data.cuda() output = model(data) pred = output.data.max(1, keepdim=True)[1] output_file.write("%s,%d\n" % (f[:-4], pred)) output_file.close() print("Succesfully wrote " + args.outfile + ', you can upload this file to the kaggle competition website')
state_dict = torch.load(args.model) model = Net() model.load_state_dict(state_dict) model.eval() def pil_loader(path): # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835) with open(path, 'rb') as f: with Image.open(f) as img: return img.convert('RGB') for f in tqdm(os.listdir(test_dir)): if 'ppm' in f: data = data_transforms(pil_loader('/' + f)) data = data.view(1, data.size(0), data.size(1), data.size(2)) data = Variable(data, volatile=True) output = model(data) pred = output.data.max(1, keepdim=True)[1] file_id = f[0:5] output_file.write("%s,%d\n" % (file_id, pred)) if (pred == 0): classification = 'Non - Recyclable' else: classification = 'Recyclable' print(classification) if __name__ == '__main__':