Mask_RCNN icon indicating copy to clipboard operation
Mask_RCNN copied to clipboard

Coco has no attribute CocoConfig [SOLVED-->Solution]

Open johannathiemich opened this issue 7 years ago • 11 comments

I ran upon this error when executing the demo.ipynb: "Coco has no attribute CocoConfig" (altough the coco module was imported successfully) I searched really long for an answer. Finally, I discovered that in the coco.py file (from: https://github.com/waleedka/coco, as suggested by the installation guide from this repository) does indeed not contain a class called CocoConfig. I thought I downloaded the wrong repository, but that was not the case. Then I found a code snippet here: https://github.com/karolmajek/Mask_RCNN/blob/master/coco.py that contained the class CocoConfig. I ended up just pasting the class definition into the demo.py file.

class CocoConfig(Config):
    """Configuration for training on MS COCO.
    Derives from the base Config class and overrides values specific
    to the COCO dataset.
    """
    # Give the configuration a recognizable name
    NAME = "coco"

    # We use a GPU with 12GB memory, which can fit two images.
    # Adjust down if you use a smaller GPU.
    IMAGES_PER_GPU = 2

    # Uncomment to train on 8 GPUs (default is 1)
    # GPU_COUNT = 8

    # Number of classes (including background)
    NUM_CLASSES = 1 + 80  # COCO has 80 classes

And it worked! It is really annoying that the demo example already contains mistakes. But maybe someone else will find this helpful. But on the other hand: I would not think that this is really a mistake, so what did I do wrong? I followed all the instructions (and also additional instructions from here: http://bradsliz.com/2017-11-06-object-segmentation/)

So this "bug" is already solved but I thought this experience could save some time for others having the same problem.

johannathiemich avatar May 07 '18 10:05 johannathiemich

@johannathiemich Hi I faced similar problem and used your workround but after pasted class cococonfig showed below error AttributeError: 'InferenceConfig' object has no attribute 'IMAGE_SHAPE' what is the problem?? can i see your correct demo.ipynp file?? thanks

naserpiltan avatar May 26 '18 08:05 naserpiltan

This is my demo.py file:


# coding: utf-8

# In[ ]:

from datetime import datetime
import os
import psutil
import sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt

# Root directory of the project
ROOT_DIR = os.path.abspath("/home/thiemi/MaskRCNN/Mask_RCNN")
pid = os.getpid()
py = psutil.Process(pid)
memoryUse = py.get_memory_info()[0]/2.**30
print("Memory use:", memoryUse)
# Import Mask RCNN
sys.path.append(ROOT_DIR)  # To find local version of the library
from mrcnn import utils
import mrcnn.model as modellib
from mrcnn.config import Config
from mrcnn import visualize
# Import COCO config
#sys.path.append(os.path.abspath("/home/thiemi/Coco/coco/PythonAPI"))  # To find local version

sys.path.append('/home/thiemi/Coco/coco_1/PythonAPI/pycocotools')
#from pycocotools.coco import coco
import coco

#get_ipython().magic(u'matplotlib inline')

# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")

# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# Download COCO trained weights from Releases if needed
if not os.path.exists(COCO_MODEL_PATH):
    utils.download_trained_weights(COCO_MODEL_PATH)

# Directory of images to run detection on
IMAGE_DIR = os.path.join(ROOT_DIR, "images")

class CocoConfig(Config):
    """Configuration for training on MS COCO.
    Derives from the base Config class and overrides values specific
    to the COCO dataset.
    """
    # Give the configuration a recognizable name
    NAME = "coco"

    # We use a GPU with 12GB memory, which can fit two images.
    # Adjust down if you use a smaller GPU.
    IMAGES_PER_GPU = 2

    # Uncomment to train on 8 GPUs (default is 1)
    # GPU_COUNT = 8

    # Number of classes (including background)
    #NUM_CLASSES = 37  # COCO has 80 classes
    NUM_CLASSES = 81

#class InferenceConfig(coco.CocoConfig):
class InferenceConfig(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
    #MAX_GT_INSTANCES = 100
    #TRAIN_ROIS_PER_IMAGE = 50
    #BACKBONE = "resnet50" #not working at all!
    #RPN_ANCHOR_STRIDE = 2
    POST_NMS_ROIS_TRAINING = 1000
    POST_NMS_ROIS_INFERENCE = 500
    IMAGE_MIN_DIM = 400 #really much faster but bad results
    IMAGE_MAX_DIM = 512
    #DETECTION_MAX_INSTANCES = 50 #a little faster but some instances not recognized

config = InferenceConfig()
config.display()




# Create model object in inference mode.
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)

# Load weights trained on MS-COCO
model.load_weights(COCO_MODEL_PATH, by_name=True)



# Class names
# Index of the class in the list is its ID. For example, to get ID of
# the teddy bear class, use: class_names.index('teddy bear')
class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
               'bus', 'train', 'truck', 'boat', 'traffic light',
               'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
               'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
               'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
               'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
               'kite', 'baseball bat', 'baseball glove', 'skateboard',
               'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
               'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
               'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
               'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
               'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
               'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
               'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
               'teddy bear', 'hair drier', 'toothbrush']

"""class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
               'bus', 'train', 'truck', 'boat', 'traffic light',
               'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
               'cat', 'dog', 'horse', 'sheep', 'cow', 'bear', 'backpack', 'umbrella',   		'handbag', 
               'suitcase', 'frisbee', 'sports ball',
               'skateboard',
               'surfboard', 'tennis racket', 'bottle', 
               'chair', 'couch', 'potted plant', 
                'toilet', 
               'clock']"""


# Load a random image from the images folder
#file_names = next(os.walk(IMAGE_DIR))[2]
#image = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names)))

start = datetime.now()
image = skimage.io.imread(os.path.join(IMAGE_DIR, "street" + str(7) + ".jpg"))
# Run detection
result = model.detect([image], verbose=1)

#results = model.detect([image], verbose=1)
memoryUse = py.get_memory_info()[0]/2.**30
print("Memory use:", memoryUse)
print("The program took", datetime.now() - start, " seconds") 
# Visualize results
r = result[0]
visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], 
                            class_names, r['scores'])

