有没有办法获取图片中已识别物体的颜色?

2023-12-22

我在用张量流 https://www.tensorflow.org/为了识别提供的图片中的对象,请遵循此tutorial https://www.tensorflow.org/install/install_java并使用这个仓库 https://github.com/tensorflow/tensorflow/blob/master/tensorflow/java/src/main/java/org/tensorflow/examples/LabelImage.java我成功地让我的程序返回图片内的对象。 例如,这是我用作输入的图片:

这是我的程序的输出:

我想要的只是获取已识别项目的颜色(最后一种情况是红色球衣),这可能吗?

这是代码(来自上一个链接,仅进行了一些小更改)

/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

package com.test.sec.compoment;

import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import org.tensorflow.DataType;
import org.tensorflow.Graph;
import org.tensorflow.Output;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.tensorflow.TensorFlow;
import org.tensorflow.types.UInt8;

/** Sample use of the TensorFlow Java API to label images using a pre-trained model. */
public class ImageRecognition {
  private static void printUsage(PrintStream s) {
    final String url =
        "https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip";
    s.println(
        "Java program that uses a pre-trained Inception model (http://arxiv.org/abs/1512.00567)");
    s.println("to label JPEG images.");
    s.println("TensorFlow version: " + TensorFlow.version());
    s.println();
    s.println("Usage: label_image <model dir> <image file>");
    s.println();
    s.println("Where:");
    s.println("<model dir> is a directory containing the unzipped contents of the inception model");
    s.println("            (from " + url + ")");
    s.println("<image file> is the path to a JPEG image file");
  }

  public void index() {
        String modelDir = "C:/Users/Admin/Downloads/inception5h";
        String imageFile = "C:/Users/Admin/Desktop/red-tshirt.jpg";

    byte[] graphDef = readAllBytesOrExit(Paths.get(modelDir, "tensorflow_inception_graph.pb"));
    List<String> labels =
        readAllLinesOrExit(Paths.get(modelDir, "imagenet_comp_graph_label_strings.txt"));
    byte[] imageBytes = readAllBytesOrExit(Paths.get(imageFile));

    try (Tensor<Float> image = constructAndExecuteGraphToNormalizeImage(imageBytes)) {
      float[] labelProbabilities = executeInceptionGraph(graphDef, image);
      int bestLabelIdx = maxIndex(labelProbabilities);
      System.out.println(
          String.format("BEST MATCH: %s (%.2f%% likely)",
              labels.get(bestLabelIdx),
              labelProbabilities[bestLabelIdx] * 100f));
    }
  }

  private static Tensor<Float> constructAndExecuteGraphToNormalizeImage(byte[] imageBytes) {
    try (Graph g = new Graph()) {
      GraphBuilder b = new GraphBuilder(g);
      // Some constants specific to the pre-trained model at:
      // https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip
      //
      // - The model was trained with images scaled to 224x224 pixels.
      // - The colors, represented as R, G, B in 1-byte each were converted to
      //   float using (value - Mean)/Scale.
      final int H = 224;
      final int W = 224;
      final float mean = 117f;
      final float scale = 1f;

      // Since the graph is being constructed once per execution here, we can use a constant for the
      // input image. If the graph were to be re-used for multiple input images, a placeholder would
      // have been more appropriate.
      final Output<String> input = b.constant("input", imageBytes);
      final Output<Float> output =
          b.div(
              b.sub(
                  b.resizeBilinear(
                      b.expandDims(
                          b.cast(b.decodeJpeg(input, 3), Float.class),
                          b.constant("make_batch", 0)),
                      b.constant("size", new int[] {H, W})),
                  b.constant("mean", mean)),
              b.constant("scale", scale));
      try (Session s = new Session(g)) {
        return s.runner().fetch(output.op().name()).run().get(0).expect(Float.class);
      }
    }
  }

