从零开始:Java使用通用物体识别-ResNet18镜像实现图像分类

news2026/4/1 20:54:05
从零开始Java使用通用物体识别-ResNet18镜像实现图像分类你是否想过用Java写几行代码就能让程序看懂一张图片里有什么过去这可能需要搭建复杂的Python环境、学习深度学习框架、处理繁琐的模型部署。但现在事情变得简单多了。今天我将带你体验一种全新的方式使用一个预置好的“通用物体识别-ResNet18”AI镜像在纯Java环境中快速构建一个图像分类服务。你不需要懂PyTorch不需要配Python环境甚至不需要知道模型文件在哪。整个过程就像调用一个普通的Java库一样简单。我们将从最基础的环境准备开始一步步实现图片上传、AI识别、结果解析的完整流程。无论你是Java后端开发想为系统增加智能识图功能还是单纯对AI应用感兴趣这篇文章都能让你在30分钟内跑通第一个可用的图像分类Demo。1. 项目准备理解我们要用的工具在开始写代码之前我们先花几分钟了解一下今天的主角通用物体识别-ResNet18镜像。1.1 镜像是什么为什么选择它简单来说这个镜像就是一个打包好的、开箱即用的AI服务。它基于PyTorch官方的ResNet-18模型已经在ImageNet数据集上训练好了能识别1000种常见的物体和场景。它解决了什么问题环境依赖不用安装Python、PyTorch、CUDA等复杂环境模型部署模型已经内置在镜像里不用自己下载和配置服务封装提供了标准的Web接口任何语言都能调用稳定性基于官方TorchVision实现没有第三方魔改的风险1.2 技术栈一览为了让概念更清晰我们看看这个镜像内部都包含了什么组件说明作用模型架构ResNet-18经典的深度卷积神经网络平衡了精度和速度训练数据ImageNet-1k包含1000个类别覆盖动物、植物、交通工具、日常用品等推理框架PyTorch TorchScript高性能的深度学习框架支持模型优化导出服务接口Flask WebUI REST API提供可视化界面和程序调用接口运行环境CPU优化版针对CPU推理做了优化内存占用小启动快1.3 它能识别什么这个模型能识别的东西比你想象的要多。不仅仅是具体的物体还能理解场景具体物体比如“金毛犬”、“咖啡杯”、“键盘”、“汽车”动物植物比如“老虎”、“大象”、“玫瑰”、“橡树”场景环境比如“高山”alp、“滑雪场”ski、“珊瑚礁”coral_reef人造物品比如“电视”、“手机”、“椅子”、“建筑”这意味着你上传一张旅游照片它不仅能识别出“山”还能识别出“雪山”和“滑雪”这样的组合场景。2. 环境搭建启动你的第一个AI服务现在让我们开始动手。整个过程分为三步获取镜像、启动服务、验证可用性。2.1 获取并启动镜像如果你使用的是CSDN云服务或者类似的容器平台操作非常简单搜索镜像在镜像市场搜索“通用物体识别-ResNet18”创建实例点击“部署”或“创建实例”配置资源选择CPU规格2核4G足够其他保持默认启动服务点击启动按钮等待容器运行如果你在本地Docker环境可以使用以下命令# 拉取镜像如果平台提供了镜像地址 docker pull your-registry/resnet18-classification:latest # 运行容器 docker run -d -p 5000:5000 \ --name resnet18-classifier \ your-registry/resnet18-classification:latest2.2 验证服务是否正常服务启动后打开浏览器访问http://你的服务器IP:5000你应该能看到一个简单的Web界面。这个界面允许你上传图片文件支持JPG、PNG格式查看上传的图片预览点击“识别”按钮进行分析查看识别结果Top-3类别和置信度手动测试一下找一张清晰的图片比如猫、狗、汽车通过Web界面上传查看识别结果是否合理如果一切正常你会看到类似这样的结果识别结果 1. 金毛犬 (92.3%) 2. 拉布拉多犬 (5.1%) 3. 狗 (1.8%)2.3 理解服务接口除了Web界面这个镜像还提供了一个REST API接口这就是我们Java程序要调用的接口地址POST http://你的服务器IP:5000/predict 请求格式multipart/form-data 参数名file图片文件 响应格式JSON一个典型的响应看起来像这样{ predictions: [ {class: golden_retriever, probability: 0.923}, {class: labrador, probability: 0.051}, {class: dog, probability: 0.018} ] }现在服务已经跑起来了接下来我们用Java来调用它。3. Java客户端开发三种调用方式实战我将展示三种不同的Java调用方式从最简单到最灵活你可以根据项目需求选择。3.1 方式一使用纯Java HTTP客户端最通用这是最直接的方式适合任何Java项目不依赖特定AI库。首先添加依赖到你的pom.xmldependencies !-- HTTP客户端 -- dependency groupIdcom.squareup.okhttp3/groupId artifactIdokhttp/artifactId version4.12.0/version /dependency !-- JSON解析 -- dependency groupIdcom.google.code.gson/groupId artifactIdgson/artifactId version2.10.1/version /dependency !-- 日志可选 -- dependency groupIdorg.slf4j/groupId artifactIdslf4j-simple/artifactId version2.0.9/version /dependency /dependencies然后创建我们的图像分类客户端import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import okhttp3.*; import java.io.File; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; /** * 图像分类客户端 - 通过HTTP API调用ResNet18服务 */ public class ImageClassifierClient { private final OkHttpClient client; private final String baseUrl; private final Gson gson new Gson(); // 定义响应数据结构 public static class Prediction { SerializedName(class) private String className; private double probability; // getters and setters public String getClassName() { return className; } public void setClassName(String className) { this.className className; } public double getProbability() { return probability; } public void setProbability(double probability) { this.probability probability; } Override public String toString() { return String.format(%s: %.2f%%, className, probability * 100); } } public static class PredictionResponse { private ListPrediction predictions; public ListPrediction getPredictions() { return predictions; } public void setPredictions(ListPrediction predictions) { this.predictions predictions; } } /** * 构造函数 * param baseUrl 服务地址如 http://localhost:5000 * param timeoutSeconds 超时时间秒 */ public ImageClassifierClient(String baseUrl, int timeoutSeconds) { this.baseUrl baseUrl; // 配置HTTP客户端启用连接池 this.client new OkHttpClient.Builder() .connectTimeout(timeoutSeconds, TimeUnit.SECONDS) .readTimeout(timeoutSeconds, TimeUnit.SECONDS) .writeTimeout(timeoutSeconds, TimeUnit.SECONDS) .connectionPool(new ConnectionPool(5, 5, TimeUnit.MINUTES)) .build(); } /** * 识别单张图片 * param imageFile 图片文件 * return 识别结果列表按置信度降序 * throws IOException 网络或IO异常 */ public ListPrediction predict(File imageFile) throws IOException { // 1. 构建请求体multipart/form-data RequestBody requestBody new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart( file, imageFile.getName(), RequestBody.create(imageFile, MediaType.parse(image/*)) ) .build(); // 2. 构建请求 Request request new Request.Builder() .url(baseUrl /predict) .post(requestBody) .addHeader(User-Agent, Java-ImageClassifier/1.0) .build(); // 3. 发送请求并解析响应 try (Response response client.newCall(request).execute()) { if (!response.isSuccessful()) { throw new IOException(请求失败: response.code() response.message()); } String responseBody response.body().string(); PredictionResponse predictionResponse gson.fromJson(responseBody, PredictionResponse.class); return predictionResponse.getPredictions(); } } /** * 批量识别多张图片 * param imageFiles 图片文件数组 * return 每张图片的识别结果 */ public ListListPrediction predictBatch(File... imageFiles) throws IOException { // 简单实现顺序调用实际生产环境可以考虑并行或服务端批量接口 // 这里为了简单演示实际使用时建议根据业务需求优化 return Arrays.stream(imageFiles) .map(file - { try { return predict(file); } catch (IOException e) { System.err.println(识别图片失败: file.getName() - e.getMessage()); return Collections.emptyList(); } }) .collect(Collectors.toList()); } /** * 测试方法 */ public static void main(String[] args) { try { // 创建客户端实例 ImageClassifierClient client new ImageClassifierClient(http://localhost:5000, 30); // 测试图片路径 File testImage new File(test_images/dog.jpg); if (!testImage.exists()) { System.out.println(测试图片不存在请准备一张测试图片); return; } System.out.println(开始识别图片: testImage.getName()); System.out.println(图片大小: testImage.length() bytes); // 调用识别接口 ListPrediction results client.predict(testImage); // 打印结果 System.out.println(\n识别结果 (Top-3):); System.out.println(.repeat(40)); for (int i 0; i Math.min(3, results.size()); i) { Prediction p results.get(i); System.out.printf(%d. %s (置信度: %.2f%%)\n, i 1, p.getClassName(), p.getProbability() * 100); } System.out.println(.repeat(40)); } catch (Exception e) { System.err.println(程序执行出错: e.getMessage()); e.printStackTrace(); } } }3.2 方式二集成到Spring Boot项目企业级方案如果你的项目基于Spring Boot这里有一个更优雅的集成方案。首先创建配置类import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; import okhttp3.OkHttpClient; import java.util.concurrent.TimeUnit; Configuration public class AiServiceConfig { Bean public OkHttpClient okHttpClient() { return new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .connectionPool(new ConnectionPool(10, 5, TimeUnit.MINUTES)) .build(); } Bean public RestTemplate restTemplate() { return new RestTemplate(); } }然后创建服务类import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import okhttp3.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.List; Service public class ImageClassificationService { Value(${ai.classifier.url:http://localhost:5000}) private String classifierUrl; Autowired private OkHttpClient httpClient; Data public static class ClassificationResult { private ListPrediction predictions; Data public static class Prediction { JsonProperty(class) private String className; private double probability; } } /** * 识别上传的图片 */ public ClassificationResult classifyImage(MultipartFile file) throws IOException { // 将MultipartFile转换为RequestBody RequestBody fileBody RequestBody.create( file.getBytes(), MediaType.parse(file.getContentType()) ); MultipartBody requestBody new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart(file, file.getOriginalFilename(), fileBody) .build(); Request request new Request.Builder() .url(classifierUrl /predict) .post(requestBody) .build(); try (Response response httpClient.newCall(request).execute()) { if (!response.isSuccessful()) { throw new RuntimeException(识别服务调用失败: response.code()); } String json response.body().string(); // 使用Jackson或Gson解析JSON // 这里简化处理实际使用时需要完整的JSON解析 return parseResult(json); } } /** * 批量识别 */ public ListClassificationResult classifyImages(ListMultipartFile files) { return files.parallelStream() .map(file - { try { return classifyImage(file); } catch (IOException e) { throw new RuntimeException(识别失败: file.getOriginalFilename(), e); } }) .collect(Collectors.toList()); } private ClassificationResult parseResult(String json) { // 实现JSON解析逻辑 // 可以使用Jackson的ObjectMapper return new ClassificationResult(); } }最后创建REST控制器import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.util.HashMap; import java.util.Map; RestController RequestMapping(/api/ai) public class ImageClassificationController { Autowired private ImageClassificationService classificationService; PostMapping(/classify) public ResponseEntityMapString, Object classifyImage( RequestParam(image) MultipartFile image) { try { if (image.isEmpty()) { return ResponseEntity.badRequest() .body(Map.of(error, 请上传图片文件)); } // 检查文件类型 String contentType image.getContentType(); if (contentType null || !contentType.startsWith(image/)) { return ResponseEntity.badRequest() .body(Map.of(error, 仅支持图片文件)); } // 调用识别服务 ImageClassificationService.ClassificationResult result classificationService.classifyImage(image); MapString, Object response new HashMap(); response.put(success, true); response.put(filename, image.getOriginalFilename()); response.put(size, image.getSize()); response.put(contentType, contentType); response.put(predictions, result.getPredictions()); return ResponseEntity.ok(response); } catch (Exception e) { return ResponseEntity.internalServerError() .body(Map.of( error, 识别失败, message, e.getMessage() )); } } PostMapping(/classify/batch) public ResponseEntityMapString, Object classifyImages( RequestParam(images) MultipartFile[] images) { // 批量处理逻辑 // ... return ResponseEntity.ok(Map.of(message, 批量识别完成)); } }3.3 方式三使用Apache HttpClient替代方案如果你不想用OkHttp也可以使用Java自带的HttpClient或者Apache HttpClientimport org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.File; import java.io.IOException; public class ApacheHttpClientExample { public String classifyImage(File imageFile) throws IOException { CloseableHttpClient httpClient HttpClients.createDefault(); HttpPost uploadFile new HttpPost(http://localhost:5000/predict); // 构建multipart请求 MultipartEntityBuilder builder MultipartEntityBuilder.create(); builder.addBinaryBody( file, imageFile, ContentType.APPLICATION_OCTET_STREAM, imageFile.getName() ); HttpEntity multipart builder.build(); uploadFile.setEntity(multipart); try (CloseableHttpResponse response httpClient.execute(uploadFile)) { HttpEntity responseEntity response.getEntity(); return EntityUtils.toString(responseEntity); } } }4. 实战演练构建完整的图像分类应用现在让我们把这些代码组合起来构建一个完整的小应用。4.1 项目结构规划image-classifier-demo/ ├── src/main/java/ │ ├── com/example/classifier/ │ │ ├── client/ # HTTP客户端 │ │ │ ├── ImageClassifierClient.java │ │ │ └── ApiClientConfig.java │ │ ├── service/ # 业务服务 │ │ │ ├── ClassificationService.java │ │ │ └── ImageProcessor.java │ │ ├── web/ # Web接口 │ │ │ ├── controller/ │ │ │ └── dto/ │ │ └── Application.java # 启动类 ├── src/main/resources/ │ ├── application.yml # 配置文件 │ └── static/ # 静态资源 ├── test_images/ # 测试图片目录 ├── pom.xml # Maven配置 └── README.md4.2 完整的示例应用这里是一个简化版的完整应用import java.io.File; import java.util.List; import java.util.Scanner; /** * 完整的图像分类演示应用 */ public class ImageClassifierDemoApp { private final ImageClassifierClient client; private final Scanner scanner; public ImageClassifierDemoApp(String serviceUrl) { this.client new ImageClassifierClient(serviceUrl, 30); this.scanner new Scanner(System.in); } /** * 交互式识别演示 */ public void interactiveDemo() { System.out.println( 图像分类演示程序 ); System.out.println(输入图片路径进行识别输入 quit 退出); System.out.println(); while (true) { System.out.print(请输入图片路径: ); String input scanner.nextLine().trim(); if (quit.equalsIgnoreCase(input)) { System.out.println(感谢使用再见); break; } if (input.isEmpty()) { System.out.println(路径不能为空请重新输入); continue; } File imageFile new File(input); if (!imageFile.exists()) { System.out.println(文件不存在: input); continue; } if (!imageFile.isFile()) { System.out.println(不是有效的文件: input); continue; } // 检查文件扩展名 String fileName imageFile.getName().toLowerCase(); if (!fileName.endsWith(.jpg) !fileName.endsWith(.jpeg) !fileName.endsWith(.png)) { System.out.println(仅支持 JPG/JPEG/PNG 格式图片); continue; } try { System.out.println(正在识别: imageFile.getName()); System.out.println(-.repeat(50)); long startTime System.currentTimeMillis(); ListPrediction results client.predict(imageFile); long endTime System.currentTimeMillis(); System.out.println(识别完成耗时: (endTime - startTime) ms); System.out.println(); if (results null || results.isEmpty()) { System.out.println(未识别到有效结果); } else { System.out.println(Top-3 识别结果:); System.out.println(.repeat(40)); for (int i 0; i Math.min(3, results.size()); i) { Prediction p results.get(i); System.out.printf(%d. %-30s %.2f%%\n, i 1, translateClassName(p.getClassName()), p.getProbability() * 100); } // 获取最可能的结果 Prediction topResult results.get(0); System.out.println(); System.out.println(最可能的结果: translateClassName(topResult.getClassName())); System.out.println(置信度: String.format(%.2f, topResult.getProbability() * 100) %); } System.out.println(.repeat(50)); System.out.println(); } catch (Exception e) { System.err.println(识别过程中出错: e.getMessage()); System.out.println(请检查服务是否正常运行或图片格式是否正确); System.out.println(); } } scanner.close(); } /** * 简单的类别名称翻译示例 */ private String translateClassName(String englishName) { // 这里可以扩展更完整的翻译词典 switch (englishName) { case golden_retriever: return 金毛犬; case labrador: return 拉布拉多犬; case dog: return 狗; case cat: return 猫; case car: return 汽车; case bird: return 鸟; case flower: return 花; case tree: return 树; case mountain: return 山; case beach: return 海滩; case building: return 建筑; case computer: return 电脑; case keyboard: return 键盘; case mouse: return 鼠标; case book: return 书; case chair: return 椅子; case table: return 桌子; case phone: return 手机; case television: return 电视; default: return englishName; } } /** * 批量处理演示 */ public void batchDemo(String directoryPath) { File directory new File(directoryPath); if (!directory.exists() || !directory.isDirectory()) { System.out.println(目录不存在: directoryPath); return; } File[] imageFiles directory.listFiles((dir, name) - name.toLowerCase().endsWith(.jpg) || name.toLowerCase().endsWith(.jpeg) || name.toLowerCase().endsWith(.png) ); if (imageFiles null || imageFiles.length 0) { System.out.println(目录中没有找到图片文件); return; } System.out.println(找到 imageFiles.length 张图片开始批量识别...); System.out.println(); int successCount 0; long totalTime 0; for (File imageFile : imageFiles) { try { System.out.print(处理: imageFile.getName() ... ); long startTime System.currentTimeMillis(); ListPrediction results client.predict(imageFile); long endTime System.currentTimeMillis(); long costTime endTime - startTime; totalTime costTime; if (results ! null !results.isEmpty()) { Prediction topResult results.get(0); System.out.printf(识别为: %s (%.1f%%, %dms)\n, translateClassName(topResult.getClassName()), topResult.getProbability() * 100, costTime); successCount; } else { System.out.println(识别失败); } } catch (Exception e) { System.out.println(出错: e.getMessage()); } } System.out.println(); System.out.println(批量处理完成!); System.out.println(成功处理: successCount / imageFiles.length); System.out.println(总耗时: totalTime ms); System.out.println(平均每张: (imageFiles.length 0 ? totalTime / imageFiles.length : 0) ms); } public static void main(String[] args) { // 配置服务地址 String serviceUrl http://localhost:5000; if (args.length 0) { serviceUrl args[0]; } ImageClassifierDemoApp app new ImageClassifierDemoApp(serviceUrl); System.out.println(请选择模式:); System.out.println(1. 交互式单张识别); System.out.println(2. 批量处理目录); System.out.print(请输入选择 (1/2): ); Scanner scanner new Scanner(System.in); String choice scanner.nextLine().trim(); if (2.equals(choice)) { System.out.print(请输入图片目录路径: ); String dirPath scanner.nextLine().trim(); app.batchDemo(dirPath); } else { app.interactiveDemo(); } scanner.close(); } }4.3 测试你的应用现在让我们测试一下这个应用准备测试图片在项目目录下创建test_images文件夹放入几张测试图片启动AI服务确保ResNet18镜像正在运行端口5000运行Java应用执行ImageClassifierDemoApp交互测试输入图片路径查看识别结果你可以尝试不同类型的图片动物照片猫、狗、鸟日常物品键盘、杯子、手机风景照片山、海、建筑食物图片水果、菜肴观察识别结果是否准确感受一下AI识别的速度和精度。5. 进阶技巧与优化建议基本的调用已经实现了但在实际项目中我们还需要考虑更多。下面是一些进阶技巧和优化建议。5.1 性能优化连接池配置// 优化OkHttpClient配置 OkHttpClient client new OkHttpClient.Builder() .connectionPool(new ConnectionPool(20, 5, TimeUnit.MINUTES)) // 更大的连接池 .connectTimeout(10, TimeUnit.SECONDS) // 合理的超时时间 .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .retryOnConnectionFailure(true) // 自动重试 .build();异步调用// 使用CompletableFuture进行异步调用 public CompletableFutureListPrediction predictAsync(File imageFile) { return CompletableFuture.supplyAsync(() - { try { return predict(imageFile); } catch (IOException e) { throw new CompletionException(e); } }); } // 批量异步处理 public ListCompletableFutureListPrediction predictBatchAsync(ListFile imageFiles) { return imageFiles.stream() .map(this::predictAsync) .collect(Collectors.toList()); }5.2 错误处理与重试public class RetryableClassifierClient { private static final int MAX_RETRIES 3; private static final long RETRY_DELAY_MS 1000; public ListPrediction predictWithRetry(File imageFile) throws IOException { int retryCount 0; while (retryCount MAX_RETRIES) { try { return predict(imageFile); } catch (IOException e) { retryCount; if (retryCount MAX_RETRIES) { throw e; } System.out.printf(第%d次重试...\n, retryCount); try { Thread.sleep(RETRY_DELAY_MS * retryCount); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new IOException(重试被中断, ie); } } } throw new IOException(达到最大重试次数); } // 指数退避重试 public ListPrediction predictWithExponentialBackoff(File imageFile) throws IOException { int retryCount 0; long delay RETRY_DELAY_MS; while (true) { try { return predict(imageFile); } catch (IOException e) { retryCount; if (retryCount MAX_RETRIES) { throw new IOException(重试失败: e.getMessage(), e); } System.out.printf(第%d次重试等待%dms...\n, retryCount, delay); try { Thread.sleep(delay); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new IOException(重试被中断, ie); } delay * 2; // 指数退避 } } } }5.3 结果缓存对于重复的图片识别可以考虑添加缓存import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; public class CachedImageClassifier { private final ImageClassifierClient delegate; private final ConcurrentHashMapString, CacheEntry cache; private final long cacheTimeoutMs; public CachedImageClassifier(ImageClassifierClient delegate, long cacheTimeoutMinutes) { this.delegate delegate; this.cache new ConcurrentHashMap(); this.cacheTimeoutMs TimeUnit.MINUTES.toMillis(cacheTimeoutMinutes); } public ListPrediction predictWithCache(File imageFile) throws IOException { // 生成缓存键可以使用文件MD5 String cacheKey generateCacheKey(imageFile); CacheEntry entry cache.get(cacheKey); if (entry ! null !entry.isExpired()) { System.out.println(缓存命中: imageFile.getName()); return entry.getPredictions(); } // 缓存未命中或已过期 System.out.println(缓存未命中重新识别: imageFile.getName()); ListPrediction predictions delegate.predict(imageFile); // 更新缓存 cache.put(cacheKey, new CacheEntry(predictions, System.currentTimeMillis())); return predictions; } private String generateCacheKey(File file) { // 简单实现使用文件名和最后修改时间 // 实际项目中可以使用MD5等更可靠的方式 return file.getName() _ file.lastModified(); } private class CacheEntry { private final ListPrediction predictions; private final long timestamp; CacheEntry(ListPrediction predictions, long timestamp) { this.predictions predictions; this.timestamp timestamp; } ListPrediction getPredictions() { return predictions; } boolean isExpired() { return System.currentTimeMillis() - timestamp cacheTimeoutMs; } } }5.4 监控与日志import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MonitoredImageClassifier { private static final Logger logger LoggerFactory.getLogger(MonitoredImageClassifier.class); private final ImageClassifierClient delegate; // 监控指标 private long totalRequests 0; private long successfulRequests 0; private long totalProcessingTimeMs 0; public ListPrediction predictWithMonitoring(File imageFile) throws IOException { totalRequests; long startTime System.currentTimeMillis(); try { ListPrediction result delegate.predict(imageFile); long processingTime System.currentTimeMillis() - startTime; successfulRequests; totalProcessingTimeMs processingTime; logger.info(识别成功: {} (大小: {} bytes, 耗时: {}ms), imageFile.getName(), imageFile.length(), processingTime); // 记录详细日志 if (logger.isDebugEnabled() result ! null !result.isEmpty()) { Prediction top result.get(0); logger.debug(Top结果: {} ({:.2f}%), top.getClassName(), top.getProbability() * 100); } return result; } catch (IOException e) { logger.error(识别失败: {} - {}, imageFile.getName(), e.getMessage(), e); throw e; } } public void printStatistics() { double successRate totalRequests 0 ? (double) successfulRequests / totalRequests * 100 : 0; double avgTime successfulRequests 0 ? (double) totalProcessingTimeMs / successfulRequests : 0; System.out.println( 服务统计 ); System.out.printf(总请求数: %d\n, totalRequests); System.out.printf(成功请求: %d\n, successfulRequests); System.out.printf(成功率: %.2f%%\n, successRate); System.out.printf(平均耗时: %.2fms\n, avgTime); } }6. 总结JavaAI的无限可能通过本文的实践我们完成了一个完整的Java图像分类应用。从启动AI服务到编写Java客户端再到构建完整的应用整个过程展示了Java在AI集成方面的强大能力。6.1 关键收获回顾零基础起步不需要深度学习背景不需要Python环境Java开发者也能快速上手AI应用服务化思维将AI能力封装成标准HTTP服务任何语言都能轻松调用工程化实践从简单的HTTP调用到企业级的Spring Boot集成展示了完整的工程路径性能与稳定通过连接池、缓存、重试等机制确保生产环境的可靠性6.2 三种方案的对比为了帮助你更好地选择这里对比一下我们介绍的几种方案方案优点缺点适用场景纯HTTP客户端简单直接无额外依赖适合任何Java项目需要自己处理HTTP细节功能相对基础快速原型、简单集成、学习演示Spring Boot集成符合企业标准易于扩展生态完善需要Spring Boot基础相对重量级生产环境、微服务架构、团队协作Apache HttpClientJava标准库兼容性好无需额外依赖API相对陈旧功能不如OkHttp丰富老项目集成、限制第三方库的环境6.3 下一步学习方向如果你对这个主题感兴趣可以继续探索模型优化尝试不同的预训练模型ResNet-50、MobileNet等比较精度和速度自定义训练使用自己的数据集微调模型实现特定领域的识别多模态扩展结合文本、语音等其他AI能力构建更智能的应用边缘部署将模型部署到移动设备或IoT设备实现离线识别性能调优探索模型量化、推理优化等技术进一步提升性能6.4 实际应用场景这个技术可以应用到很多实际场景中电商平台自动为商品图片打标签提升搜索和推荐效果内容审核识别违规图片辅助人工审核智能相册自动分类照片按人物、场景、时间组织工业检测识别产品缺陷提升质检效率教育应用识别动植物辅助自然教育AI不再是遥不可及的技术通过这样的预置镜像和简单的Java集成每个开发者都能快速构建智能应用。技术的价值不在于有多复杂而在于能解决多少实际问题。希望这篇文章能帮助你迈出Java AI应用的第一步。从识别一张图片开始开启你的智能应用开发之旅。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2473168.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…

