Skip to content

Same mask rcnn model shows different result between tensorflow and opencv dnn module #14480

Closed

Description

@stq054188
System information (version)
  • OpenCV => 4.1.0
  • Operating System / Platform => Windows10 64 Bit
  • Compiler => Visual Studio 2017
  • Tensorflow => 1.10.0
  • Python vision =>3.5.1
Detailed description

I have trained a mask rcnn model, so I tested it with tensorflow and opencv dnn module, but it showed different result between tensorflow and opencv dnn module. The tensorflow result is more accurate than opencv dnn module.

1

2

Steps to reproduce
  1. my C++ opencv code is OpenCV_Mask_RCNN.cpp
  2. my tensorflow py code is mask_rcnn_obj.py
  3. my model file is in model folder
  4. test image is 7.jpg
  5. all files is in files.zip here: https://drive.google.com/open?id=1xTI6_bqbZpi3vbeVcFxX1emBSa7QI58z

@dkurt Would you please help me see if this problem is bug? Thank you very much.

Activity

  1. stq054188 commented on May 6, 2019

    @stq054188
    Author

    @dkurt Would you please help me see this problem, I'm really in a hurry. Thanks.

  2. dkurt commented on May 6, 2019

    @dkurt
    Member

    @stq054188, Please add a configuration file which was used for training and generation of graph.pbtxt.

  3. dkurt commented on May 6, 2019

    @dkurt
    Member

    BTW, this is the output I got with OpenCV's sample with modified mask threshold:

    python mask_rcnn.py --input 7.jpg --model frozen_inference_graph.pb --config graph.pbtxt
    

    from

    mask = (classMask > 0.5)
    

    to

    mask = (classMask > 0.6)
    

    out

    Please note that there are two factors of difference: a bug in TensorFlow's CropAndResize layer (we're working on it: tensorflow/tensorflow#21660) and a .jpg sample. JPEG decoding is not cross platform. Please add a .png sample.

  4. stq054188 commented on May 6, 2019

    @stq054188
    Author

    @dkurt Thank you for your reply and I upload config file and a png sample here.
    config.zip

  5. dkurt commented on May 6, 2019

    @dkurt
    Member

    @stq054188, Please show how desired TensorFlow output has been obtained. For me the following script gives different output:

    import tensorflow as tf
    import cv2 as cv
    import numpy as np
    
    img = cv.imread('7.png')
    inp = cv.resize(img, dsize=(1365, 800))
    inp = inp.reshape(1, 800, 1365, 3)
    
    
    graph = 'model/frozen_inference_graph.pb'
    with tf.gfile.FastGFile(graph) as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
    
    with tf.Session() as sess:
        # Restore session
        sess.graph.as_default()
        tf.import_graph_def(graph_def, name='')
    
        tfOut = sess.run([sess.graph.get_tensor_by_name('num_detections:0'),
                          sess.graph.get_tensor_by_name('detection_scores:0'),
                          sess.graph.get_tensor_by_name('detection_boxes:0'),
                          sess.graph.get_tensor_by_name('detection_classes:0'),
                          sess.graph.get_tensor_by_name('detection_masks:0')],
                         feed_dict={'image_tensor:0': inp})
    
    num = int(tfOut[0])
    scores = tfOut[1] # 1xN
    boxes = tfOut[2] # 1xNx4
    classes = tfOut[3] # 1xN
    masks = tfOut[4] # 1xNx15x15
    
    color = np.array([0, 255, 0], dtype=np.uint8)
    
    for i in range(num):
        score = float(scores[0, i])
        if score < 0.5:
            continue
    
        box = boxes[0, i]
        ymin = int(img.shape[0] * box[0])
        xmin = int(img.shape[1] * box[1])
        ymax = int(img.shape[0] * box[2])
        xmax = int(img.shape[1] * box[3])
    
        classMask = masks[0, i]
        classMask = cv.resize(classMask, (xmax - xmin + 1, ymax - ymin + 1))
        mask = (classMask > 0.5)
    
        roi = img[ymin:ymax+1, xmin:xmax+1][mask]
        img[ymin:ymax+1, xmin:xmax+1][mask] = (0.7 * color + 0.3 * roi).astype(np.uint8)
    
    cv.imwrite('tf.jpg', img)

    tf

  6. stq054188 commented on May 6, 2019

    @stq054188
    Author

    BTW, this is the output I got with OpenCV's sample with modified mask threshold:

    python mask_rcnn.py --input 7.jpg --model frozen_inference_graph.pb --config graph.pbtxt
    

    from

    mask = (classMask > 0.5)
    

    to

    mask = (classMask > 0.6)
    

    out

    Please note that there are two factors of difference: a bug in TensorFlow's CropAndResize layer (we're working on it: tensorflow/tensorflow#21660) and a .jpg sample. JPEG decoding is not cross platform. Please add a .png sample.

    I have test with OpenCV's sample mask_rcnn.py with 7.png it looks to change good, but with small object like grain its location seems to be shifted to the left. This makes me confused.
    2
    I test it with 2.png again, the result is as follow.
    00
    11

  7. stq054188 commented on May 6, 2019

    @stq054188
    Author

    @dkurt Here is my python code, thanks.
    mask_rcnn_obj.zip

  8. dkurt commented on May 6, 2019

    @dkurt
    Member

    @stq054188, Please make it reproducible. There is no utils module there.

  9. stq054188 commented on May 6, 2019

    @stq054188
    Author

    @stq054188, Please make it reproducible. There is no utils module there.

    @dkurt I am sorry, utils is here.
    utils.zip

  10. stq054188 commented on May 6, 2019

    @stq054188
    Author

    @stq054188, Please show how desired TensorFlow output has been obtained. For me the following script gives different output:

    import tensorflow as tf
    import cv2 as cv
    import numpy as np
    
    img = cv.imread('7.png')
    inp = cv.resize(img, dsize=(1365, 800))
    inp = inp.reshape(1, 800, 1365, 3)
    
    
    graph = 'model/frozen_inference_graph.pb'
    with tf.gfile.FastGFile(graph) as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
    
    with tf.Session() as sess:
        # Restore session
        sess.graph.as_default()
        tf.import_graph_def(graph_def, name='')
    
        tfOut = sess.run([sess.graph.get_tensor_by_name('num_detections:0'),
                          sess.graph.get_tensor_by_name('detection_scores:0'),
                          sess.graph.get_tensor_by_name('detection_boxes:0'),
                          sess.graph.get_tensor_by_name('detection_classes:0'),
                          sess.graph.get_tensor_by_name('detection_masks:0')],
                         feed_dict={'image_tensor:0': inp})
    
    num = int(tfOut[0])
    scores = tfOut[1] # 1xN
    boxes = tfOut[2] # 1xNx4
    classes = tfOut[3] # 1xN
    masks = tfOut[4] # 1xNx15x15
    
    color = np.array([0, 255, 0], dtype=np.uint8)
    
    for i in range(num):
        score = float(scores[0, i])
        if score < 0.5:
            continue
    
        box = boxes[0, i]
        ymin = int(img.shape[0] * box[0])
        xmin = int(img.shape[1] * box[1])
        ymax = int(img.shape[0] * box[2])
        xmax = int(img.shape[1] * box[3])
    
        classMask = masks[0, i]
        classMask = cv.resize(classMask, (xmax - xmin + 1, ymax - ymin + 1))
        mask = (classMask > 0.5)
    
        roi = img[ymin:ymax+1, xmin:xmax+1][mask]
        img[ymin:ymax+1, xmin:xmax+1][mask] = (0.7 * color + 0.3 * roi).astype(np.uint8)
    
    cv.imwrite('tf.jpg', img)

    tf

    @dkurt How can I get the same effect as the above picture using opencv?

  11. dkurt commented on May 6, 2019

    @dkurt
    Member

    @stq054188, Still there is no way to reproduce gold results with utils due the following error:

    Traceback (most recent call last):
      File "mask_rcnn_obj.py", line 9, in <module>
        from utils import label_map_util
      File "/path/to/utils/label_map_util.py", line 22, in <module>
        from object_detection.protos import string_int_label_map_pb2
    ImportError: No module named object_detection.protos
    

    However you can try the following:

    • OpenCV

    Modify mask_rcnn.py:

    mask = (classMask > 0.7)
    

    run:

    python mask_rcnn.py --model frozen_inference_graph.pb --config graph.pbtxt --input 7.png --width 1012 --height 800
    

    Where 1012x800 is from the following condition for image of size 2592x2048 (see a config file):

        image_resizer {
          keep_aspect_ratio_resizer {
            min_dimension: 800
            max_dimension: 1365
          }
        }
    

    cv

    TensorFlow code:

    import tensorflow as tf
    import cv2 as cv
    import numpy as np
    
    img = cv.imread('7.png')
    inp = np.expand_dims(img[:,:,[2, 1, 0]], 0)  # Make a 4D blob and convert BGR to RGB
    
    
    graph = 'model/frozen_inference_graph.pb'
    with tf.gfile.FastGFile(graph) as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
    
    with tf.Session() as sess:
        # Restore session
        sess.graph.as_default()
        tf.import_graph_def(graph_def, name='')
    
        tfOut = sess.run([sess.graph.get_tensor_by_name('num_detections:0'),
                          sess.graph.get_tensor_by_name('detection_scores:0'),
                          sess.graph.get_tensor_by_name('detection_boxes:0'),
                          sess.graph.get_tensor_by_name('detection_classes:0'),
                          sess.graph.get_tensor_by_name('detection_masks:0')],
                         feed_dict={'image_tensor:0': inp})
    
    num = int(tfOut[0])
    scores = tfOut[1] # 1xN
    boxes = tfOut[2] # 1xNx4
    classes = tfOut[3] # 1xN
    masks = tfOut[4] # 1xNx15x15
    
    color = np.array([0, 255, 0], dtype=np.uint8)
    
    for i in range(num):
        score = float(scores[0, i])
        if score < 0.2:
            continue
    
        box = boxes[0, i]
        ymin = int(img.shape[0] * box[0])
        xmin = int(img.shape[1] * box[1])
        ymax = int(img.shape[0] * box[2])
        xmax = int(img.shape[1] * box[3])
    
        classMask = masks[0, i]
        classMask = cv.resize(classMask, (xmax - xmin + 1, ymax - ymin + 1))
        mask = (classMask > 0.7)
    
        roi = img[ymin:ymax+1, xmin:xmax+1][mask]
        img[ymin:ymax+1, xmin:xmax+1][mask] = (0.7 * color + 0.3 * roi).astype(np.uint8)
    
        cv.rectangle(img, (xmin, ymin), (xmax, ymax), (255, 0, 255))
    
    cv.imwrite('tf.jpg', img)

    TensorFlow output:
    tf

  12. stq054188 commented on May 7, 2019

    @stq054188
    Author

    @dkurt Thank you again. It seems mask_rcnn.py is correct but my C++ code is still have some problems. I will change it and retest, thanks.

  13. sctrueew commented on Apr 16, 2021

    @sctrueew

    @stq054188 Hi,

    Did you solve the problem? And How did you convert h5 to .pb? I've converted with keras_to_tensorflow.py but I get an error when I use readNet in OpenCVDNN.

  14. Jeffin21 commented on May 8, 2021

    @Jeffin21

    @zpmmehrdad use this code

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    import os
    import sys
    import warnings
    
    import keras.backend as K
    import tensorflow as tf
    
    warnings.filterwarnings('ignore', category=FutureWarning)
    # suppress warning and error message tf
    os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
    
    # Root directory of the project
    ROOT_DIR = os.getcwd()
    # Import Mask RCNN
    sys.path.append(ROOT_DIR)  # To find local version of the library
    from mrcnn import model as modellib
    from mrcnn import utils
    
    import coco 
    K.clear_session()
    K.set_learning_phase(0)
    
    ##############################################################################
    # Load model
    ##############################################################################
    
    
    # Model Directory
    MODEL_DIR = ("/logs")
    DEFAULT_WEIGHTS =  ("/content/drive/MyDrive/thirip2/mask_rcnn_coco.h5")
    # Download COCO trained weights from Releases if needed
    if not os.path.exists(DEFAULT_WEIGHTS):
        utils.download_trained_weights(DEFAULT_WEIGHTS)
    
    ##############################################################################
    # Load configuration
    ##############################################################################
    
    
    
    class InferenceConfig(coco.CocoConfig):
            # Set batch size to 1 since we'll be running inference on
            # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
            GPU_COUNT = 1
            IMAGES_PER_GPU = 1
            
    
    ##############################################################################
    # Save entire model function
    ##############################################################################
    
    def h5_to_pb(h5_model, output_dir, model_name, out_prefix="output_"):
        out_nodes = []
        for i in range(len(h5_model.outputs)):
            out_nodes.append(out_prefix + str(i + 1))
            tf.identity(h5_model.output[i], out_prefix + str(i + 1))
        sess = K.get_session()
        init_graph = sess.graph.as_graph_def()
        main_graph = tf._api.v1.graph_util.convert_variables_to_constants(sess, init_graph, out_nodes)
        with tf.gfile.GFile(os.path.join(output_dir, model_name), "wb") as filemodel:
            filemodel.write(main_graph.SerializeToString())
        print("pb model: ", {os.path.join(output_dir, model_name)})
    
    
    if __name__ == "__main__":
        config = InferenceConfig()
        config.display()
        # Create model in inference mode
        model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
    
        # Set path to model weights
        weights_path = DEFAULT_WEIGHTS#model.find_last()
        # Load weights
        print("Loading weights ", weights_path)
        model.load_weights(weights_path, by_name=True)
        model.keras_model.summary()
    
        # make folder for full model
        model_dir = os.path.join(ROOT_DIR, "Model")
        if not os.path.exists(model_dir):
            os.makedirs(model_dir)
    
        # save h5 full model
        name_model = os.path.join(model_dir, "/content/drive/MyDrive/thirip2/mask_rcnn_bottle_0040.h5")
        if not os.path.exists(name_model):
            model.keras_model.save(name_model)
            print("save model: ", name_model)
    
        # export pb model
        pb_name_model = "mask_rcnn_landing.pb"
        h5_to_pb(model.keras_model, output_dir=model_dir, model_name=pb_name_model)
        K.clear_session()
        sys.exit()
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions