def predict(dataset_name, input_path, output_path):
dataset = Dataset(dataset_name)
net = caffe.Net(dataset.model_path, dataset.pretrained_path, caffe.TEST)
label_margin = 186
input_dims = net.blobs['data'].shape
batch_size, num_channels, input_height, input_width = input_dims
caffe_in = np.zeros(input_dims, dtype=np.float32)
image = cv2.imread(input_path, 1).astype(np.float32) - dataset.mean_pixel
image_size = image.shape
output_height = input_height - 2 * label_margin
output_width = input_width - 2 * label_margin
image = cv2.copyMakeBorder(image, label_margin, label_margin,
label_margin, label_margin,
cv2.BORDER_REFLECT_101)
num_tiles_h = image_size[0] // output_height + \
(1 if image_size[0] % output_height else 0)
num_tiles_w = image_size[1] // output_width + \
(1 if image_size[1] % output_width else 0)
prediction = []
for h in range(num_tiles_h):
col_prediction = []
for w in range(num_tiles_w):
offset = [output_height * h,
output_width * w]
tile = image[offset[0]:offset[0] + input_height,
offset[1]:offset[1] + input_width, :]
margin = [0, input_height - tile.shape[0],
0, input_width - tile.shape[1]]
tile = cv2.copyMakeBorder(tile, margin[0], margin[1],
margin[2], margin[3],
cv2.BORDER_REFLECT_101)
caffe_in[0] = tile.transpose([2, 0, 1])
out = net.forward_all(**{net.inputs[0]: caffe_in})
prob = out['prob'][0]
col_prediction.append(prob)
# print('concat row')
col_prediction = np.concatenate(col_prediction, axis=2)
prediction.append(col_prediction)
prob = np.concatenate(prediction, axis=1)
if dataset.zoom > 1:
prob = util.interp_map(prob, dataset.zoom, image_size[1], image_size[0])
prediction = np.argmax(prob.transpose([1, 2, 0]), axis=2)
color_image = dataset.palette[prediction.ravel()].reshape(image_size)
color_image = cv2.cvtColor(color_image, cv2.COLOR_RGB2BGR)
print('Writing', output_path)
cv2.imwrite(output_path, color_image)
评论列表
文章目录