wordpress后台更新后 前端没变化的解决方法

使用siteground主机的wordpress网站,会出现更新了网站内容和修改了php模板文件、js文件、css文件、图片文件后,网站没有变化的情况。 不熟悉siteground主机的新手,遇到这个问题,就很抓狂,明明是哪都没操作错误&#x…

网络编程(Modbus进阶)

思维导图 Modbus RTU(先学一点理论) 概念 Modbus RTU 是工业自动化领域 最广泛应用的串行通信协议,由 Modicon 公司(现施耐德电气)于 1979 年推出。它以 高效率、强健性、易实现的特点成为工业控制系统的通信标准。 包…

UE5 学习系列(二)用户操作界面及介绍

这篇博客是 UE5 学习系列博客的第二篇,在第一篇的基础上展开这篇内容。博客参考的 B 站视频资料和第一篇的链接如下: 【Note】:如果你已经完成安装等操作,可以只执行第一篇博客中 2. 新建一个空白游戏项目 章节操作,重…

IDEA运行Tomcat出现乱码问题解决汇总

最近正值期末周,有很多同学在写期末Java web作业时,运行tomcat出现乱码问题,经过多次解决与研究,我做了如下整理: 原因: IDEA本身编码与tomcat的编码与Windows编码不同导致,Windows 系统控制台…