You will have to adapt the paths to the directory. But I think the mistake is that I wrote in my original post that you had to paste those lines into the demo.py file, which is not true. If I remember correctly, you have to paste those lines into the coco.py file.

johannathiemich avatar May 28 '18 06:05 johannathiemich

It is already present in my file coco.py but still I'm getting the same error on running demo.ipynb. I tried changing the root directory path in both demo.ipynb as well as coco.py but still, the error persists. Kindly advise.

akshay-iyer avatar Feb 11 '19 19:02 akshay-iyer

It is already present in my file coco.py but still I'm getting the same error on running demo.ipynb. I tried changing the root directory path in both demo.ipynb as well as coco.py but still, the error persists. Kindly advise.

I think you should download the mask_rcnn_coco.h5 firstly as described in the Installation. The coco.py may not correctly loaded due to the missing of the mask_rcnn_coco.h5, thus the class in the coco.py won't work.

ustcjerry avatar Mar 13 '19 02:03 ustcjerry

Running into the same issue here. I copied the config class from Karol Majek's fork.

Now I'm running into AttributeError: 'Config' object has no attribute 'IMAGE_META_SIZE'

brendanbailey avatar Jul 02 '19 20:07 brendanbailey

Nevermind. I see the Config class is actually imported in from mrcnn.config import Config

