Python `TypeError:类型为'的对象;非类型';在jupyter笔记本上运行基本M RCNN程序时没有len()`错误
我正在运行一个基本的maskr cnn程序来检测物体。它正在使用coco数据集。我正在连接到AWS Ec2实例的Jupyter笔记本上运行此程序。我发现以下错误Python `TypeError:类型为'的对象;非类型';在jupyter笔记本上运行基本M RCNN程序时没有len()`错误,python,opencv,amazon-ec2,jupyter-notebook,computer-vision,Python,Opencv,Amazon Ec2,Jupyter Notebook,Computer Vision,我正在运行一个基本的maskr cnn程序来检测物体。它正在使用coco数据集。我正在连接到AWS Ec2实例的Jupyter笔记本上运行此程序。我发现以下错误 Below is the traceback from this internal error. Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py
Below is the traceback from this internal error.
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 3343, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-1-dfbb133297e0>", line 117, in <module>
cv2.imshow('frame', frame)
cv2.error: OpenCV(4.2.0) /home/ubuntu/src/opencv/modules/highgui/src/window.cpp:651: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvShowImage'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 2044, in showtraceback
stb = value._render_traceback_()
AttributeError: 'error' object has no attribute '_render_traceback_'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/IPython/core/ultratb.py", line 1169, in get_records
return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
File "/usr/local/lib/python3.6/dist-packages/IPython/core/ultratb.py", line 316, in wrapped
return f(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/IPython/core/ultratb.py", line 350, in _fixed_getinnerframes
records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
File "/usr/lib/python3.6/inspect.py", line 1490, in getinnerframes
frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
File "/usr/lib/python3.6/inspect.py", line 1448, in getframeinfo
filename = getsourcefile(frame) or getfile(frame)
File "/usr/lib/python3.6/inspect.py", line 696, in getsourcefile
if getattr(getmodule(object, filename), '__loader__', None) is not None:
File "/usr/lib/python3.6/inspect.py", line 733, in getmodule
if ismodule(module) and hasattr(module, '__file__'):
File "/usr/local/lib/python3.6/dist-packages/tensorflow/__init__.py", line 50, in __getattr__
module = self._load()
File "/usr/local/lib/python3.6/dist-packages/tensorflow/__init__.py", line 44, in _load
module = _importlib.import_module(self.__name__)
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/contrib/__init__.py", line 48, in <module>
from tensorflow.contrib import estimator
File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/contrib/estimator/__init__.py", line 30, in <module>
from tensorflow_estimator.contrib import estimator
ModuleNotFoundError: No module named 'tensorflow_estimator.contrib'
---------------------------------------------------------------------------
error Traceback (most recent call last)
[... skipping hidden 1 frame]
<ipython-input-1-dfbb133297e0> in <module>
116
--> 117 cv2.imshow('frame', frame)
118 cv2.waitkey(0)
error: OpenCV(4.2.0) /home/ubuntu/src/opencv/modules/highgui/src/window.cpp:651: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvShowImage'
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py in showtraceback(self, exc_tuple, filename, tb_offset, exception_only, running_compiled_code)
2043 # in the engines. This should return a list of strings.
-> 2044 stb = value._render_traceback_()
2045 except Exception:
AttributeError: 'error' object has no attribute '_render_traceback_'
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
[... skipping hidden 1 frame]
/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py in showtraceback(self, exc_tuple, filename, tb_offset, exception_only, running_compiled_code)
2045 except Exception:
2046 stb = self.InteractiveTB.structured_traceback(etype,
-> 2047 value, tb, tb_offset=tb_offset)
2048
2049 self._showtraceback(etype, value, stb)
/usr/local/lib/python3.6/dist-packages/IPython/core/ultratb.py in structured_traceback(self, etype, value, tb, tb_offset, number_of_lines_of_context)
1434 self.tb = tb
1435 return FormattedTB.structured_traceback(
-> 1436 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1437
1438
/usr/local/lib/python3.6/dist-packages/IPython/core/ultratb.py in structured_traceback(self, etype, value, tb, tb_offset, number_of_lines_of_context)
1334 # Verbose modes need a full traceback
1335 return VerboseTB.structured_traceback(
-> 1336 self, etype, value, tb, tb_offset, number_of_lines_of_context
1337 )
1338 elif mode == 'Minimal':
/usr/local/lib/python3.6/dist-packages/IPython/core/ultratb.py in structured_traceback(self, etype, evalue, etb, tb_offset, number_of_lines_of_context)
1191
1192 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
-> 1193 tb_offset)
1194
1195 colors = self.Colors # just a shorthand + quicker name lookup
/usr/local/lib/python3.6/dist-packages/IPython/core/ultratb.py in format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset)
1148
1149
-> 1150 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1151
1152 frames = self.format_records(records, last_unique, recursion_repeat)
/usr/local/lib/python3.6/dist-packages/IPython/core/ultratb.py in find_recursion(etype, value, records)
449 # first frame (from in to out) that looks different.
450 if not is_recursion_error(etype, value, records):
--> 451 return len(records), 0
452
453 # Select filename, lineno, func_name to track frames with
TypeError: object of type 'NoneType' has no len()
尝试安装它
pip安装-U tensorflow\U估计器
。或者阅读。
import numpy as np
import tensorflow
print(tensorflow.__version__)
def random_colors(N):
np.random.seed(1)
colors = [tuple(255 * np.random.rand(3)) for _ in range(N)]
return colors
def apply_mask(image, mask, color, alpha=0.5):
"""apply mask to image"""
for n, c in enumerate(color):
image[:, :, n] = np.where(
mask == 1,
image[:, :, n] * (1 - alpha) + alpha * c,
image[:, :, n]
)
return image
def display_instances(image, boxes, masks, ids, names, scores):
"""
take the image and results and apply the mask, box, and Label
"""
n_instances = boxes.shape[0]
colors = random_colors(n_instances)
if not n_instances:
print('NO INSTANCES TO DISPLAY')
else:
assert boxes.shape[0] == masks.shape[-1] == ids.shape[0]
for i, color in enumerate(colors):
if not np.any(boxes[i]):
continue
y1, x1, y2, x2 = boxes[i]
label = names[ids[i]]
score = scores[i] if scores is not None else None
caption = '{} {:.2f}'.format(label, score) if score else label
mask = masks[:, :, i]
image = apply_mask(image, mask, color)
image = cv2.rectangle(image, (x1, y1), (x2, y2), color, 2)
image = cv2.putText(
image, caption, (x1, y1), cv2.FONT_HERSHEY_COMPLEX, 0.7, color, 2
)
return image
if __name__ == '__main__':
"""
test everything
"""
import os
import sys
from mrcnn import utils
from mrcnn import model as modellib
ROOT_DIR = os.getcwd()
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
if not os.path.exists(COCO_MODEL_PATH):
utils.download_trained_weights(COCO_MODEL_PATH)
sys.path.append(os.path.join(ROOT_DIR, "samples/coco/")) # To find local version
import coco
class InferenceConfig(coco.CocoConfig):
GPU_COUNT = 1
IMAGES_PER_GPU = 1
config = InferenceConfig()
config.display()
model = modellib.MaskRCNN(
mode="inference", model_dir=MODEL_DIR, config=config
)
model.load_weights(COCO_MODEL_PATH, by_name=True)
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'
]
#capture = cv2.VideoCapture(0)
# these 2 lines can be removed if you dont have a 1080p camera.
##capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
#capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
#while True:
frame = cv2.imread("test_images.jpg")
results = model.detect([frame], verbose=0)
r = results[0]
frame = display_instances(
frame, r['rois'], r['masks'], r['class_ids'], class_names, r['scores']
)
cv2.imshow('frame', frame)
cv2.waitkey(0)
#if cv2.waitKey(1) & 0xFF == ord('q'):
# break
#capture.release()
cv2.destroyAllWindows()