利用最小二乘法找圆心和半径

#include <iostream> #include <vector> #include <cmath> #include <Eigen/Dense> // 需安装Eigen库用于矩阵运算 // 定义点结构 struct Point { double x, y; Point(double x_, double y_) : x(x_), y(y_) {} }; // 最小二乘法求圆心和半径 …

使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式

一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明&#xff1a;假设每台服务器已…

XML Group端口详解

在XML数据映射过程中&#xff0c;经常需要对数据进行分组聚合操作。例如&#xff0c;当处理包含多个物料明细的XML文件时&#xff0c;可能需要将相同物料号的明细归为一组&#xff0c;或对相同物料号的数量进行求和计算。传统实现方式通常需要编写脚本代码&#xff0c;增加了开…

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造&#xff0c;完美适配AGV和无人叉车。同时&#xff0c;集成以太网与语音合成技术&#xff0c;为各类高级系统&#xff08;如MES、调度系统、库位管理、立库等&#xff09;提供高效便捷的语音交互体验。 L…

(LeetCode 每日一题) 3442. 奇偶频次间的最大差值 I (哈希、字符串)

题目&#xff1a;3442. 奇偶频次间的最大差值 I 思路 &#xff1a;哈希&#xff0c;时间复杂度0(n)。 用哈希表来记录每个字符串中字符的分布情况&#xff0c;哈希表这里用数组即可实现。 C版本&#xff1a; class Solution { public:int maxDifference(string s) {int a[26]…