The author then modifies it through ``` class CocoConfig(Config): """Configuration for training on MS COCO. Derives from the base Config class and overrides values specific to the COCO dataset. """ # Give the configuration a recognizable name NAME = "coco"

# We use a GPU with 12GB memory, which can fit two images.
# Adjust down if you use a smaller GPU.
IMAGES_PER_GPU = 2

# Uncomment to train on 8 GPUs (default is 1)
# GPU_COUNT = 8

# Number of classes (including background)
NUM_CLASSES = 1 + 80  # COCO has 80 classes

brendanbailey avatar Jul 02 '19 23:07 brendanbailey

This is my demo.py file:


# coding: utf-8

# In[ ]:

from datetime import datetime
import os
import psutil
import sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt

# Root directory of the project
ROOT_DIR = os.path.abspath("/home/thiemi/MaskRCNN/Mask_RCNN")
pid = os.getpid()
py = psutil.Process(pid)
memoryUse = py.get_memory_info()[0]/2.**30
print("Memory use:", memoryUse)
# Import Mask RCNN
sys.path.append(ROOT_DIR)  # To find local version of the library
from mrcnn import utils
import mrcnn.model as modellib
from mrcnn.config import Config
from mrcnn import visualize
# Import COCO config
#sys.path.append(os.path.abspath("/home/thiemi/Coco/coco/PythonAPI"))  # To find local version

sys.path.append('/home/thiemi/Coco/coco_1/PythonAPI/pycocotools')
#from pycocotools.coco import coco
import coco

#get_ipython().magic(u'matplotlib inline')

# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")

# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# Download COCO trained weights from Releases if needed
if not os.path.exists(COCO_MODEL_PATH):
    utils.download_trained_weights(COCO_MODEL_PATH)

# Directory of images to run detection on
IMAGE_DIR = os.path.join(ROOT_DIR, "images")

class CocoConfig(Config):
    """Configuration for training on MS COCO.
    Derives from the base Config class and overrides values specific
    to the COCO dataset.
    """
    # Give the configuration a recognizable name
    NAME = "coco"

    # We use a GPU with 12GB memory, which can fit two images.
    # Adjust down if you use a smaller GPU.
    IMAGES_PER_GPU = 2

    # Uncomment to train on 8 GPUs (default is 1)
    # GPU_COUNT = 8

    # Number of classes (including background)
    #NUM_CLASSES = 37  # COCO has 80 classes
    NUM_CLASSES = 81

#class InferenceConfig(coco.CocoConfig):
class InferenceConfig(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
    #MAX_GT_INSTANCES = 100
    #TRAIN_ROIS_PER_IMAGE = 50
    #BACKBONE = "resnet50" #not working at all!
    #RPN_ANCHOR_STRIDE = 2
    POST_NMS_ROIS_TRAINING = 1000
    POST_NMS_ROIS_INFERENCE = 500
    IMAGE_MIN_DIM = 400 #really much faster but bad results
    IMAGE_MAX_DIM = 512
    #DETECTION_MAX_INSTANCES = 50 #a little faster but some instances not recognized

config = InferenceConfig()
config.display()




# Create model object in inference mode.
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)

# Load weights trained on MS-COCO
model.load_weights(COCO_MODEL_PATH, by_name=True)



# Class names
# Index of the class in the list is its ID. For example, to get ID of
# the teddy bear class, use: class_names.index('teddy bear')
class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
               'bus', 'train', 'truck', 'boat', 'traffic light',
               'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
               'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
               'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
               'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
               'kite', 'baseball bat', 'baseball glove', 'skateboard',
               'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
               'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
               'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
               'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
               'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
               'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
               'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
               'teddy bear', 'hair drier', 'toothbrush']

"""class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
               'bus', 'train', 'truck', 'boat', 'traffic light',
               'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
               'cat', 'dog', 'horse', 'sheep', 'cow', 'bear', 'backpack', 'umbrella',   		'handbag', 
               'suitcase', 'frisbee', 'sports ball',
               'skateboard',
               'surfboard', 'tennis racket', 'bottle', 
               'chair', 'couch', 'potted plant', 
                'toilet', 
               'clock']"""


# Load a random image from the images folder
#file_names = next(os.walk(IMAGE_DIR))[2]
#image = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names)))

start = datetime.now()
image = skimage.io.imread(os.path.join(IMAGE_DIR, "street" + str(7) + ".jpg"))
# Run detection
result = model.detect([image], verbose=1)

#results = model.detect([image], verbose=1)
memoryUse = py.get_memory_info()[0]/2.**30
print("Memory use:", memoryUse)
print("The program took", datetime.now() - start, " seconds") 
# Visualize results
r = result[0]
visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], 
                            class_names, r['scores'])

You will have to adapt the paths to the directory. But I think the mistake is that I wrote in my original post that you had to paste those lines into the demo.py file, which is not true. If I remember correctly, you have to paste those lines into the coco.py file.

@ johannathiemich

I`m unable to get through this line # Create model object in inference mode. model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config).

It throws error like 'NoneType' object has no attribute 'lower'.

Please help me to resolve this issue.

Thanks

Benito2204 avatar Apr 03 '20 15:04 Benito2204

This is my demo.py file:


# coding: utf-8

# In[ ]:

from datetime import datetime
import os
import psutil
import sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt

# Root directory of the project
ROOT_DIR = os.path.abspath("/home/thiemi/MaskRCNN/Mask_RCNN")
pid = os.getpid()
py = psutil.Process(pid)
memoryUse = py.get_memory_info()[0]/2.**30
print("Memory use:", memoryUse)
# Import Mask RCNN
sys.path.append(ROOT_DIR)  # To find local version of the library
from mrcnn import utils
import mrcnn.model as modellib
from mrcnn.config import Config
from mrcnn import visualize
# Import COCO config
#sys.path.append(os.path.abspath("/home/thiemi/Coco/coco/PythonAPI"))  # To find local version

sys.path.append('/home/thiemi/Coco/coco_1/PythonAPI/pycocotools')
#from pycocotools.coco import coco
import coco

#get_ipython().magic(u'matplotlib inline')

# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")

# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# Download COCO trained weights from Releases if needed
if not os.path.exists(COCO_MODEL_PATH):
    utils.download_trained_weights(COCO_MODEL_PATH)

# Directory of images to run detection on
IMAGE_DIR = os.path.join(ROOT_DIR, "images")