  private static float[] executeInceptionGraph(byte[] graphDef, Tensor<Float> image) {
    try (Graph g = new Graph()) {
      g.importGraphDef(graphDef);
      try (Session s = new Session(g);
          Tensor<Float> result =
              s.runner().feed("input", image).fetch("output").run().get(0).expect(Float.class)) {
        final long[] rshape = result.shape();
        if (result.numDimensions() != 2 || rshape[0] != 1) {
          throw new RuntimeException(
              String.format(
                  "Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s",
                  Arrays.toString(rshape)));
        }
        int nlabels = (int) rshape[1];
        return result.copyTo(new float[1][nlabels])[0];
      }
    }
  }

  private static int maxIndex(float[] probabilities) {
    int best = 0;
    for (int i = 1; i < probabilities.length; ++i) {
      if (probabilities[i] > probabilities[best]) {
        best = i;
      }
    }
    return best;
  }

  private static byte[] readAllBytesOrExit(Path path) {
    try {
      return Files.readAllBytes(path);
    } catch (IOException e) {
      System.err.println("Failed to read [" + path + "]: " + e.getMessage());
      System.exit(1);
    }
    return null;
  }

  private static List<String> readAllLinesOrExit(Path path) {
    try {
      return Files.readAllLines(path, Charset.forName("UTF-8"));
    } catch (IOException e) {
      System.err.println("Failed to read [" + path + "]: " + e.getMessage());
      System.exit(0);
    }
    return null;
  }

  // In the fullness of time, equivalents of the methods of this class should be auto-generated from
  // the OpDefs linked into libtensorflow_jni.so. That would match what is done in other languages
  // like Python, C++ and Go.
  static class GraphBuilder {
    GraphBuilder(Graph g) {
      this.g = g;
    }

    Output<Float> div(Output<Float> x, Output<Float> y) {
      return binaryOp("Div", x, y);
    }

    <T> Output<T> sub(Output<T> x, Output<T> y) {
      return binaryOp("Sub", x, y);
    }

    <T> Output<Float> resizeBilinear(Output<T> images, Output<Integer> size) {
      return binaryOp3("ResizeBilinear", images, size);
    }

    <T> Output<T> expandDims(Output<T> input, Output<Integer> dim) {
      return binaryOp3("ExpandDims", input, dim);
    }

    <T, U> Output<U> cast(Output<T> value, Class<U> type) {
      DataType dtype = DataType.fromClass(type);
      return g.opBuilder("Cast", "Cast")
          .addInput(value)
          .setAttr("DstT", dtype)
          .build()
          .<U>output(0);
    }

    Output<UInt8> decodeJpeg(Output<String> contents, long channels) {
      return g.opBuilder("DecodeJpeg", "DecodeJpeg")
          .addInput(contents)
          .setAttr("channels", channels)
          .build()
          .<UInt8>output(0);
    }

    <T> Output<T> constant(String name, Object value, Class<T> type) {
      try (Tensor<T> t = Tensor.<T>create(value, type)) {
        return g.opBuilder("Const", name)
            .setAttr("dtype", DataType.fromClass(type))
            .setAttr("value", t)
            .build()
            .<T>output(0);
      }
    }
    Output<String> constant(String name, byte[] value) {
      return this.constant(name, value, String.class);
    }

    Output<Integer> constant(String name, int value) {
      return this.constant(name, value, Integer.class);
    }

    Output<Integer> constant(String name, int[] value) {
      return this.constant(name, value, Integer.class);
    }

    Output<Float> constant(String name, float value) {
      return this.constant(name, value, Float.class);
    }

    private <T> Output<T> binaryOp(String type, Output<T> in1, Output<T> in2) {
      return g.opBuilder(type, type).addInput(in1).addInput(in2).build().<T>output(0);
    }

    private <T, U, V> Output<T> binaryOp3(String type, Output<U> in1, Output<V> in2) {
      return g.opBuilder(type, type).addInput(in1).addInput(in2).build().<T>output(0);
    }
    private Graph g;
  }
}

