首页 > 其他分享 >11.8 图像增强与动漫化二

11.8 图像增强与动漫化二

时间:2024-12-29 14:59:42浏览次数:6  
标签:11.8 String java 化二 public result new import 图像增强

/*
 * Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
 */
package org.example;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;

/**
 * Json工具类.
 */
public class GsonUtils {
    private static Gson gson = new GsonBuilder().create();

    public static String toJson(Object value) {
        return gson.toJson(value);
    }

    public static <T> T fromJson(String json, Class<T> classOfT) throws JsonParseException {
        return gson.fromJson(json, classOfT);
    }

    public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException {
        return (T) gson.fromJson(json, typeOfT);
    }
}

  

package org.example;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * http 工具类
 */
public class HttpUtil {

    public static String post(String requestUrl, String accessToken, String params)
            throws Exception {
        String contentType = "application/x-www-form-urlencoded";
        return HttpUtil.post(requestUrl, accessToken, contentType, params);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params)
            throws Exception {
        String encoding = "UTF-8";
        if (requestUrl.contains("nlp")) {
            encoding = "GBK";
        }
        return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
            throws Exception {
        String url = requestUrl + "?access_token=" + accessToken;
        return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
    }

    public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
            throws Exception {
        URL url = new URL(generalUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(params.getBytes(encoding));
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> headers = connection.getHeaderFields();
        // 遍历所有的响应头字段
        for (String key : headers.keySet()) {
            System.err.println(key + "--->" + headers.get(key));
        }
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        System.err.println("result:" + result);
        return result;
    }
}

  

package org.example;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class ImageProcessingUI extends JFrame {

    private JTextField filePathField;
    private JButton selectFileButton;
    private JButton processButton;
    private JLabel originalImageLabel;
    private JLabel processedImageLabel;
    private String selectedAction; // "anime" 或 "enhance"

    public ImageProcessingUI() {
        setTitle("图像处理");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        // 创建顶部面板
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new GridLayout(3, 2, 5, 5)); // 添加间距

        JLabel filePathLabel = new JLabel("图片路径:");
        filePathField = new JTextField();
        filePathField.setColumns(30);

        selectFileButton = new JButton("选择图片");
        selectFileButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                int result = fileChooser.showOpenDialog(ImageProcessingUI.this);
                if (result == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = fileChooser.getSelectedFile();
                    filePathField.setText(selectedFile.getAbsolutePath());
                    displayOriginalImage(selectedFile);
                }
            }
        });

        JButton actionSelectButton = new JButton("选择操作");
        actionSelectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String action = (String) JOptionPane.showInputDialog(ImageProcessingUI.this, "请选择操作:",
                        "操作选择", JOptionPane.QUESTION_MESSAGE, null, new Object[]{"动漫化", "清晰度增强"}, "动漫化");
                selectedAction = action;
            }
        });

        processButton = new JButton("处理");
        processButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String filePath = filePathField.getText();
                if (filePath.isEmpty()) {
                    JOptionPane.showMessageDialog(ImageProcessingUI.this, "请选择一个图片文件。", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                String result = processImage(filePath);
                if (result != null) {
                    JOptionPane.showMessageDialog(ImageProcessingUI.this, "结果已保存。", "成功", JOptionPane.INFORMATION_MESSAGE);
                    displayProcessedImage(new File(result));
                } else {
                    JOptionPane.showMessageDialog(ImageProcessingUI.this, "处理图片失败。", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        topPanel.add(filePathLabel);
        topPanel.add(filePathField);
        topPanel.add(selectFileButton);
        topPanel.add(actionSelectButton);
        topPanel.add(processButton);

        // 创建中间面板用于显示图像
        JPanel imagePanel = new JPanel();
        imagePanel.setLayout(new GridLayout(1, 2, 10, 10)); // 添加间距

        originalImageLabel = new JLabel("原始图像");
        originalImageLabel.setHorizontalAlignment(SwingConstants.CENTER);
        originalImageLabel.setBorder(BorderFactory.createTitledBorder("原始图像"));

        processedImageLabel = new JLabel("处理后的图像");
        processedImageLabel.setHorizontalAlignment(SwingConstants.CENTER);
        processedImageLabel.setBorder(BorderFactory.createTitledBorder("处理后的图像"));

        imagePanel.add(originalImageLabel);
        imagePanel.add(processedImageLabel);

        panel.add(topPanel, BorderLayout.NORTH);
        panel.add(imagePanel, BorderLayout.CENTER);

        add(panel);

        // 设置背景颜色
        panel.setBackground(Color.LIGHT_GRAY);
        topPanel.setBackground(Color.LIGHT_GRAY);
        imagePanel.setBackground(Color.LIGHT_GRAY);
    }

    private void displayOriginalImage(final File file) {
        SwingUtilities.invokeLater(() -> {
            try {
                BufferedImage originalImage = ImageIO.read(file);
                ImageIcon icon = new ImageIcon(resizeImage(originalImage, 350, 350));
                originalImageLabel.setIcon(icon);
                originalImageLabel.setText(""); // 清除文本
            } catch (IOException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "加载原始图像失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
    }

    private void displayProcessedImage(final File file) {
        SwingUtilities.invokeLater(() -> {
            try {
                BufferedImage processedImage = ImageIO.read(file);
                ImageIcon icon = new ImageIcon(resizeImage(processedImage, 350, 350));
                processedImageLabel.setIcon(icon);
                processedImageLabel.setText(""); // 清除文本
            } catch (IOException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "加载处理后的图像失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
    }

    private BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
        Image temp = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
        BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = resizedImage.createGraphics();
        g2d.drawImage(temp, 0, 0, null);
        g2d.dispose();
        return resizedImage;
    }

    public String processImage(String filePath) {
        try {
            byte[] imgData = Files.readAllBytes(Paths.get(filePath));
            String imgStr = Base64.getEncoder().encodeToString(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 获取access_token
            String accessToken = AuthService.getAuth(API_KEY, SECRET_KEY);

            String url;
            if ("动漫化".equals(selectedAction)) {
                url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime";
            } else {
                url = "https://aip.baidubce.com/rest/2.0/image-process/v1/image_definition_enhance";
            }

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);

            // 解析返回的结果
            if (result != null && !result.isEmpty()) {
                // 假设返回的JSON中包含一个名为"image"的字段,该字段包含Base64编码的图像数据
                String base64EncodedString = parseBase64FromResult(result);

                // 解码Base64字符串
                byte[] decodedBytes = Base64.getDecoder().decode(base64EncodedString);

                // 指定输出文件名
                String outputFilePath = "output_image.jpg"; // 或者其他格式,比如.png等

                // 将解码后的字节写入到指定的文件中
                Files.write(Paths.get(outputFilePath), decodedBytes);

                System.out.println("图像已保存到:" + outputFilePath);
                return outputFilePath;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String parseBase64FromResult(String result) {
        // 这里假设返回的JSON格式如下:
        // {"log_id":1234567890,"image":"base64_encoded_string"}
        // 你需要根据实际返回的JSON格式进行解析
        // 可以使用JSON库(如Gson或Jackson)来解析JSON
        // 这里简化处理,直接提取"image"字段的值
        int startIndex = result.indexOf("\"image\":\"") + 9;
        int endIndex = result.indexOf("\"", startIndex);
        return result.substring(startIndex, endIndex);
    }

    // 百度AI平台的凭证信息
    public static final String API_KEY = "68ny2VNI0OXN7YTgnzk8Rqya";
    public static final String SECRET_KEY = "gPJUrulUE9xIBXoPXLB6BMbE6lSw8Kzy";

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            ImageProcessingUI frame = new ImageProcessingUI();
            frame.setVisible(true);
        });
    }
}

  

package org.example;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class TokenUtil {

    private static final String API_KEY = "68ny2VNI0OXN7YTgnzk8Rqya";
    private static final String SECRET_KEY = "gPJUrulUE9xIBXoPXLB6BMbE6lSw8Kzy";

    public static String getAccessToken() throws Exception {
        String requestUrl = "https://aip.baidubce.com/oauth/2.0/token";
        String params = "grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY;
        URL url = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setFixedLengthStreamingMode(params.getBytes().length);
        conn.getOutputStream().write(params.getBytes());

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        // 使用Gson解析JSON响应
        JsonObject jsonResponse = JsonParser.parseString(response.toString()).getAsJsonObject();
        String accessToken = jsonResponse.get("access_token").getAsString();

        return accessToken;
    }

    public static void main(String[] args) throws Exception {

    }
}

  

标签:11.8,String,java,化二,public,result,new,import,图像增强
From: https://www.cnblogs.com/luoqingci/p/18638840

相关文章

  • 11.7 图像增强与动漫化一
    packageorg.example;importorg.json.JSONObject;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.net.URL;importjava.util.logging.Level;importjava.util.loggin......
  • 11.8
    晨曦初露,新的一周又开始了。今天的课程从软件设计拉开序幕,复杂的系统架构和设计流程让我有些应接不暇,那些密密麻麻的线条和模块仿佛是一座迷宫,我在其中努力寻找着出口。紧接着是软件需求分析,用户需求的多样性和不确定性让我深刻体会到这门课的难度,每一个细节都可能影响到整个软件......
  • 哪种空气净化器能有效净化二手烟?净化二手烟最佳的产品推荐!
    被动吸烟,俗称二手烟,其烟雾具有极高的附着性,能轻易附着在衣物和皮肤上,并被带入室内空间。在户外,吸烟者边走边抽的现象也不少见,导致二手烟随风传播,危害范围随之扩大。值得注意的是,二手烟内含超过4000种有害化学物质及数十种可能致癌的物质,诸如焦油、氨、尼古丁等。长期置身于二......
  • 哪种空气净化器能净化二手烟?除二手烟最好的空气净化器推荐
    越来越多的人开始深刻认识到吸烟所带来的巨大危害,而二手烟问题更是日益显著。尽管吸烟现象依旧普遍,但二手烟的无处不在及其对我们健康的潜在威胁,已引起广泛重视。它不仅能附着在头发、衣物和皮肤上,更时刻威胁着我们的身体健康。烟草燃烧时释放的烟雾中含有上百种有害物质,对于免......
  • 11.8
    用计算机测量时间要想在计算机上制作一个时钟需要一个周期性的振动源——最好有很好的精确性和正确性——以及一种让软件获取振动源的时标的方法。要想专门为了计时而制造一台计算机是很容易的。不过,多数现在流行的计算机体系结构在设计时都没有考虑过要提供很好的时钟。我将会结......
  • yolov8+图像去雨+图像去雾+图像增强+图像去噪
    YOLOv8图像去雾、图像去雨、图像增强与图像去噪:综合解决方案引言随着计算机视觉技术的不断进步,YOLO(YouOnlyLookOnce)系列模型以其快速和高效的目标检测能力而闻名。最新版本YOLOv8不仅继承了这些优点,还引入了图像处理的新功能,如图像去雾、图像去雨、图像增强和图像去噪......
  • 12.7百度图像增强与特效SDK实验
    实验二名称:百度图像增强与特效SDK实验(2024.11.22日完成)一、实验要求  任务一:下载配置百度图像增强与特效的Java相关库及环境(占10%)。    任务二:了解百度图像增强与特效相关功能并进行总结(占20%)。    任务三:完成图像增强GUI相关功能代码并测试调用,要求上传自己的模糊......
  • 【图像处理】用Python和OpenCV实现简单的图像增强与特征提取
    《PythonOpenCV从菜鸟到高手》带你进入图像处理与计算机视觉的大门!图像处理是计算机视觉领域的重要基础,而图像增强和特征提取是其中的关键技术。本文将详细探讨如何使用Python和OpenCV实现图像增强与特征提取。通过具体示例,我们将介绍滤波、直方图均衡化、边缘检测、......
  • 11.8日报
    背了些单词,之后进行了人机交互的实验,完成了添加人员模块:以下为今日完成部分代码:namespacetest1{partialclassaddmanForm{///<summary>///Requireddesignervariable.///</summary>privateSystem.ComponentModel.IConta......
  • 图像数据增强库综述:10个强大图像增强工具对比与分析
    在深度学习和计算机视觉领域,数据增强已成为提高模型性能和泛化能力的关键技术。本文旨在全面介绍当前广泛使用的图像数据增强库,分析其特点和适用场景,以辅助研究人员和开发者选择最适合其需求的工具。数据增强的重要性数据增强在深度学习模型训练中扮演着至关重要的角色,其......