class CocoConfig(Config):
    """Configuration for training on MS COCO.
    Derives from the base Config class and overrides values specific
    to the COCO dataset.
    """
    # Give the configuration a recognizable name
    NAME = "coco"

    # We use a GPU with 12GB memory, which can fit two images.
    # Adjust down if you use a smaller GPU.
    IMAGES_PER_GPU = 2

    # Uncomment to train on 8 GPUs (default is 1)
    # GPU_COUNT = 8

    # Number of classes (including background)
    #NUM_CLASSES = 37  # COCO has 80 classes
    NUM_CLASSES = 81

#class InferenceConfig(coco.CocoConfig):
class InferenceConfig(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
    #MAX_GT_INSTANCES = 100
    #TRAIN_ROIS_PER_IMAGE = 50
    #BACKBONE = "resnet50" #not working at all!
    #RPN_ANCHOR_STRIDE = 2
    POST_NMS_ROIS_TRAINING = 1000
    POST_NMS_ROIS_INFERENCE = 500
    IMAGE_MIN_DIM = 400 #really much faster but bad results
    IMAGE_MAX_DIM = 512
    #DETECTION_MAX_INSTANCES = 50 #a little faster but some instances not recognized

config = InferenceConfig()
config.display()




# Create model object in inference mode.
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)

# Load weights trained on MS-COCO
model.load_weights(COCO_MODEL_PATH, by_name=True)



# Class names
# Index of the class in the list is its ID. For example, to get ID of
# the teddy bear class, use: class_names.index('teddy bear')
class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
               'bus', 'train', 'truck', 'boat', 'traffic light',
               'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
               'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
               'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
               'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
               'kite', 'baseball bat', 'baseball glove', 'skateboard',
               'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
               'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
               'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
               'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
               'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
               'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
               'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
               'teddy bear', 'hair drier', 'toothbrush']

"""class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
               'bus', 'train', 'truck', 'boat', 'traffic light',
               'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
               'cat', 'dog', 'horse', 'sheep', 'cow', 'bear', 'backpack', 'umbrella',   		'handbag', 
               'suitcase', 'frisbee', 'sports ball',
               'skateboard',
               'surfboard', 'tennis racket', 'bottle', 
               'chair', 'couch', 'potted plant', 
                'toilet', 
               'clock']"""


# Load a random image from the images folder
#file_names = next(os.walk(IMAGE_DIR))[2]
#image = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names)))

start = datetime.now()
image = skimage.io.imread(os.path.join(IMAGE_DIR, "street" + str(7) + ".jpg"))
# Run detection
result = model.detect([image], verbose=1)

#results = model.detect([image], verbose=1)
memoryUse = py.get_memory_info()[0]/2.**30
print("Memory use:", memoryUse)
print("The program took", datetime.now() - start, " seconds") 
# Visualize results
r = result[0]
visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], 
                            class_names, r['scores'])

You will have to adapt the paths to the directory. But I think the mistake is that I wrote in my original post that you had to paste those lines into the demo.py file, which is not true. If I remember correctly, you have to paste those lines into the coco.py file.

@ johannathiemich

I`m unable to get through this line # Create model object in inference mode. model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config).

It throws error like 'NoneType' object has no attribute 'lower'.

Please help me to resolve this issue.

Thanks

Hello everybody, i thanks all contributors to cooperate with this Forum . As i was checking some versions of TensorFlow, Keras and more, to use demo file of mask RCNN ,from https://github.com/matterport/Mask_RCNN/ using gogle colaboratory.

i did some modifications to the file in order to make it run. here i´ve a copy of the file.

Open it with google colab and run it.

MaskRCNN_180420.zip

adferchava avatar Apr 19 '20 14:04 adferchava

Hello, I was running into the same problem and this is what worked for me:

from mrcnn.config import Config
class CocoConfig(Config):
    """Configuration for training on MS COCO.
    Derives from the base Config class and overrides values specific
    to the COCO dataset.
    """
    # Give the configuration a recognizable name
    NAME = "coco"

    # We use a GPU with 12GB memory, which can fit two images.
    # Adjust down if you use a smaller GPU.
    IMAGES_PER_GPU = 2

    # Uncomment to train on 8 GPUs (default is 1)
    # GPU_COUNT = 8

    # Number of classes (including background)
    NUM_CLASSES = 1 + 80  # COCO has 80 classes

class InferenceConfig(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

config = InferenceConfig()
config.display()

I hope it helps you!

GabrielaCaballero avatar Mar 05 '21 17:03 GabrielaCaballero

Best helpful

arifulai avatar Oct 19 '23 13:10 arifulai

I have another issue AttributeError: module 'tensorflow.python.framework.ops' has no attribute '_TensorLike'

How to do solve ?

arifulai avatar Oct 19 '23 13:10 arifulai