您正在使用预测给定图像标签的代码,即将图像从一些经过训练的类中进行分类,因此您不知道对象的确切像素。

因此,我建议您执行以下任一操作,

  1. Use an 物体探测器 https://github.com/tensorflow/models/tree/master/research/object_detection检测物体的位置并获取边界框。然后获取最多像素的颜色。
  2. 使用像素级分类(分割),例如this https://github.com/arahusky/Tensorflow-Segmentation获取对象的精确像素。

请注意,您可能需要为您的对象手动训练网络(或模型)

Edit:

对于 Java 对象检测示例,请查看this https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android编码为的项目android,但在桌面应用程序中使用它们应该很简单。更具体地查看this https://github.com/tensorflow/tensorflow/blob/4a7bbb54f2841b9c871ac0dc0099ca690d9e1af2/tensorflow/examples/android/src/org/tensorflow/demo/TensorFlowObjectDetectionAPIModel.java#L111 part.

您不需要同时进行对象检测和分割,但如果您愿意,我认为首先尝试使用 python 训练分割模型(上面提供了链接),然后在 java 中使用该模型,与对象检测模型类似。

Edit 2:

我添加了一个简单的物体检测客户端 https://github.com/sumsuddin/TensorflowObjectDetectorJava in java它使用 Tensorflow 对象检测 APImodels https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md只是为了向您展示您可以在 java 中使用任何冻结模型。

另外,检查一下这个美丽的存储库 https://github.com/karolmajek/Mask_RCNN它使用像素级分割。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有办法获取图片中已识别物体的颜色? 的相关文章

