对于相同的图像大小,mask-rcnn 的多图像推理运行速度比 faster-rcnn 慢 10 倍
Multiple image inference for mask-rcnn runs ~10x slower than faster-rcnn for the same image size
我使用自己的自定义数据集成功地重新训练了 mask-rcnn 和 faster-rcnn 模型,我想 运行 对多个图像进行推理。我使用下面的代码修改了演示中的单图像推理功能。如果我使用再训练的 faster-rcnn resnet101,我会得到以下结果
如果我使用重新训练的 mask-rcnn resnet101,则结果如下
下面如果我运行用faster-rcnn inception-resnet
以及以下与 mask-rcnn inception-resnet
所有图像的分辨率均为 1024x768。请帮助这是否是正确的行为。谢谢
下面的函数是我根据demo修改的
def run_inference_for_multiple_images(images, graph):
with graph.as_default():
with tf.Session() as sess:
output_dict_array = []
dict_time = []
for image in images:
# Get handles to input and output tensors
ops = tf.get_default_graph().get_operations()
all_tensor_names = {output.name for op in ops for output in op.outputs}
tensor_dict = {}
for key in ['num_detections', 'detection_boxes', 'detection_scores',
'detection_classes', 'detection_masks']:
tensor_name = key + ':0'
if tensor_name in all_tensor_names:
tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
tensor_name)
if 'detection_masks' in tensor_dict:
detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
# Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
detection_masks, detection_boxes, image.shape[0], image.shape[1])
detection_masks_reframed = tf.cast(
tf.greater(detection_masks_reframed, 0.5), tf.uint8)
# Follow the convention by adding back the batch dimension
tensor_dict['detection_masks'] = tf.expand_dims(
detection_masks_reframed, 0)
image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
# Run inference
start = time.time()
output_dict = sess.run(tensor_dict,
feed_dict={image_tensor: np.expand_dims(image, 0)})
end = time.time()
print('inference time : {}'.format(end-start))
# all outputs are float32 numpy arrays, so convert types as appropriate
output_dict['num_detections'] = int(output_dict['num_detections'][0])
output_dict['detection_classes'] = output_dict[
'detection_classes'][0].astype(np.uint8)
output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
output_dict['detection_scores'] = output_dict['detection_scores'][0]
if 'detection_masks' in output_dict:
output_dict['detection_masks'] = output_dict['detection_masks'][0]
output_dict_array.append(output_dict)
dict_time.append(end-start)
return output_dict_array, dict_time
下面是运行函数
的一段代码
batch_size = 10
chunks = len(diff_files) // batch_size + 1
ave_time = []
for i in range(chunks):
batch = diff_files[i*batch_size:(i+1)*batch_size]
images = []
files = []
proc_time = []
for file in batch:
image_path = os.path.join(subdir_path, file)
print('Reading file {}'.format(image_path))
image = cv2.imread(image_path)
image_np = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
images.append(image_np)
files.append(file)
output_dicts, out_time = run_inference_for_multiple_images(images, detection_graph)
print('length of output_dicts is : {}'.format(len(output_dicts)))
if len(output_dicts) == 0:
break
for idx in range(len(output_dicts)):
output_dict = output_dicts[idx]
image_np = images[idx]
file = files[idx]
# Visualization of the results of a detection.
start = time.time()
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
output_dict['detection_boxes'],
output_dict['detection_classes'],
output_dict['detection_scores'],
category_index,
instance_masks=output_dict.get('detection_masks'),
use_normalized_coordinates=True, min_score_thresh=.5,
line_thickness=4, skip_scores=False,
skip_labels=False,
skip_boxes=False)
height, width, chan = image_np.shape
# Saving the processed image
image_np = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
cv2.imwrite(os.path.join(result_img_path, file), image_np)
print('Saving {}, time : {}'.format(file, time.time()-start))
proc_time.append(time.time()-start + out_time[idx])
# count += 1
if len(proc_time) != 0:
mean_batch_time = statistics.mean(proc_time)
print('mean processing time: {}'.format(mean_batch_time))
ave_time.append(mean_batch_time)
proc_time.clear()
output_dicts.clear()
我发现了问题,以下功能似乎可以使用。每个图像的平均推理时间从大约 3-4 秒减少到 0.3-0.4 秒(使用 resnet50 特征提取器)。但是,使用此函数时必须小心,因为使用批量大小图像时的假设是所有图像必须具有相同的大小。因此,当批次中的其中一张图像具有不同尺寸时会抛出错误。虽然我自己还没有证实这一点。
def run_inference_for_multiple_images(images, graph):
with graph.as_default():
with tf.Session() as sess:
output_dict_array = []
dict_time = []
# Get handles to input and output tensors
ops = tf.get_default_graph().get_operations()
all_tensor_names = {output.name for op in ops for output in op.outputs}
tensor_dict = {}
for key in ['num_detections', 'detection_boxes', 'detection_scores',
'detection_classes', 'detection_masks']:
tensor_name = key + ':0'
if tensor_name in all_tensor_names:
tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(tensor_name)
if 'detection_masks' in tensor_dict:
detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
# Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
detection_masks, detection_boxes, images[0].shape[0], images[0].shape[1])
detection_masks_reframed = tf.cast(tf.greater(detection_masks_reframed, 0.5), tf.uint8)
# Follow the convention by adding back the batch dimension
tensor_dict['detection_masks'] = tf.expand_dims(detection_masks_reframed, 0)
image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
for image in images:
# Run inference
start = time.time()
output_dict = sess.run(tensor_dict, feed_dict={image_tensor: np.expand_dims(image, 0)})
end = time.time()
print('inference time : {}'.format(end - start))
# all outputs are float32 numpy arrays, so convert types as appropriate
output_dict['num_detections'] = int(output_dict['num_detections'][0])
output_dict['detection_classes'] = output_dict['detection_classes'][0].astype(np.uint8)
output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
output_dict['detection_scores'] = output_dict['detection_scores'][0]
if 'detection_masks' in output_dict:
output_dict['detection_masks'] = output_dict['detection_masks'][0]
output_dict_array.append(output_dict)
dict_time.append(end - start)
return output_dict_array, dict_time
我使用自己的自定义数据集成功地重新训练了 mask-rcnn 和 faster-rcnn 模型,我想 运行 对多个图像进行推理。我使用下面的代码修改了演示中的单图像推理功能。如果我使用再训练的 faster-rcnn resnet101,我会得到以下结果
下面的函数是我根据demo修改的
def run_inference_for_multiple_images(images, graph):
with graph.as_default():
with tf.Session() as sess:
output_dict_array = []
dict_time = []
for image in images:
# Get handles to input and output tensors
ops = tf.get_default_graph().get_operations()
all_tensor_names = {output.name for op in ops for output in op.outputs}
tensor_dict = {}
for key in ['num_detections', 'detection_boxes', 'detection_scores',
'detection_classes', 'detection_masks']:
tensor_name = key + ':0'
if tensor_name in all_tensor_names:
tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
tensor_name)
if 'detection_masks' in tensor_dict:
detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
# Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
detection_masks, detection_boxes, image.shape[0], image.shape[1])
detection_masks_reframed = tf.cast(
tf.greater(detection_masks_reframed, 0.5), tf.uint8)
# Follow the convention by adding back the batch dimension
tensor_dict['detection_masks'] = tf.expand_dims(
detection_masks_reframed, 0)
image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
# Run inference
start = time.time()
output_dict = sess.run(tensor_dict,
feed_dict={image_tensor: np.expand_dims(image, 0)})
end = time.time()
print('inference time : {}'.format(end-start))
# all outputs are float32 numpy arrays, so convert types as appropriate
output_dict['num_detections'] = int(output_dict['num_detections'][0])
output_dict['detection_classes'] = output_dict[
'detection_classes'][0].astype(np.uint8)
output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
output_dict['detection_scores'] = output_dict['detection_scores'][0]
if 'detection_masks' in output_dict:
output_dict['detection_masks'] = output_dict['detection_masks'][0]
output_dict_array.append(output_dict)
dict_time.append(end-start)
return output_dict_array, dict_time
下面是运行函数
的一段代码batch_size = 10
chunks = len(diff_files) // batch_size + 1
ave_time = []
for i in range(chunks):
batch = diff_files[i*batch_size:(i+1)*batch_size]
images = []
files = []
proc_time = []
for file in batch:
image_path = os.path.join(subdir_path, file)
print('Reading file {}'.format(image_path))
image = cv2.imread(image_path)
image_np = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
images.append(image_np)
files.append(file)
output_dicts, out_time = run_inference_for_multiple_images(images, detection_graph)
print('length of output_dicts is : {}'.format(len(output_dicts)))
if len(output_dicts) == 0:
break
for idx in range(len(output_dicts)):
output_dict = output_dicts[idx]
image_np = images[idx]
file = files[idx]
# Visualization of the results of a detection.
start = time.time()
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
output_dict['detection_boxes'],
output_dict['detection_classes'],
output_dict['detection_scores'],
category_index,
instance_masks=output_dict.get('detection_masks'),
use_normalized_coordinates=True, min_score_thresh=.5,
line_thickness=4, skip_scores=False,
skip_labels=False,
skip_boxes=False)
height, width, chan = image_np.shape
# Saving the processed image
image_np = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
cv2.imwrite(os.path.join(result_img_path, file), image_np)
print('Saving {}, time : {}'.format(file, time.time()-start))
proc_time.append(time.time()-start + out_time[idx])
# count += 1
if len(proc_time) != 0:
mean_batch_time = statistics.mean(proc_time)
print('mean processing time: {}'.format(mean_batch_time))
ave_time.append(mean_batch_time)
proc_time.clear()
output_dicts.clear()
我发现了问题,以下功能似乎可以使用。每个图像的平均推理时间从大约 3-4 秒减少到 0.3-0.4 秒(使用 resnet50 特征提取器)。但是,使用此函数时必须小心,因为使用批量大小图像时的假设是所有图像必须具有相同的大小。因此,当批次中的其中一张图像具有不同尺寸时会抛出错误。虽然我自己还没有证实这一点。
def run_inference_for_multiple_images(images, graph):
with graph.as_default():
with tf.Session() as sess:
output_dict_array = []
dict_time = []
# Get handles to input and output tensors
ops = tf.get_default_graph().get_operations()
all_tensor_names = {output.name for op in ops for output in op.outputs}
tensor_dict = {}
for key in ['num_detections', 'detection_boxes', 'detection_scores',
'detection_classes', 'detection_masks']:
tensor_name = key + ':0'
if tensor_name in all_tensor_names:
tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(tensor_name)
if 'detection_masks' in tensor_dict:
detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
# Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
detection_masks, detection_boxes, images[0].shape[0], images[0].shape[1])
detection_masks_reframed = tf.cast(tf.greater(detection_masks_reframed, 0.5), tf.uint8)
# Follow the convention by adding back the batch dimension
tensor_dict['detection_masks'] = tf.expand_dims(detection_masks_reframed, 0)
image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
for image in images:
# Run inference
start = time.time()
output_dict = sess.run(tensor_dict, feed_dict={image_tensor: np.expand_dims(image, 0)})
end = time.time()
print('inference time : {}'.format(end - start))
# all outputs are float32 numpy arrays, so convert types as appropriate
output_dict['num_detections'] = int(output_dict['num_detections'][0])
output_dict['detection_classes'] = output_dict['detection_classes'][0].astype(np.uint8)
output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
output_dict['detection_scores'] = output_dict['detection_scores'][0]
if 'detection_masks' in output_dict:
output_dict['detection_masks'] = output_dict['detection_masks'][0]
output_dict_array.append(output_dict)
dict_time.append(end - start)
return output_dict_array, dict_time