tensorflow/models reading&debuging

源码链接

https://github.com/tensorflow/models/tree/master/research/object_detection

下载后解压,直接下zip的记住改名models-master为models,在research/object_detection中阅读其中的notebook文件,按步骤抄到一个py文件中。

1. 环境配置

ubuntu系统,windows再说。。。。。。。。

1.1 安装tensorflow

使用清华源出问题,改为豆瓣源就好了

1.2 pip install pycocotools报错

坑1:缺个包

 pip install cython

坑2: error: command ‘x86_64-linux-gnu-gcc’ failed with exit status 1

sudo apt-get install build-essential python3-dev libssl-dev libffi-dev libxml2 libxml2-dev libxslt1-dev zlib1g-dev

2. include

ModuleNotFoundError: No module named ‘object_detection’
后来发现这里出问题是因为我没有按步骤走,其实按步骤走下来就这种问题了。

3. Detection

model_name = 'ssd_mobilenet_v1_coco_2017_11_17'
detection_model = load_model(model_name)

这步需要科学上网
运行一次后下载完成,之后再次运行无需再次下载,故梯子可以关了

4. Test

运行到这步

for image_path in TEST_IMAGE_PATHS:
    show_inference(detection_model, image_path)

发现图片未显示
应该是display在jupyter中有显示,pycharm中没有显示
改用cv2
把下面这个函数改一下

def show_inference(model, image_path):
    # the array based representation of the image will be used later in order to prepare the
    # result image with boxes and labels on it.
    image_np = np.array(Image.open(image_path))
    # Actual detection.
    output_dict = run_inference_for_single_image(model, image_np)
    # Visualization of the results of a detection.
    vis_util.visualize_boxes_and_labels_on_image_array(
        image_np,
        output_dict['detection_boxes'],
        output_dict['detection_classes'],
        output_dict['detection_scores'],
        category_index,
        instance_masks=output_dict.get('detection_masks_reframed', None),
        use_normalized_coordinates=True,
        line_thickness=8)

    display(Image.fromarray(image_np))
    ## 这里增加这两句
    cv2.imshow("test",image_np)
    cv2.waitKey()#按esc换下一张图

搞定,附上效果图
在这里插入图片描述在这里插入图片描述
还有点时间,整个window测试

window测试

把ubuntu中整好的代码全部打包挪到windows看效果(估计不太行)
清华源估计真不行了,继续换源

坑1:

pip install pycocotools

改为

pip install git+https://github.com/philferriere/cocoapi.git#subdirectory=PythonAPI

成功

坑2

