Imagenet VGG-19图片识别实例展示

资源

1.相关的vgg模型下载网址

2.ImageNet 1000种分类以及排列

https://github.com/sh1r0/caffe-Android-demo/blob/master/app/src/main/assets/synset_words.txt(如果下载单个txt格式不对的话就整包下载)

 

完整代码如下:

import numpy as np
import scipy.misc
import scipy.io as sio
import tensorflow as  tf
import os


##卷积层
def _conv_layer(input, weight, bias):
    conv = tf.nn.conv2d(input, tf.constant(weight), strides=(1, 1, 1, 1), padding='SAME')
    return tf.nn.bias_add(conv, bias)


##池化层
def _pool_layer(input):
    return tf.nn.max_pool(input, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1), padding='SAME')


##全链接层
def _fc_layer(input, weights, bias):
    shape = input.get_shape().as_list()
    dim = 1
    for d in shape[1:]:
        dim *= d
    x = tf.reshape(input, [-1, dim])
    fc = tf.nn.bias_add(tf.matmul(x, weights), bias)
    return fc


##softmax输出层
def _softmax_preds(input):
    preds = tf.nn.softmax(input, name='prediction')
    return preds


##图片处里前减去均值
def _preprocess(image, mean_pixel):
    return image - mean_pixel


##加均值  显示图片
def _unprocess(image, mean_pixel):
    return image + mean_pixel


##读取图片 并压缩
def _get_img(src, img_size=False):
    img = scipy.misc.imread(src, mode='RGB')
    if not (len(img.shape) == 3 and img.shape[2] == 3):
        img = np.dstack((img, img, img))
    if img_size != False:
        img = scipy.misc.imresize(img, img_size)
    return img.astype(np.float32)


##获取名列表
def list_files(in_path):
    files = []
    for (dirpath, dirnames, filenames) in os.walk(in_path):
        # print("dirpath=%s, dirnames=%s, filenames=%s"%(dirpath, dirnames, filenames))
        files.extend(filenames)
        break

    return files


##获取文件路径列表dir+filename
def _get_files(img_dir):
    files = list_files(img_dir)
    return [os.path.join(img_dir, x) for x in files]

##获得图片lable列表
def _get_allClassificationName(file_path):
    f = open(file_path, 'r')
    lines = f.readlines()
    f.close()
    return lines

##构建cnn前向传播网络
def net(data, input_image):
    layers = (
        'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1',

        'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2',

        'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2',
        'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3',

        'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2',
        'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4',

        'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2',
        'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4', 'pool5',

        'fc6', 'relu6',
        'fc7', 'relu7',
        'fc8', 'softmax'
    )

    weights = data['layers'][0]
    net = {}
    current = input_image
    for i, name in enumerate(layers):
        kind = name[:4]
        if kind == 'conv':
            kernels, bias = weights[i][0][0][0][0]
            kernels = np.transpose(kernels, (1, 0, 2, 3))
            bias = bias.reshape(-1)
            current = _conv_layer(current, kernels, bias)
        elif kind == 'relu':
            current = tf.nn.relu(current)
        elif kind == 'pool':
            current = _pool_layer(current)
        elif kind == 'soft':
            current = _softmax_preds(current)

        kind2 = name[:2]
        if kind2 == 'fc':
            kernels1, bias1 = weights[i][0][0][0][0]

            kernels1 = kernels1.reshape(-1, kernels1.shape[-1])
            bias1 = bias1.reshape(-1)
            current = _fc_layer(current, kernels1, bias1)

        net[name] = current
    assert len(net) == len(layers)
    return net, mean_pixel, layers


if __name__ == '__main__':
    imagenet_path = 'data/imagenet-vgg-verydeep-19.mat'
    image_dir = 'images/'

    data = sio.loadmat(imagenet_path)  ##加载ImageNet mat模型
    mean = data['normalization'][0][0][0]
    mean_pixel = np.mean(mean, axis=(0, 1))  ##获取图片像素均值

    lines = _get_allClassificationName('data/synset_words.txt')  ##加载ImageNet mat标签
    images = _get_files(image_dir)  ##获取图片路径列表
    with tf.Session() as sess:
        for i, imgPath in enumerate(images):
            image = _get_img(imgPath, (224, 224, 3))  ##加载图片并压缩到标准格式=>224 224

            image_pre = _preprocess(image, mean_pixel)
            # image_pre = image_pre.transpose((2, 0, 1))
            image_pre = np.expand_dims(image_pre, axis=0)

            image_preTensor = tf.convert_to_tensor(image_pre)
            image_preTensor = tf.to_float(image_preTensor)

            # Test pretrained model
            nets, mean_pixel, layers = net(data, image_preTensor)

            preds = nets['softmax']

            predsSortIndex = np.argsort(-preds[0].eval())
            print('#####%s#######' % imgPath)
            for i in range(3):   ##输出前3种分类
                nIndex = predsSortIndex
                classificationName = lines[nIndex[i]] ##分类名称
                problity = preds[0][nIndex[i]]   ##某一类型概率

                print('%d.ClassificationName=%s  Problity=%f' % ((i + 1), classificationName, problity.eval()))

 