【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型

摘要 拍照搜题系统采用“三层管道&#xff08;多模态 OCR → 语义检索 → 答案渲染&#xff09;、两级检索&#xff08;倒排 BM25 向量 HNSW&#xff09;并以大语言模型兜底”的整体框架&#xff1a; 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后&#xff0c;分别用…

【Axure高保真原型】引导弹窗

今天和大家中分享引导弹窗的原型模板&#xff0c;载入页面后&#xff0c;会显示引导弹窗&#xff0c;适用于引导用户使用页面&#xff0c;点击完成后&#xff0c;会显示下一个引导弹窗&#xff0c;直至最后一个引导弹窗完成后进入首页。具体效果可以点击下方视频观看或打开下方…

接口测试中缓存处理策略

在接口测试中&#xff0c;缓存处理策略是一个关键环节&#xff0c;直接影响测试结果的准确性和可靠性。合理的缓存处理策略能够确保测试环境的一致性&#xff0c;避免因缓存数据导致的测试偏差。以下是接口测试中常见的缓存处理策略及其详细说明&#xff1a; 一、缓存处理的核…

龙虎榜——20250610

上证指数放量收阴线&#xff0c;个股多数下跌&#xff0c;盘中受消息影响大幅波动。 深证指数放量收阴线形成顶分型&#xff0c;指数短线有调整的需求&#xff0c;大概需要一两天。 2025年6月10日龙虎榜行业方向分析 1. 金融科技 代表标的&#xff1a;御银股份、雄帝科技 驱动…

