models icon indicating copy to clipboard operation
models copied to clipboard

Mask Output for Object detection in TF-Serving is of [100 * 33 * 33 ]

Open aashish-0393 opened this issue 7 years ago • 13 comments

Hi.

I am deploying ObjectDetection Mask (From their Model zoo) Pretrained model on tensorflow Serving. When hitting the API with the image array, I am getting Mask in strange manner. Rest all the outputs are OK. For Mask I am getting below output : an array of [100 * 33 * 33 ] instead of [Nwidthheight]. - this resultant array dimensions are same for different image sizes. The array contains float values but not 0 and 1

Is this expected or something has to be changed from my side??

aashish-0393 avatar Feb 08 '19 12:02 aashish-0393

Thank you for your post. We noticed you have not filled out the following field in the issue template. Could you update them if they are relevant in your case, or leave them as N/A? Thanks. What is the top-level directory of the model you are using Have I written custom code OS Platform and Distribution TensorFlow installed from TensorFlow version Bazel version CUDA/cuDNN version GPU model and memory Exact command to reproduce

tensorflowbutler avatar Feb 09 '19 12:02 tensorflowbutler

What is the top-level directory of the model you are using Have I written custom code : No, Just using mask_rcnn_resnet101_atrous_coco pretrained model OS Platform and Distribution : Ubuntu 16.04 TensorFlow installed from conda TensorFlow version 1.12.0 Bazel version : NA CUDA/cuDNN version cuda : V9.0.176 GPU model and memory NA CPU : Intel(R) Xeon(R) Platinum 8124M CPU @ 3.00GHz RAM : 8gb Exact command to reproduce : response = requests.post(http://localhost:8501/v1/models/mask_rcnn_resnet101_atrous_coco :predict, json=payload)

aashish-0393 avatar Feb 11 '19 05:02 aashish-0393

Hi @aashish-0393, did you find a solution? I am facing a similar situation. I am trying to process the output masks in the C++ API. In my case, I have a tensor of 300x15x15, where I know 300 is the total number of detected objects. The 15x15 matrix consists of float numbers ranging from 0 to 1. I wonder what is the exact process needed to get those 15x15 values to become my pixel instance mask.

mldm4 avatar Feb 26 '19 16:02 mldm4

Hi All,

The problem is that exporter.py doesn't have functionality to map 15X15 masks to the original image size using utils_ops.reframe_box_masks_to_image_masks function ?

can we please fix the export graph code to make sure the masks are of the original image size but not 15 x 15 images.

Thank you.

tumusudheer avatar Mar 21 '19 23:03 tumusudheer

@aashish-0393 , from what I understand if the mask is an array with length [100 * 33 * 33]. Then your proposal is 100 and your mask is 33x33. So, do a np.reshape(masks_array, (100, 33, 33)). Then resize all of the masks using something like cv2.resize to the size of the predicted bounding box. Then, place the resized masks on a 1-channel black image, the same size as your original image , i.e.

...
mask_temp = np.zeros((img.shape[0], img.shape[1])
mask_temp[bb_ymin:bb_ymax, bb_xmin:bb_xmax] = mask_resized
mask_temp[mask_temp>0.5] = 1
...

Hope this helps.

david-imagr avatar Mar 25 '19 04:03 david-imagr

Hi @mldm4 Even I am writing a C+ inference code for MaskRCNN. Were you able to solve your problem?

deepikakanade avatar Apr 22 '19 17:04 deepikakanade

Hi all (and thanks @deepikakanade for reminding me this thread),

I eventually found how to process the output mask. It must be done as indicated in page 5 in the MaskRCNN paper (https://arxiv.org/pdf/1703.06870.pdf):

The m×m floating-number mask output is then resized to the RoI size, and binarized at a threshold of 0.5.

Just like magic, your mask will appear ;D

mldm4 avatar Apr 22 '19 18:04 mldm4

@mldm4 Thank you for the prompt response. Do you have the C++ code for this operation? I am getting an output of (100,15,15) and I am trying to resize it to the original image size in C++. It would be really helpful to get some insight on this.

Thanks.

deepikakanade avatar Apr 22 '19 18:04 deepikakanade

@deepikakanade I used a commercial external library in C++, but I am sure you can easily get it done with something like OpenCV. Good luck!

PD: you have some Python clues in @david-imagr reply:

@aashish-0393 , from what I understand if the mask is an array with length [100 * 33 * 33]. Then your proposal is 100 and your mask is 33x33. So, do a np.reshape(masks_array, (100, 33, 33)). Then resize all of the masks using something like cv2.resize to the size of the predicted bounding box. Then, place the resized masks on a 1-channel black image, the same size as your original image , i.e.

...
mask_temp = np.zeros((img.shape[0], img.shape[1])
mask_temp[bb_ymin:bb_ymax, bb_xmin:bb_xmax] = mask_resized
mask_temp[mask_temp>0.5] = 1
...

Hope this helps.

mldm4 avatar Apr 22 '19 18:04 mldm4

Here is my python code to resize the detection_masks for a single image inference from a TensorFlow Model Server:

import requests
import json
import PIL

def resize_predictions_detection_masks(predictions={}, image_shape=('height','width','channels'), mask_threshold=0., verbose=1, debug=1):
    #import PIL
    detection_masks = []
    
    for idx, detection_mask in enumerate(predictions['detection_masks']):
        height, width, _ = image_shape
        # background_mask with all black=0
        mask = np.zeros((height, width))

        ## Get normalised bbox coordinates
        ymin, xmin, ymax, xmax = predictions['detection_boxes'][idx]

        ## Convert to image size fixed bbox coordinates
        ymin, xmin, ymax, xmax = int(ymin*height), int(xmin*width), int(ymax*height), int(xmax*width)

        ## Define bbox height and width 
        bbox_height, bbox_width = ymax-ymin, xmax-xmin

        ## Resize 'detection_mask' to bbox size 
        bbox_mask = np.array(
            PIL.Image.fromarray(np.uint8(np.array(detection_mask)*255), mode='L').resize(
                size=(bbox_width, bbox_height), resample=Image.NEAREST)  # Image.NEAREST is fastest and no weird artefacts
        )
        
        ## Insert detection_mask into image.size np.zeros((height, width)) background_mask
        mask[ymin:ymax, xmin:xmax] = bbox_mask
        mask_threshold = mask_threshold  
        mask = np.where(mask>(mask_threshold*255), 1, mask)   # mask_threshold > 0.5 resulting mask seems too coarse, any value > 0 seems resulting in better masks
        if mask_threshold > 0: mask = np.where(mask!=1, 0, mask)   # in case threshold is used to have other values (0)
        
        if debug: 
            try:
                assert(
                    (np.unique(mask)==np.array([0., 1.])).all() # in case, bbox_mask has (0,1)
                    or 
                    (np.unique(mask)==np.array([0.])).all()  # in case, bbox_mask resulted in only (0)
                )
            except Exception as e:
                print(e)
                print('Mask Index:', idx)
                print('Mask unique values: ', np.unique(mask))
                print('Expected unique values: ', np.array([0., 1.]))
                break

        ## Verbose first detection_mask 
        if (verbose==True or debug==True) and idx==0: 
            print('Index (Example): ', idx)
            print('detection_mask shape():', np.array(detection_mask).shape)
            print('detection_boxes:', predictions['detection_boxes'][idx])
            print('[email protected] (ymin, xmin, ymax, xmax) :', [ymin, xmin, ymax, xmax])
            print('detection_boxes (height, width):', (bbox_height, bbox_width))
        
        
        ## Append mask to list() 'detection_masks'
        detection_masks.append(mask.astype(np.uint8))
    
    return detection_masks

detection_masks = resize_predictions_detection_masks(
    predictions=requests.post("http://localhost:8501/v1/models/1:predict", data=data).json()['predictions'][0]
    , image_shape=image_np.shape
    , verbose=1
    , debug=0.
)

Hope that helps. NB: debug=1 makes it 5x slower for me so make sure to switch it off after successful testing.

Paperone80 avatar Jul 09 '19 02:07 Paperone80

On the topic, I tested and found that loading the same checkpoint but as frozen_inference_graph.pb instead of saved_model into a Jupyterhub InteractiveSession does return the full size mask, i.d. mask.size == image.size when running Google's run_inference_for_single_image() code.

Does anyone know how to config Tensorflow Model Server to have different output dimensions. 15x15 for a mask is a bit rough on the edges...

My guess is to customize the GraphDef which returns currently: $ curl -X GET http://localhost:8501/v1/models/1/metadata

{ "model_spec":{ "name": "1", "signature_name": "", "version": "1" } , "metadata": {"signature_def": { "signature_def": { "serving_default": { "inputs": {"inputs": {...} }, "outputs": {...,"detection_masks": { "dtype": "DT_FLOAT", "tensor_shape": { "dim": [ { "size": "-1", "name": "" }, { "size": "300", "name": "" }, { "size": "15", "name": "" }, { "size": "15", "name": "" } ], "unknown_rank": false }, "name": "detection_masks:0" } }, "method_name": "tensorflow/serving/predict" } } } } }

I just started playing with Tensorflow Servering yesterday, so any pointers how to configure are much appreciated. Thanks.

Paperone80 avatar Jul 09 '19 03:07 Paperone80

Hi There, We are checking to see if you still need help on this, as this seems to be an old issue. Please update this issue with the latest information, code snippet to reproduce your issue and error you are seeing. If we don't hear from you in the next 7 days, this issue will be closed automatically. If you don't need help on this issue any more, please consider closing this.

tensorflowbutler avatar Mar 18 '20 21:03 tensorflowbutler

requests.post("http://localhost:8501/v1/models/1:predict", data=data)

While looking for the solution to an issue I am facing right now, I somehow landed on this thread, I want to serve my custom object detection model using TensorFlow serving, I had followed various solutions and converted my .ckpt saved model to .pb along with variables folder. I had changed the exporter.py file and got my model in this format.

What I am struggling to achieve is to get the correct prediction, when I run the tersorflow_model_server at localhost:9000 and send a POST request to it with an expanded image array I am getting the exact same output for different input images.

does anybody have a clue why am I getting exactly the same response for any kind of input image?

django15 avatar Feb 11 '22 10:02 django15