#####images/cat1.jpg#######
1.ClassificationName=n02123045 tabby, tabby cat
  Problity=0.219027
2.ClassificationName=n02123159 tiger cat
  Problity=0.091527
3.ClassificationName=n02445715 skunk, polecat, wood pussy
  Problity=0.028864

 

#####images/cat2.jpg#######
1.ClassificationName=n02123045 tabby, tabby cat
  Problity=0.337648
2.ClassificationName=n02123159 tiger cat
  Problity=0.171013
3.ClassificationName=n02124075 Egyptian cat
  Problity=0.059857

 

#####images/cat_two.jpg#######
1.ClassificationName=n03887697 paper towel
  Problity=0.178623
2.ClassificationName=n02111889 Samoyed, Samoyede
  Problity=0.119629
3.ClassificationName=n02098286 West Highland white terrier
  Problity=0.060589

 

#####images/dog1.jpg#######
1.ClassificationName=n02096585 Boston bull, Boston terrier
  Problity=0.403131
2.ClassificationName=n02108089 boxer
  Problity=0.184223
3.ClassificationName=n02093256 Staffordshire bullterrier, Staffordshire bull terrier
  Problity=0.101937

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
### 回答1: Imagenet-vgg-verydeep-19.mat是一个预训练的深度神经网络模型文件,包含了一个19层的卷积神经网络(CNN)模型,在计算机视觉领域中非常有用。它被称为VGG-19,因为它由两个重复的卷积层阶段组成,每个阶段包含了4个卷积层和2个池化层,加上3个全连接层。此模型是由牛津大学计算机科学系Visual Geometry Group团队开发的,用于2014年ImageNet图像分类竞赛中取得了第二名的成绩。 下载Imagenet-vgg-verydeep-19.mat模型文件可以方便地使用它进行迁移学习和特征提取,将已经训练好的模型用于类似的计算机视觉任务,例如图像分类、物体检测、图像分割等。在许多研究领域,它已经成为使用深度学习进行计算机视觉最常使用的模型之一。 需要注意的是,Imagenet-vgg-verydeep-19.mat是一个很大的文件(约几百MB),下载它可能需要一些耐心和时间,特别是在网络环境较为缓慢的情况下。此外,该模型是使用MATLAB语言编写的,因此如果你想在其他编程语言中使用该模型,需要进行一些额外的工作来将其转化为其他语言所能识别的格式。 ### 回答2: imagenet-vgg-verydeep-19.mat是一个神经网络模型,它是基于VGG网络架构的一个深度神经网络。它是在2014年ILSVRC比赛中,由Visual Geometry Group (VGG)的研究人员提出的一种高效的CNN模型,该模型在“image classification”(图像分类)任务上的表现相当惊人,打破了当时的记录。它在准确性和速度方面表现出色,因此它得到了广泛的应用,成为深度学习领域的研究者和开发者们常用的模型之一。 imagenet-vgg-verydeep-19.mat是该模型的一个预训练权重文件,其中包含了30多万个图像的标识符和与之相应的特征描述符。这些权重可用于快速训练您自己的图片分类器或其他深度学习任务,这比从头开始训练一个完整的神经网络要快得多。您也可以使用这些权重来对一些图像进行分类,并使用它们的特征描述符来进行特征提取和图像检索。 如果您想要使用imagenet-vgg-verydeep-19.mat文件,您需要先下载它并存储到您的本地计算机中。在MATLAB中,您可以使用以下命令来下载该文件: ``` urlwrite('http://www.vlfeat.org/matconvnet/models/imagenet-vgg-verydeep-19.mat', 'imagenet-vgg-verydeep-19.mat'); ``` 下载完成后,您可以将其导入到MATLAB环境中,使用它进行图像分类和特征提取。该文件的大小约为500MB,因此请确保您的计算机具有足够的存储空间和足够的RAM来使用它。 ### 回答3: Imagenet-vgg-verydeep-19.mat是一个预训练的深度神经网络的模型文件,可以用来在计算机视觉领域进行图像分类、目标检测等诸多任务。该模型主要基于VGG网络结构,是一种具有较好性能和广泛应用的深度卷积神经网络。 下载Imagenet-vgg-verydeep-19.mat文件可以帮助研究人员或开发人员更快地开发和实现计算机视觉的应用程序。在某些应用场景下,为了实现对图像的识别或分类,需要大量的数据和计算资源。使用预训练的模型可以节省很多时间和计算资源,同时也可以提高模型的准确度。 目前,Imagenet-vgg-verydeep-19.mat模型已经被广泛应用于图像分类、目标检测和语义分割等领域。可以作为图像识别算法的基础模型,进行相应的改进和优化,从而得到更高的精度和更好的效果。 需要注意的是,使用Imagenet-vgg-verydeep-19.mat文件时,需要具备一定的深度学习算法和编程技能,否则很难实现相关应用。同时,也需要具备一定的数据处理能力,针对不同的应用场景,对数据进行适当的预处理和增强,才能得到更优的模型效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值