0

I am trying to create an object detector in Python (I use Pycharm). My idea is to save an image and with my webcam I can look around and see whether something looks like the image I saved. Nothing seems to work..

This is the error I get:

2020-01-20 12:27:44.554767: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found 2020-01-20 12:27:44.554964: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. Traceback (most recent call last): File "C:/Users/frevo/PycharmProjects/CameraTracking/models/object_detection/object_detection_tutorial_CONVERTED.py", line 74, in od_graph_def = tf.GraphDef() AttributeError: module 'tensorflow' has no attribute 'GraphDef'

This is my code:

import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile

from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image

import cv2
cap = cv2.VideoCapture(1)

# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")


# ## Object detection imports
# Here are the imports from the object detection module.

# In[3]:

from utils import label_map_util

from utils import visualization_utils as vis_util


# # Model preparation

# ## Variables
#
# Any model exported using the `export_inference_graph.py` tool can be loaded here simply by changing `PATH_TO_CKPT` to point to a new .pb file.
#
# By default we use an "SSD with Mobilenet" model here. See the [detection model zoo](https://github.com/tensorflow/models/blob/master/object_detection/g3doc/detection_model_zoo.md) for a list of other models that can be run out-of-the-box with varying speeds and accuracies.

# In[4]:

# What model to download.
MODEL_NAME = 'ssd_mobilenet_v1_coco_11_06_2017'
MODEL_FILE = MODEL_NAME + '.tar.gz'
DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'

# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')

NUM_CLASSES = 90


# ## Download Model

# In[5]:

opener = urllib.request.URLopener()
opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
tar_file = tarfile.open(MODEL_FILE)
for file in tar_file.getmembers():
  file_name = os.path.basename(file.name)
  if 'frozen_inference_graph.pb' in file_name:
    tar_file.extract(file, os.getcwd())


# ## Load a (frozen) Tensorflow model into memory.

# In[6]:

detection_graph = tf.Graph()
with detection_graph.as_default():
  od_graph_def = tf.GraphDef()
  with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
    serialized_graph = fid.read()
    od_graph_def.ParseFromString(serialized_graph)
    tf.import_graph_def(od_graph_def, name='')


# ## Loading label map
# Label maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `airplane`.  Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine

# In[7]:

label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)


# ## Helper code

# In[8]:

def load_image_into_numpy_array(image):
  (im_width, im_height) = image.size
  return np.array(image.getdata()).reshape(
      (im_height, im_width, 3)).astype(np.uint8)


# # Detection

# In[9]:

# For the sake of simplicity we will use only 2 images:
# image1.jpg
# image2.jpg
# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
PATH_TO_TEST_IMAGES_DIR = 'test_images'
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'dollar.jpg'.format(i)) for i in range(1, 3) ]

# Size, in inches, of the output images.
IMAGE_SIZE = (12, 8)


# In[10]:

with detection_graph.as_default():
  with tf.Session(graph=detection_graph) as sess:
    while True:
      ret, image_np = cap.read()
      # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
      image_np_expanded = np.expand_dims(image_np, axis=0)
      image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
      # Each box represents a part of the image where a particular object was detected.
      boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
      # Each score represent how level of confidence for each of the objects.
      # Score is shown on the result image, together with the class label.
      scores = detection_graph.get_tensor_by_name('detection_scores:0')
      classes = detection_graph.get_tensor_by_name('detection_classes:0')
      num_detections = detection_graph.get_tensor_by_name('num_detections:0')
      # Actual detection.
      (boxes, scores, classes, num_detections) = sess.run(
          [boxes, scores, classes, num_detections],
          feed_dict={image_tensor: image_np_expanded})
      # Visualization of the results of a detection.
      vis_util.visualize_boxes_and_labels_on_image_array(
          image_np,
          np.squeeze(boxes),
          np.squeeze(classes).astype(np.int32),
          np.squeeze(scores),
          category_index,
          use_normalized_coordinates=True,
          line_thickness=8)

      cv2.imshow('object detection', cv2.resize(image_np, (800,600)))
      if cv2.waitKey(25) & 0xFF == ord('q'):
        cv2.destroyAllWindows()
    break
  • this error means that you try to launch tensorflow-gpu without the right version of cuda – AdForte Jan 20 '20 at 12:02
  • @AdForte actually, this is now a warning from [TF 2.1+ (they changed the packages to unify the cpu & gpu ones)](https://stackoverflow.com/questions/59823283/could-not-load-dynamic-library-cudart64-101-dll-on-tensorflow-cpu-only-install/59823284#59823284) – GPhilo Jan 20 '20 at 12:31

3 Answers3

0

You installed the latest release of Tensorflow (version 2.1) via pip install tensorflow. The latest version of the package is the same for CPU and GPU builds, so unless you installed the correct CUDA version to use a GPU with tensorflow, TF will show the warning about cudart64_101.dll not found, which - as the warning itself says - you can safely ignore.

As per your actual error: The code you're using is based on Tensorflow's version 1, which i not compatible with TF 2.X. You can work around this by importing the V1 API replacing import tensorflow as tf with import tensorflow.compat.v1 as tf.

GPhilo
  • 18,519
  • 9
  • 63
  • 89
  • Thank you for your comment! It is not working.. If I do that I get this following error: Traceback (most recent call last): File "C:/Users/frevo/PycharmProjects/CameraTracking/models/object_detection/object_detection_tutorial_CONVERTED.py", line 86, in label_map = label_map_util.load_labelmap(PATH_TO_LABELS) File "C:\Users\frevo\PycharmProjects\CameraTracking\models\object_detection\utils\label_map_util.py", line 138, in load_labelmap with tf.gfile.GFile(path, 'r') as fid: AttributeError: module 'tensorflow' has no attribute 'gfile' – Frederique Voskeuil Jan 20 '20 at 12:08
  • You'll have to adapt all files imported by your script. `label_map_util` (and the whole TF object detection API, really) are not yet compatible with TF2. Replace the same tensorflow import in all the files with the compat.v1 or, if you're interested in using the object detection API, I'd suggest you install the 1.15 version of Tensorflow – GPhilo Jan 20 '20 at 12:12
  • I installed tensorflow 1.15, but I do not understand what you mean with replacing the same tensorflow import in all the files? Sorry I am quite new to Python ;) – Frederique Voskeuil Jan 20 '20 at 12:30
  • If you have TF 1.15 you don't need to replace anything :) – GPhilo Jan 20 '20 at 12:32
  • Aahh, that is weid, I installed TF 1.15, but I still get the same error! – Frederique Voskeuil Jan 20 '20 at 12:33
  • I changed import tensorflow.compat.v1 back to import tensorflow and now I am getting the first error again: Traceback (most recent call last): File "C:/Users/frevo/PycharmProjects/CameraTracking/models/object_detection/object_detection_tutorial_CONVERTED.py", line 75, in od_graph_def = tf.GraphDef() AttributeError: module 'tensorflow' has no attribute 'GraphDef' – Frederique Voskeuil Jan 20 '20 at 12:34
  • I see! Apparently `tf.gfile` was moved already in TF 1.15. If you open `label_map_util.py`, you can replace `tf.gfile` with `tf.io.gfile` to fix the issue. You can also revert the `import tensorflow.compat.v1 as tf` back to its original `import tensorflow as tf` – GPhilo Jan 20 '20 at 12:36
  • Can you `print(tf.__version__)` just to ckeck you're loading TF v1? – GPhilo Jan 20 '20 at 12:37
  • That seems to have no effect. I changed tf.gfile in label_map_util.py, but I still get the same error about tensorflow not having an attribute Graphdef.. – Frederique Voskeuil Jan 20 '20 at 12:42
  • Aah if I print the version it says 2.1.0, that is weird because I did install 1.15 via my cmd.. – Frederique Voskeuil Jan 20 '20 at 12:43
  • Yep, that's the problem. Uninstall both TF 1.15 and 2.1, then reinstall 1.15 – GPhilo Jan 20 '20 at 12:43
  • Do you know how I can delete everything of tensorflow and install tensorflow 1.15? – Frederique Voskeuil Jan 20 '20 at 12:44
  • I can uninstall 1.15, but my cmd does not uninstall 2.1.0. This is what I fill in in my cmd: python -m pip uninstall tensorflow==2.1.0. When I try this, my cmd says that tensorflow is not installed. My python file however still prints that I have tensorflow 2.1.0 – Frederique Voskeuil Jan 20 '20 at 12:49
0
       #either you switch to tensorflow==1.14
       pip install tensorflow==1.14

Let's Try This code

       #In tensorflow=2.0 or above update code :
       import tensorflow.compat.v1 as tf
Welcome_back
  • 1,245
  • 12
  • 18
0

I got the same problem as you,you can use tensoflow2.0.0+CUDA10 instead to solve this problem.

  • This better fits as comment to this question, but as I can see due to lack of reputation you cannot answer a question now so wait till you earn required reputation to answer. – Razneesh Feb 04 '20 at 12:21