%%bash
cd models/research/
protoc object_detection/protos/*.proto --python_out=.
%%bash 
cd models/research
pip install .

报错

'protoc' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
ERROR: Directory '.' is not installable. Neither 'setup.py' nor 'pyproject.toml' found.

windows安装protoc
参考windows 环境下的 protoc 安装
进入https://github.com/protocolbuffers/protobuf/releases
下载win64版本,将protoc.exe拷贝到c:\windows\system32中 ,测试如下

PS C:\Users\15518> protoc --version
libprotoc 3.12.1

然后再执行那两个命令就没问题了。

坑3

AttributeError: module 'google.protobuf.descriptor' has no attribute '_internal_create_key'

应该是tensorflow和protobuf的版本对应问题
在这里插入图片描述
从这个链接看到
在这里插入图片描述查看自己的版本

E:\self_study\git\models\research>pip install protobuf
Looking in indexes: http://mirrors.aliyun.com/pypi/simple/
Requirement already satisfied: protobuf in c:\users\15518\appdata\roaming\python\python37\site-packages (3.11.3)
Requirement already satisfied: six>=1.9 in c:\users\15518\appdata\local\programs\python\python37\lib\site-packages (from protobuf) (1.12.0)
Requirement already satisfied: setuptools in c:\users\15518\appdata\roaming\python\python37\site-packages (from protobuf) (46.1.1)

不对应,重新下,测试

PS C:\Users\15518> protoc --version
libprotoc 3.0.0

重新执行

%%bash
cd models/research/
protoc object_detection/protos/*.proto --python_out=.
%%bash 
cd models/research
pip install .

报错解决!
改一下图片存储的路径(参考上下文找修改位置)

# 自己改的部分
    cv2.imshow("test",image_np)
    img_name = str(image_path)
    img_name = img_name.split("\\")[-1].split('.')[0]
    cv2.imwrite('E:\self_study\git\models\images\\'+img_name+'.jpg',image_np)
    print('E:\self_study\git\models\images\\'+img_name+'.jpg')
    cv2.waitKey()

自己的测试

查看当前模型能识别什么,一顿找找到了这句话

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = 'object_detection/data/mscoco_label_map.pbtxt'
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)

打开这个pbtxt

item {
  name: "/m/01g317"
  id: 1
  display_name: "person"
}
item {
  name: "/m/0199g"
  id: 2
  display_name: "bicycle"
}
item {
  name: "/m/0k4j"
  id: 3
  display_name: "car"
}

。。。。。共90个不列了
。。。。。

那就找个自行车看认不认识,上图
在这里插入图片描述场景挺乱的,但识别效果还可以
在这里插入图片描述由于用的cv2打印的图片,通道和display可能不太一样,所以有色差。

舒服了。。。

最后附上我自己按步骤抄的和改的代码

## linux版本,windows需改动上一个代码块的内容
import os
import pathlib

print(pathlib.Path.cwd().parts)
os.chdir('..')
print(pathlib.Path.cwd().parts)

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

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

## Import the object detection module.
from object_detection.utils import ops as utils_ops
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util

# Patches:
# patch tf1 into `utils.ops`
utils_ops.tf = tf.compat.v1
# Patch the location of gfile
tf.gfile = tf.io.gfile


def load_model(model_name):
    base_url = 'http://download.tensorflow.org/models/object_detection/'
    model_file = model_name + '.tar.gz'
    model_dir = tf.keras.utils.get_file(
        fname=model_name,
        origin=base_url + model_file,
        untar=True)

    model_dir = pathlib.Path(model_dir) / "saved_model"

    model = tf.saved_model.load(str(model_dir))
    model = model.signatures['serving_default']

    return model


# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = 'object_detection/data/mscoco_label_map.pbtxt'
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)

# 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 = pathlib.Path('object_detection/test_images')
TEST_IMAGE_PATHS = sorted(list(PATH_TO_TEST_IMAGES_DIR.glob("*.jpg")))
print(TEST_IMAGE_PATHS)

# Detection
model_name = 'ssd_mobilenet_v1_coco_2017_11_17'
detection_model = load_model(model_name)

print(detection_model.inputs)
print(detection_model.output_dtypes)
print(detection_model.output_shapes)


def run_inference_for_single_image(model, image):
    image = np.asarray(image)
    # The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
    input_tensor = tf.convert_to_tensor(image)
    # The model expects a batch of images, so add an axis with `tf.newaxis`.
    input_tensor = input_tensor[tf.newaxis, ...]

    # Run inference
    output_dict = model(input_tensor)

    # All outputs are batches tensors.
    # Convert to numpy arrays, and take index [0] to remove the batch dimension.
    # We're only interested in the first num_detections.
    num_detections = int(output_dict.pop('num_detections'))
    output_dict = {key: value[0, :num_detections].numpy()
                   for key, value in output_dict.items()}
    output_dict['num_detections'] = num_detections

    # detection_classes should be ints.
    output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64)

    # Handle models with masks:
    if 'detection_masks' in output_dict:
        # Reframe the the bbox mask to the image size.
        detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
            output_dict['detection_masks'], output_dict['detection_boxes'],
            image.shape[0], image.shape[1])
        detection_masks_reframed = tf.cast(detection_masks_reframed > 0.5,
                                           tf.uint8)
        output_dict['detection_masks_reframed'] = detection_masks_reframed.numpy()

    return output_dict


def show_inference(model, image_path):
    # the array based representation of the image will be used later in order to prepare the
    # result image with boxes and labels on it.
    image_np = np.array(Image.open(image_path))
    # Actual detection.
    output_dict = run_inference_for_single_image(model, image_np)
    # Visualization of the results of a detection.
    vis_util.visualize_boxes_and_labels_on_image_array(
        image_np,
        output_dict['detection_boxes'],
        output_dict['detection_classes'],
        output_dict['detection_scores'],
        category_index,
        instance_masks=output_dict.get('detection_masks_reframed', None),
        use_normalized_coordinates=True,
        line_thickness=8)

    display(Image.fromarray(image_np))
    
    # 自己改的部分
    cv2.imshow("test",image_np)
    img_name = str(image_path)
    img_name = img_name.split("/")[-1].split('.')[0]
    cv2.imwrite('/home/ming/Pictures/'+img_name+'.jpg',image_np)
    cv2.waitKey()



for image_path in TEST_IMAGE_PATHS:

    show_inference(detection_model, image_path)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
"debugging with gdb 中文版pdf" 是一个以中文编写的关于使用 gdb 进行调试的电子书的 PDF 版本。其目的是帮助开发人员学习如何使用 gdb 工具来调试程序。 gdb 是一个功能强大的调试工具,可以用于调试多种编程语言的程序,包括 C、C++、Python 等。通过使用 gdb,开发人员可以跟踪程序的执行过程,查找错误,理解代码的行为,并解决各种问题。 "debugging with gdb 中文版pdf" 在中文编写,使得更多的中文用户能够方便地学习和理解调试技术。这本电子书将介绍 gdb 的基本操作和一些高级调试技巧,包括断点设置、变量查看、函数调用跟踪、内存调试等。 阅读这本电子书,您将学到如何正确地安装和配置 gdb,理解 gdb 的基本命令和选项,并通过实例学习调试技术。此外,您还将了解到如何通过 gdb 进行多线程和多进程的调试。 将 "debugging with gdb 中文版pdf" 作为学习调试的参考资料,可以帮助您提高程序调试的技能,并且能够更快地解决代码中的错误。同时,这本电子书也可以作为日常开发工作中的参考指南,帮助您更好地理解和使用 gdb 工具。 总之,"debugging with gdb 中文版pdf" 是一本有助于开发人员学习和掌握 gdb 调试技术的中文电子书。通过阅读这本书,您可以提高调试技能,加速解决代码中的错误,并更好地理解和使用 gdb 工具。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值