观成科技:隐蔽隧道工具Ligolo-ng加密流量分析

1.工具介绍 Ligolo-ng是一款由go编写的高效隧道工具&#xff0c;该工具基于TUN接口实现其功能&#xff0c;利用反向TCP/TLS连接建立一条隐蔽的通信信道&#xff0c;支持使用Let’s Encrypt自动生成证书。Ligolo-ng的通信隐蔽性体现在其支持多种连接方式&#xff0c;适应复杂网…

铭豹扩展坞 USB转网口 突然无法识别解决方法

当 USB 转网口扩展坞在一台笔记本上无法识别,但在其他电脑上正常工作时,问题通常出在笔记本自身或其与扩展坞的兼容性上。以下是系统化的定位思路和排查步骤,帮助你快速找到故障原因: 背景: 一个M-pard(铭豹)扩展坞的网卡突然无法识别了,扩展出来的三个USB接口正常。…

未来机器人的大脑:如何用神经网络模拟器实现更智能的决策?

编辑&#xff1a;陈萍萍的公主一点人工一点智能 未来机器人的大脑&#xff1a;如何用神经网络模拟器实现更智能的决策&#xff1f;RWM通过双自回归机制有效解决了复合误差、部分可观测性和随机动力学等关键挑战&#xff0c;在不依赖领域特定归纳偏见的条件下实现了卓越的预测准…

Linux应用开发之网络套接字编程(实例篇)

服务端与客户端单连接 服务端代码 #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <pthread.h> …

华为云AI开发平台ModelArts

华为云ModelArts&#xff1a;重塑AI开发流程的“智能引擎”与“创新加速器”&#xff01; 在人工智能浪潮席卷全球的2025年&#xff0c;企业拥抱AI的意愿空前高涨&#xff0c;但技术门槛高、流程复杂、资源投入巨大的现实&#xff0c;却让许多创新构想止步于实验室。数据科学家…

深度学习在微纳光子学中的应用

深度学习在微纳光子学中的主要应用方向 深度学习与微纳光子学的结合主要集中在以下几个方向&#xff1a; 逆向设计 通过神经网络快速预测微纳结构的光学响应&#xff0c;替代传统耗时的数值模拟方法。例如设计超表面、光子晶体等结构。 特征提取与优化 从复杂的光学数据中自…