随机推荐

  • iOS 7下蓝牙键盘如何支持上下方向键

    在 iOS 6 下 当使用外部蓝牙键盘以及在模拟器中工作时 UITextView 会遵循向上和向下箭头键 在 iOS 7 下 向上和向下箭头键不再执行任何操作 但左右箭头键仍然可以移动光标 iOS 7 下的 UITextView 如何支持外
  • 对“MainWindow vtable”的未定义引用

    我正在跟进Qt 的指南 https wiki qt io How to Use QPushButton用于使用QPushButton 我完全按照指南的建议进行操作 但出现编译错误 src mainwindow o In function M
  • 是否可以使用 bpython 作为完整的调试器?

    我想使用bpython http bpython interpreter org 用于调试的解释器 我的问题类似于 是否可以从代码进入ipython https stackoverflow com questions 1126930 is
  • 在 Ubuntu 18.04 上安装 Nodejs v18

    我们使用 Azure Pipelines 和使用 Ubuntu 18 04 作为操作系统的构建代理 我目前正在尝试将管道中的 Nodejs 版本从 16 更新到 18 通过使用 Nodejs 的安装非常简单Azure Pipelines 中
  • array[1][2] 和 array[1,2] 有什么区别? [关闭]

    Closed 这个问题是无法重现或由拼写错误引起 help closed questions 目前不接受答案 如果我的二维数组是 int array 4 5 1 2 3 4 5 6 7 8 9 0 11 12 13 14 15 16 17
  • Shopify Order API 是否允许按嵌套字段进行过滤?

    我正在使用shopify api gem API 文档 http api shopify com order html表明你可以瘦下来ShopifyAPI Order通过告诉它要返回哪些字段来响应 例如 以下内容将仅返回id属性 以及shi
  • `无法在继承的 Activity 中创建处理程序...Looper.prepare()`

    我有一个游戏Activity 活动 A 适用于所有代码 然后我创建一个新的Activity 活动 B 对于我的新游戏模式 extendsActivity A 然而 当遇到 Toast 行时 Activity B 突然抛出异常 Activit
  • 使用 Ruby/Erlang 迭代生成排列,无需递归或堆栈

    我想生成列表的所有排列 但我想在将它们添加到堆栈或存储在任何地方之前过滤掉一些排列 我将根据一些自定义的临时规则过滤掉排列 换句话说 我想生成一个大列表 50 300 个元素 的排列列表 但我想在这个过程中丢弃大部分生成的排列 我知道排列的
  • iOS 9 应用程序在多任务处理中的提交问题需要所有方向

    我正在使用 Xcode 7 将我的应用程序推送到应用程序商店 并且我的应用程序适用于 iPhone 和 iPad 但它仅支持纵向和横向 这是我的错误 如何提交特定方向的应用程序 例如仅保留纵向和横向 有解决问题的建议吗 如果您不想启用多任务
  • UML 类图:对实例的引用?

    我的类图中的某些类需要引用其他类或其自身的特定实例 我应该像在对象图中一样对它们进行建模还是有更好的选择 一般来说 由于对象图本身就是类图 因此可以将类图和对象图结合起来吗 thanks UML2引入复合结构图正是为了解决这个问题 在复合结
  • Angular.js 和 Express 的路由错误

    我正在尝试使用 angular js 围绕 parent root 进行路由 如果我使用锚链接等 则该路由有效 又名纯粹从角度处理的路由 例如 具有 parent createstudent 的 href 的链接可以工作但是 当我在网址栏中
  • 如何确定 matplotlib 轴对象的投影(2D 或 3D)?

    在 Python 的 matplotlib 库中 很容易在创建时指定坐标区对象的投影 import matplotlib pyplot as plt from mpl toolkits mplot3d import Axes3D ax pl
  • C# 是否需要检查某项是否有值以及某项是否大于 0?

    在项目中工作时 编码员在检查中经常这样做 首先 他检查是否可为空int有一个值 然后他检查它是否大于 0 为什么 如果一项检查 如果大于 0 就足够了 为什么还要进行两项检查 既然空值不大于0 那不是多余的吗 该代码可能是多余的 If i
  • 将经过身份验证的用户依赖项注入到我的存储库类的正确方法

    我正在使用具有存储库模式的服务层 控制器对服务层有依赖 服务层对存储库有依赖 我必须将登录的用户信息传递到存储库层以进行授权 并尝试确定将用户信息注入存储库的最佳方法 考虑到我似乎有一个广泛的注入链 controller gt servic
  • 从字符串创建嵌套列表结构

    我有一个由 n 个子字符串组成的字符串 它可能看起来像这样 string lt c A AA A BB A BB AAA B AA B BB B CC 该字符串中的每个子组件均通过 与其他子组件分隔 这里 第一级由值 A 和 B 组成 第二
  • iPhone 中 NSCachesDirectory 的大小

    我如何获取文件夹 NSCachesDirectory 的大小 即 Library Cache 我想知道这个文件夹的大小 以便我最终可以清除它 thanks 编辑 这是我的代码 NSDictionary attributes NSFileMa
  • 从包含一对整数的列表中删除重复元素的复杂性

    我有一个包含整数对的列表示例 gt 1 2 2 3 2 1 我想从中删除重复的元素 就像 1 2 和 2 1 相同 这是我的代码 gt class Pair
  • iOS 错误:“Project”没有可见的 @interface 声明选择器“alloc”

    我正在初始化一个对象 如下所示 Project Project Project alloc init 这是项目类的代码 项目 h import
  • Mifare Classic 1K 的锁定机制

    Mifare Classic 1K的流程是 轮询标签 验证这些标签 如果身份验证成功 则进行读 写 我已经完成了这些过程 并且还从特定扇区读取和写入数据 命令为轮询标签 is new byte byte 0xFF byte 0x00 byt
  • 有没有办法获取图片中已识别物体的颜色?

    我在用张量流 https www tensorflow org 为了识别提供的图片中的对象 请遵循此tutorial https www tensorflow org install install java并使用这个仓库 https gi