-
Notifications
You must be signed in to change notification settings - Fork 12
/
test.py
73 lines (53 loc) · 2.17 KB
/
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import argparse
import cv2
import numpy as np
import os
import pathlib
import torch
import models
from utils import image
parser = argparse.ArgumentParser(description='Semantic segmentation of IDCard in Image.')
parser.add_argument('input', type=str, help='Image (with IDCard) Input file')
parser.add_argument('--output_mask', type=str, default='output_mask.png', help='Output file for mask')
parser.add_argument('--output_prediction', type=str, default='output_pred.png', help='Output file for image')
parser.add_argument('--model', type=str, default='./pretrained/model_checkpoint.pt', help='Path to checkpoint file')
args = parser.parse_args()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
INPUT_FILE = args.input
OUTPUT_MASK = args.output_mask
OUTPUT_FILE = args.output_prediction
MODEL_FILE = args.model
def predict_image(model, image):
with torch.no_grad():
output = model(image.to(device))
output = output.detach().cpu().numpy()[0]
output = output.transpose((1, 2, 0))
output = np.uint8(output)
_, output = cv2.threshold(output, 127, 255, cv2.THRESH_BINARY_INV)
return output
def main():
if not os.path.isfile(INPUT_FILE):
print('Input image not found ', INPUT_FILE)
else:
if not os.path.isfile(MODEL_FILE):
print('Model not found ', MODEL_FILE)
else:
print('Load model... ', MODEL_FILE)
model = models.UNet(n_channels=1, n_classes=1)
checkpoint = torch.load(pathlib.Path(MODEL_FILE))
model.load_state_dict(checkpoint)
model.to(device)
model.eval()
print('Load image... ', INPUT_FILE)
img, h, w = image.load_image(INPUT_FILE)
print('Prediction...')
output_image = predict_image(model, img)
print('Resize mask to original size...')
mask_image = cv2.resize(output_image, (w, h))
cv2.imwrite(OUTPUT_MASK, mask_image)
print('Cut it out...')
warped = image.extract_idcard(cv2.imread(INPUT_FILE), mask_image)
cv2.imwrite(OUTPUT_FILE, warped)
print('Done.')
if __name__ == '__main__':
main()