From 30511803eb4d7c6c408a175aafe1180c2dc68929 Mon Sep 17 00:00:00 2001 From: wangxun Date: Mon, 21 Apr 2025 15:39:33 +0800 Subject: [PATCH] =?UTF-8?q?=E7=BB=9F=E4=B8=80=E8=BF=94=E5=9B=9E=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=EF=BC=9B=E5=8D=8E=E8=BD=AF=E6=9C=8D=E5=8A=A1=E5=BC=82?= =?UTF-8?q?=E5=B8=B8=E4=BD=BF=E7=94=A8=E6=9C=AC=E5=9C=B0csv?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/impl/HikVisionServiceImpl.java | 438 +++++++++++------- 1 file changed, 268 insertions(+), 170 deletions(-) diff --git a/src/main/java/com/inspect/simulator/service/impl/HikVisionServiceImpl.java b/src/main/java/com/inspect/simulator/service/impl/HikVisionServiceImpl.java index 2651386..094147d 100644 --- a/src/main/java/com/inspect/simulator/service/impl/HikVisionServiceImpl.java +++ b/src/main/java/com/inspect/simulator/service/impl/HikVisionServiceImpl.java @@ -315,10 +315,10 @@ public class HikVisionServiceImpl implements HikVisionService { //channelId = 1299L; BasedataEqpBookChannel basedataEqpBookChannel = basedataEqpBookChannelMapper.selectBasedataEqpBookChannelByChannelId(channelId); if (basedataEqpBookChannel != null) { - int firstX = 0; - int firstY = 0; - int secondX = 512; - int secondY = 640; + int firstX = 1; + int firstY = 1; + int secondX = 639; + int secondY = 511; int imgWidth = 640; int imgHeight = 512; if (infraPictureInfo.getCoordinates() != null && !infraPictureInfo.getCoordinates().isEmpty()) { @@ -342,7 +342,7 @@ public class HikVisionServiceImpl implements HikVisionService { } } - + //相机红外图谱获取 public InfraredInfo readDataHw(byte[] bytes, Coordinate coordinate) throws IOException { InfraredInfo infraredInfo = new InfraredInfo(); @@ -541,7 +541,6 @@ public class HikVisionServiceImpl implements HikVisionService { return infraredInfo; } - //校验 public static byte[] locateAndReadInfraredData(byte[] fileData) { // 文件末尾标识 @@ -601,7 +600,6 @@ public class HikVisionServiceImpl implements HikVisionService { } } - //图片标注__nvr // public String ImageOverlaysNvr(Coordinate coordinate, InfraredInfo infraredInfo) { // @@ -722,108 +720,118 @@ public class HikVisionServiceImpl implements HikVisionService { // } //图片标注_iVS1800 -// public String ImageOverlaysIvs(Coordinate coordinate, InfraredInfo infraredInfo) { -// -// Coordinate[] coordinates = coordinate.getCoordinates(); -// -// Date date = new Date(); -// SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss"); -// String markPicName = sf.format(date); -// // 图片路径(请替换为实际路径) -// String imagePath = coordinate.getFilePath(); -// // 获取文件名(不含扩展名) -// File file = new File(imagePath); -// String fileName = file.getName(); -// String pureName = fileName.substring(0, fileName.lastIndexOf('.')); -// String filename = picPath; -// String outputPath = picPath + pureName + "_" + markPicName + ".jpg"; -// //判断路径是否存在 -// File filePath = new File(filename); -// if (!filePath.exists()) { -// //不存在,创建目录 -// filePath.mkdirs(); -// } -// try { -// // 加载原始图片 -// BufferedImage originalImage = ImageIO.read(new File(imagePath)); -// if (originalImage == null) { -// System.err.println("无法加载图片: " + imagePath); -// return null; -// } -// -// // 创建可编辑的图片副本 -// BufferedImage annotatedImage = new BufferedImage( -// originalImage.getWidth(), -// originalImage.getHeight(), -// BufferedImage.TYPE_INT_RGB -// ); -// // 绘制原始图片 -// Graphics2D g2d = annotatedImage.createGraphics(); -// g2d.drawImage(originalImage, 0, 0, null); -// -// // 设置标注样式 -// g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); -// Font font = new Font("微软雅黑", Font.BOLD, 17); -// -// for (Coordinate c : coordinates) { -// g2d.setFont(font); -// //矩阵标注 -// if (c.getSecondX() != null && c.getSecondY() != null) { -// // 标注矩形(每两个点确定一个矩形) -// g2d.setColor(Color.WHITE); -// int x1 = c.getFirstX(); -// int y1 = c.getFirstY(); -// int x2 = c.getSecondX(); -// int y2 = c.getSecondY(); -// -// // 确保坐标在图片范围内 -// if (x1 >= 0 && x1 < originalImage.getWidth() && y1 >= 0 && y1 < originalImage.getHeight() && -// x2 >= 0 && x2 < originalImage.getWidth() && y2 >= 0 && y2 < originalImage.getHeight()) { -// -// // 确保x1,y1是左上角,x2,y2是右下角 -// int rectX = Math.min(x1, x2); -// int rectY = Math.min(y1, y2); -// int width = Math.abs(x2 - x1); -// int height = Math.abs(y2 - y1); -// // 绘制矩形 -// g2d.drawRect(rectX, rectY, width, height); -// -// coordinate.setFirstX(x1); -// coordinate.setFirstY(y1); -// coordinate.setSecondX(x2); -// coordinate.setSecondY(y2); -// // 添加矩形标签 -// //图片路径取值 -// String[] dividePath = Paths.get(imagePath).getFileName().toString().replaceAll("(?i)\\.jpg$", "").split("_"); + public String ImageOverlaysIvs(InfraPictureInfo infraPictureInfo, InfraredInfo infraredInfo) { + + List coordinates = infraPictureInfo.getCoordinates(); + + Date date = new Date(); + SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss"); + String markPicName = sf.format(date); + // 图片路径(请替换为实际路径) + String imagePath = infraPictureInfo.getFilePath(); + // 获取文件名(不含扩展名) + File file = new File(imagePath); + String fileName = file.getName(); + String pureName = fileName.substring(0, fileName.lastIndexOf('.')); + String filename = picPath; + String outputPath = picPath + pureName + "_" + markPicName + ".jpg"; + //判断路径是否存在 + File filePath = new File(filename); + if (!filePath.exists()) { + //不存在,创建目录 + filePath.mkdirs(); + } + try { + // 加载原始图片 + InputStream inputStreamPath = downloadFtp(imagePath); + if (inputStreamPath == null) { + System.out.println("无法加载图片: " + imagePath); + } + BufferedImage originalImage = ImageIO.read(inputStreamPath); + if (originalImage == null) { + System.err.println("无法加载图片: " + imagePath); + return null; + } + + // 创建可编辑的图片副本 + BufferedImage annotatedImage = new BufferedImage( + originalImage.getWidth(), + originalImage.getHeight(), + BufferedImage.TYPE_INT_RGB + ); + // 绘制原始图片 + Graphics2D g2d = annotatedImage.createGraphics(); + g2d.drawImage(originalImage, 0, 0, null); + + // 设置标注样式 + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + Font font = new Font("微软雅黑", Font.BOLD, 17); + + for (Coordinate c : coordinates) { + g2d.setFont(font); + //矩阵标注 + if (c.getSecondX() != null && c.getSecondY() != null) { + // 标注矩形(每两个点确定一个矩形) + g2d.setColor(Color.WHITE); + int x1 = c.getFirstX(); + int y1 = c.getFirstY(); + int x2 = c.getSecondX(); + int y2 = c.getSecondY(); + + // 确保坐标在图片范围内 + if (x1 >= 0 && x1 < originalImage.getWidth() && y1 >= 0 && y1 < originalImage.getHeight() && + x2 >= 0 && x2 < originalImage.getWidth() && y2 >= 0 && y2 < originalImage.getHeight()) { + + // 确保x1,y1是左上角,x2,y2是右下角 + int rectX = Math.min(x1, x2); + int rectY = Math.min(y1, y2); + int width = Math.abs(x2 - x1); + int height = Math.abs(y2 - y1); + // 绘制矩形 + g2d.drawRect(rectX, rectY, width, height); + + infraPictureInfo.setFirstX(x1); + infraPictureInfo.setFirstY(y1); + infraPictureInfo.setSecondX(x2); + infraPictureInfo.setSecondY(y2); + // 添加矩形标签 + //图片路径取值 + String[] dividePath = Paths.get(imagePath).getFileName().toString().replaceAll("(?i)\\.jpg$", "").split("_"); // String max = dividePath[dividePath.length - 3]; // 最大值 // String min = dividePath[dividePath.length - 2]; // 最小值 -// String avg = dividePath[dividePath.length - 1]; // 平均值 -// infraredInfo.setFrameMax(Float.parseFloat(max)); -//// g2d.drawString("平均温度:" +avg + "最高温度:" + max + "最低温度:" + min, rectX + 5, rectY + 15); -// -// String line1 = "平均温度:" + avg; + String max = dividePath[dividePath.length - 1]; // 最大值 + infraredInfo.setFrameMax(Float.parseFloat(max)); +// g2d.drawString("平均温度:" +avg + "最高温度:" + max + "最低温度:" + min, rectX + 5, rectY + 15); + + String line1 = "最高温度:" + max; // String line2 = "最高温度:" + max; // String line3 = "最低温度:" + min; -// -// g2d.drawString(line1, rectX + 5, rectY + 15); + + g2d.drawString(line1, rectX + 5, rectY + 15); // g2d.drawString(line2, rectX + 5, rectY + 30); // g2d.drawString(line3, rectX + 5, rectY + 45); -// } -// } -// } -// g2d.dispose(); + } + } + } + g2d.dispose(); + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + ImageIO.write(annotatedImage, "jpg", os); + InputStream inputStream = new ByteArrayInputStream(os.toByteArray()); + + picFtp(outputPath, inputStream, ftpUrlAddress, ftpUrlPort, ftpUrlAccount, ftpUrlPwd); + // // 保存标注后的图片 // File outputFile = new File(outputPath); // // 确保输出目录存在 // outputFile.getParentFile().mkdirs(); // ImageIO.write(annotatedImage, "jpg", outputFile); -// } catch (IOException e) { -// System.err.println("处理图片时出错: " + e.getMessage()); -// e.printStackTrace(); -// } -// return outputPath; -// } - + } catch (IOException e) { + System.err.println("处理图片时出错: " + e.getMessage()); + e.printStackTrace(); + } + return outputPath; + } //图片标注__无人机 public String ImageOverlaysUav(InfraPictureInfo infraPictureInfo, InfraredInfo infraredInfo) { @@ -958,6 +966,7 @@ public class HikVisionServiceImpl implements HikVisionService { return outputPath; } + //调用华软接口获取csv文件 public float[][] UploadFtpImage(String url, String type, String image) { type = "ftp"; @@ -1005,25 +1014,13 @@ public class HikVisionServiceImpl implements HikVisionService { } } catch (Exception e) { System.err.println("FTP请求处理失败,尝试本地文件: " + e.getMessage()); - - // Fall back to local file - try { - String localPath = picPath + "1.csv"; -// String csvFileName = image.replaceAll("\\..+$", ".csv"); - File csvFile = new File(localPath); - if (!csvFile.exists()) { - throw new FileNotFoundException("本地CSV文件不存在: " + csvFile.getAbsolutePath()); - } - floats = parseCsvFromFtp(csvFile.toString()); - } catch (Exception localException) { - System.err.println("本地文件处理失败: " + localException.getMessage()); - localException.printStackTrace(); - } + // + return null; } return floats; } - + //解析获取csv文件温度 private float[][] parseCsvFromFtp(String csvUrl) throws IOException { FTPClient ftp = new FTPClient(); @@ -1092,7 +1089,7 @@ public class HikVisionServiceImpl implements HikVisionService { } } - + //上传图片到ftp public void picFtp(String newPath, InputStream originalPath, String ftpUrlAddress, Integer ftpUrlPort, String ftpUrlAccount, String ftpUrlPwd) { FTPSClient ftps = null; try { @@ -1125,7 +1122,8 @@ public class HikVisionServiceImpl implements HikVisionService { } } - public void pic2Ftp(String newPath, InputStream originalPath, String ftpUrlAddress, Integer ftpUrlPort, String ftpUrlAccount, String ftpUrlPwd) { + //华软上传图片到ftp + public boolean pic2Ftp(String newPath, InputStream originalPath, String ftpUrlAddress, Integer ftpUrlPort, String ftpUrlAccount, String ftpUrlPwd) { FTPClient ftps = null; try { ftps = new FTPClient(); @@ -1141,7 +1139,7 @@ public class HikVisionServiceImpl implements HikVisionService { System.err.println("上传失败!FTP 返回: " + ftps.getReplyString()); } } catch (Exception e) { - e.printStackTrace(); + return false; } finally { // 5. 关闭资源 try { @@ -1151,11 +1149,14 @@ public class HikVisionServiceImpl implements HikVisionService { ftps.disconnect(); } } catch (IOException e) { - e.printStackTrace(); +// e.printStackTrace(); + return false; } } + return true; } + //ftp图片获取 public InputStream downloadFtp(String downloadPath) { InputStream inputStream = null; FTPSClient ftps; @@ -1181,6 +1182,36 @@ public class HikVisionServiceImpl implements HikVisionService { } + //异常处理返回本地csv + private float[][] exceptionHandling() throws IOException { + String localPath = picPath + "1.csv"; + InputStream inputStream = downloadFtp(localPath); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + + List rows = new ArrayList<>(); + String line; + while ((line = reader.readLine()) != null) { + if (line.trim().isEmpty()) { + continue; + } + String[] stringValues = line.split(","); + float[] floatValues = new float[stringValues.length]; + for (int i = 0; i < stringValues.length; i++) { + try { + floatValues[i] = Float.parseFloat(stringValues[i].trim()); + } catch (NumberFormatException e) { + throw new IOException("Invalid number format in CSV at value: " + stringValues[i], e); + } + } + rows.add(floatValues); + } + float[][] result = new float[rows.size()][]; + for (int i = 0; i < rows.size(); i++) { + result[i] = rows.get(i); + } + return result; + } + @Override public ResponseEntity irPicAnalyse(final String analyseRequestJson) { log.info("[INFRARED] irPicAnalyse: analyseRequestJson={}", analyseRequestJson); @@ -1195,7 +1226,7 @@ public class HikVisionServiceImpl implements HikVisionService { List analyseReqItemList = analyseRequest.getObjectList(); - if(analyseReqItemList == null || analyseReqItemList.isEmpty()) { + if (analyseReqItemList == null || analyseReqItemList.isEmpty()) { log.error("[INFRARED] irPicAnalyse: analyseReqItemList empty!"); return ResponseEntity.ok().body("{\"code\":\"202\"}"); } @@ -1203,21 +1234,36 @@ public class HikVisionServiceImpl implements HikVisionService { final AnalyseReqItem analyseReqItem = analyseReqItemList.get(0); final String[] typeList = analyseReqItem.getTypeList(); String algType = "unKnownType"; - if(typeList != null && typeList.length != 0) { + if (typeList != null && typeList.length != 0) { algType = typeList[0]; } final String feedBackHostIp = analyseRequest.getRequestHostIp(); final String feedBackPort = analyseRequest.getRequestHostPort(); final String feedbackUrl = feedBackHostIp + feedBackPort + "/picAnalyseRetNotify"; log.info("[INFRARED] irPicAnalyse: feedbackUrl={}", feedbackUrl); + String[] imageUrlList = analyseReqItem.getImageUrlList(); + + InfraPictureInfo infraPictureInfo = new InfraPictureInfo(); + infraPictureInfo.setImgType(3); + infraPictureInfo.setFilePath(imageUrlList[0]); + InfraredInfo infraredInfo = calculatePicture(infraPictureInfo); + AnalyseResult analyseResult = new AnalyseResult(); analyseResult.setRequestId(analyseRequest.getRequestId()); AnalyseResPoint analyseResPoint = new AnalyseResPoint(); - analyseResPoint.setValue("0"); - analyseResPoint.setConf("0.85"); +// analyseResPoint.setValue("0"); +// analyseResPoint.setConf("0.85"); + if (String.valueOf((double) infraredInfo.getFrameMax()) != null) { + analyseResPoint.setValue("0");//成功 + } else { + analyseResPoint.setValue("1");//失败 + } + analyseResPoint.setConf(String.format("%.2f", (double) infraredInfo.getFrameMax())); + analyseResPoint.setResImageUrl(infraredInfo.getOutPath()); + analyseResPoint.setCode("2000"); - analyseResPoint.setResImageUrl(analyseRequest.getObjectList().get(0).getImageUrlList()[0]); +// analyseResPoint.setResImageUrl(analyseRequest.getObjectList().get(0).getImageUrlList()[0]); List analyseResPoints = new ArrayList<>(); analyseResPoints.add(analyseResPoint); AnalyseResItem analyseResItem = new AnalyseResItem(); @@ -1230,6 +1276,7 @@ public class HikVisionServiceImpl implements HikVisionService { try { String analyseResultOutJson = JSONObject.toJSONString(analyseResult); + log.info("[INFRARED] irPicAnalyse: feedbackUrl={}, analyseResultOutJson={}", feedbackUrl, analyseResultOutJson); String result = HttpClientUtils.sendPostAgain(feedbackUrl, analyseResultOutJson); log.info("[INFRARED] irPicAnalyse: feedbackUrl={}, result: {}", feedbackUrl, result); @@ -1238,56 +1285,107 @@ public class HikVisionServiceImpl implements HikVisionService { } return ResponseEntity.ok().body("{\"code\":\"200\"}"); -// InfraredInfo infraredInfo = new InfraredInfo(); -// try { -// String imagePath = infraPictureInfo.getFilePath(); -//// String imagePath = "/images/ir_test.jpg"; -// InputStream inputStream = downloadFtp(imagePath); -// String protocol = hrFtpUrl.substring(0, 6); // "ftp://" -// String withoutProtocol = hrFtpUrl.substring(6); // "zthr02:zthr02@123.184.14.138:50021/" -// String[] userAndHost = withoutProtocol.split("@"); -// if (userAndHost.length != 2) { -// throw new IllegalArgumentException("URL 格式错误,缺少 @ 分隔符"); -// } -// String[] userPass = userAndHost[0].split(":"); -// String username = userPass[0]; -// String password = userPass[1]; -// String hostPort = userAndHost[1].replace("/", ""); // 移除末尾的 "/" -// String[] hostAndPort = hostPort.split(":"); -// String host = hostAndPort[0]; -// int port = Integer.parseInt(hostAndPort[1]); -// picFtp("/", inputStream, host, port, username, password); -// -// String imageName = Paths.get(imagePath).getFileName().toString(); -// String ftpUrlName = "[\"" + hrFtpUrl + imageName + "\"]"; -// -// -// if (infraPictureInfo.getImgType() == 1) { + + + } + + public InfraredInfo calculatePicture(InfraPictureInfo infraPictureInfo) { + + InfraredInfo infraredInfo = new InfraredInfo(); + String imagePath = infraPictureInfo.getFilePath(); + InputStream inputStream = downloadFtp(imagePath); + + if (infraPictureInfo.getImgType() == 1) { // byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath)); // infraredInfo = readDataHw(imageBytes, infraPictureInfo.getCoordinates().get(0)); -// } else if (infraPictureInfo.getImgType() == 2) { -// -//// String s = ImageOverlaysIvs(infraPictureInfo.getCoordinates().get(0), infraredInfo); -//// infraredInfo.setOutPath(s); -// } else if (infraPictureInfo.getImgType() == 3) { -// //sdk版本调用x86_32 -// //float[][] imageTem = djService.getImageTem(coordinate.getFilePath()); -// -// //调用华软接口 -// float[][] imageTem = UploadFtpImage(hrUavUrl, null, ftpUrlName); -// if (imageTem != null && imageTem.length > 0 && imageTem[0].length > 0) { -// infraredInfo.setTemperatureMatrix(imageTem); -// String s = ImageOverlaysUav(infraPictureInfo, infraredInfo); -// infraredInfo.setOutPath(s); -// } else { -// return AjaxResult.error("温度解析错误!"); -// } -// } -// } catch (Exception e) { -// e.printStackTrace(); -// return AjaxResult.error(); -// } -// return AjaxResult.success(infraredInfo); + } else if (infraPictureInfo.getImgType() == 2) { + +// String s = ImageOverlaysIvs(infraPictureInfo.getCoordinates().get(0), infraredInfo); +// infraredInfo.setOutPath(s); + } else if (infraPictureInfo.getImgType() == 3) { + //sdk版本调用x86_32 + //float[][] imageTem = djService.getImageTem(coordinate.getFilePath()); + + Long channelId = infraPictureInfo.getChannelId(); + BasedataEqpBookChannel basedataEqpBookChannel = basedataEqpBookChannelMapper.selectBasedataEqpBookChannelByChannelId(channelId); + int firstX = 1; + int firstY = 1; + int secondX = 639; + int secondY = 511; + int imgWidth = 640; + int imgHeight = 512; + if (basedataEqpBookChannel!=null) { + if (basedataEqpBookChannel.getChannelContent() !=null) { + String[] parts = basedataEqpBookChannel.getChannelContent().split(","); + // 解析坐标 + firstX = Integer.parseInt(parts[0]); + firstY = Integer.parseInt(parts[1]); + secondX = Integer.parseInt(parts[2]); + secondY = Integer.parseInt(parts[3]); + imgHeight = Integer.parseInt(parts[4]); + imgWidth = Integer.parseInt(parts[5]); + } + } else { + log.info("设置标注点位不存在!"); + } + List coordinates = new ArrayList<>(); + coordinates.add(new Coordinate(firstX, firstY, secondX, secondY)); + infraPictureInfo.setImgWidth(imgWidth); + infraPictureInfo.setImgHeight(imgHeight); + infraPictureInfo.setCoordinates(coordinates); + + //调用华软接口 + String protocol = hrFtpUrl.substring(0, 6); // "ftp://" + String withoutProtocol = hrFtpUrl.substring(6); // "zthr02:zthr02@123.184.14.138:50021/" + String[] userAndHost = withoutProtocol.split("@"); + if (userAndHost.length != 2) { + throw new IllegalArgumentException("URL 格式错误,缺少 @ 分隔符"); + } + String[] userPass = userAndHost[0].split(":"); + String username = userPass[0]; + String password = userPass[1]; + String hostPort = userAndHost[1].replace("/", ""); // 移除末尾的 "/" + String[] hostAndPort = hostPort.split(":"); + String host = hostAndPort[0]; + int port = Integer.parseInt(hostAndPort[1]); + String imageName = Paths.get(imagePath).getFileName().toString(); + boolean isLoginHr = pic2Ftp(imageName, inputStream, host, port, username, password); + String ftpUrlName = "[\"" + hrFtpUrl + imageName + "\"]"; + + + float[][] imageTem=new float[0][]; + if (isLoginHr) { + //可以登陆华软ftp + imageTem = UploadFtpImage(hrUavUrl, null, ftpUrlName); + if (imageTem != null && imageTem.length > 0 && imageTem[0].length > 0) { + infraredInfo.setTemperatureMatrix(imageTem); + } else { + //不能调用华软接口,使用本地csv + log.info("温度解析错误,接口无法调用!"); + try { + imageTem = exceptionHandling(); + infraredInfo.setTemperatureMatrix(imageTem); + } catch (IOException e) { + e.printStackTrace(); + } + } + String s = ImageOverlaysUav(infraPictureInfo, infraredInfo); + infraredInfo.setOutPath(s); + }else{ + //华软ftp不能登录,使用本地csv + log.info("温度解析错误.ftp无法登陆!"); + try { + imageTem = exceptionHandling(); + infraredInfo.setTemperatureMatrix(imageTem); + } catch (IOException e) { + e.printStackTrace(); + } + String s = ImageOverlaysUav(infraPictureInfo, infraredInfo); + infraredInfo.setOutPath(s); + + } + } + return infraredInfo; }