一个JAVA图形缩放处理工具类

Java图形图像处理【基础篇】【图像缩放】【三】 Java图形图像处理基础介绍了Image和ImageIcon两个核心类。Image是AWT中的抽象类,用于图像操作但不直接显示;ImageIcon是Swing组件,便于在GUI中显示图像。文章通过两个示例程序演示了图像绘制:DrawImageC展示了图像加载、绘制和拷贝操作;WeiQiFrm实现了一个围棋棋盘绘制程序,综合运用了图形绘制、图像加载和组件布局等技术。关键点包括:Image与ImageIcon的相互转换、相对路径处理、图像缩放以及复杂图形界面的构建方法。这些是Java图形编程的基础技术。 阅读详情
 调用的例子
  1. import java.io.FileOutputStream;
  2. import java.io.IOException;

  3. import javax.imageio.ImageIO;

  4. public class T {
  5.   public static void main(String[] args) throws Exception, IOException {
  6.     ImageIO.write(ImageUtils.resizeImage("d:/www.java2000.net.gif", ImageUtils.IMAGE_GIF, 30, 20),
  7.         "JPEG", new FileOutputStream("d:/test.jpg"));
  8.   }
  9. }

源代码,如果你复制源代码不方便,来这里: http://www.java2000.net/p10821
  1. import java.awt.Dimension;
  2. import java.awt.Image;
  3. import java.awt.image.BufferedImage;
  4. import java.awt.image.PixelGrabber;
  5. import java.io.File;
  6. import java.io.IOException;
  7. import java.util.Iterator;
  8. import java.util.Locale;
  9. import javax.imageio.IIOImage;
  10. import javax.imageio.ImageIO;
  11. import javax.imageio.ImageWriteParam;
  12. import javax.imageio.ImageWriter;
  13. import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
  14. import javax.imageio.stream.ImageOutputStream;
  15. public class ImageUtils {
  16.   public static final int IMAGE_UNKNOWN = -1;
  17.   public static final int IMAGE_JPEG = 0;
  18.   public static final int IMAGE_PNG = 1;
  19.   public static final int IMAGE_GIF = 2;
  20.   /**
  21.    * Resizes an image
  22.    * 
  23.    * @param imgName
  24.    *          The image name to resize. Must be the complet path to the file
  25.    * @param type
  26.    *          int
  27.    * @param maxWidth
  28.    *          The image's max width
  29.    * @param maxHeight
  30.    *          The image's max height
  31.    * @return A resized <code>BufferedImage</code>
  32.    */
  33.   public static BufferedImage resizeImage(String imgName, int type, int maxWidth, int maxHeight) {
  34.     try {
  35.       return resizeImage(ImageIO.read(new File(imgName)), type, maxWidth, maxHeight);
  36.     } catch (IOException e) {
  37.       e.printStackTrace();
  38.       return null;
  39.     }
  40.   }
  41.   /**
  42.    * Resizes an image.
  43.    * 
  44.    * @param image
  45.    *          The image to resize
  46.    * @param maxWidth
  47.    *          The image's max width
  48.    * @param maxHeight
  49.    *          The image's max height
  50.    * @return A resized <code>BufferedImage</code>
  51.    * @param type
  52.    *          int
  53.    */
  54.   public static BufferedImage resizeImage(BufferedImage image, int type, int maxWidth, int maxHeight) {
  55.     Dimension largestDimension = new Dimension(maxWidth, maxHeight);
  56.     // Original size
  57.     int imageWidth = image.getWidth(null);
  58.     int imageHeight = image.getHeight(null);
  59.     float aspectRatio = (float) imageWidth / imageHeight;
  60.     if (imageWidth > maxWidth || imageHeight > maxHeight) {
  61.       if ((float) largestDimension.width / largestDimension.height > aspectRatio) {
  62.         largestDimension.width = (int) Math.ceil(largestDimension.height * aspectRatio);
  63.       } else {
  64.         largestDimension.height = (int) Math.ceil(largestDimension.width / aspectRatio);
  65.       }
  66.       imageWidth = largestDimension.width;
  67.       imageHeight = largestDimension.height;
  68.     }
  69.     return createHeadlessSmoothBufferedImage(image, type, imageWidth, imageHeight);
  70.   }
  71.   /**
  72.    * Saves an image to the disk.
  73.    * 
  74.    * @param image
  75.    *          The image to save
  76.    * @param toFileName
  77.    *          The filename to use
  78.    * @param type
  79.    *          The image type. Use <code>ImageUtils.IMAGE_JPEG</code> to save as
  80.    *          JPEG images, or <code>ImageUtils.IMAGE_PNG</code> to save as PNG.
  81.    * @return <code>false</code> if no appropriate writer is found
  82.    */
  83.   public static boolean saveImage(BufferedImage image, String toFileName, int type) {
  84.     try {
  85.       return ImageIO.write(image, type == IMAGE_JPEG ? "jpg" : "png", new File(toFileName));
  86.     } catch (IOException e) {
  87.       e.printStackTrace();
  88.       return false;
  89.     }
  90.   }
  91.   /**
  92.    * Compress and save an image to the disk. Currently this method only supports
  93.    * JPEG images.
  94.    * 
  95.    * @param image
  96.    *          The image to save
  97.    * @param toFileName
  98.    *          The filename to use
  99.    * @param type
  100.    *          The image type. Use <code>ImageUtils.IMAGE_JPEG</code> to save as
  101.    *          JPEG images, or <code>ImageUtils.IMAGE_PNG</code> to save as PNG.
  102.    */
  103.   public static void saveCompressedImage(BufferedImage image, String toFileName, int type) {
  104.     try {
  105.       if (type == IMAGE_PNG) {
  106.         throw new UnsupportedOperationException("PNG compression not implemented");
  107.       }
  108.       Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
  109.       ImageWriter writer;
  110.       writer = (ImageWriter) iter.next();
  111.       ImageOutputStream ios = ImageIO.createImageOutputStream(new File(toFileName));
  112.       writer.setOutput(ios);
  113.       ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault());
  114.       iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
  115.       iwparam.setCompressionQuality(0.7F);
  116.       writer.write(null, new IIOImage(image, null, null), iwparam);
  117.       ios.flush();
  118.       writer.dispose();
  119.       ios.close();
  120.     } catch (IOException e) {
  121.       e.printStackTrace();
  122.     }
  123.   }
  124.   /**
  125.    * Creates a <code>BufferedImage</code> from an <code>Image</code>. This
  126.    * method can function on a completely headless system. This especially
  127.    * includes Linux and Unix systems that do not have the X11 libraries
  128.    * installed, which are required for the AWT subsystem to operate. This method
  129.    * uses nearest neighbor approximation, so it's quite fast. Unfortunately, the
  130.    * result is nowhere near as nice looking as the
  131.    * createHeadlessSmoothBufferedImage method.
  132.    * 
  133.    * @param image
  134.    *          The image to convert
  135.    * @param w
  136.    *          The desired image width
  137.    * @param h
  138.    *          The desired image height
  139.    * @return The converted image
  140.    * @param type
  141.    *          int
  142.    */
  143.   public static BufferedImage createHeadlessBufferedImage(BufferedImage image, int type, int width,
  144.       int height) {
  145.     if (type == ImageUtils.IMAGE_PNG && hasAlpha(image)) {
  146.       type = BufferedImage.TYPE_INT_ARGB;
  147.     } else {
  148.       type = BufferedImage.TYPE_INT_RGB;
  149.     }
  150.     BufferedImage bi = new BufferedImage(width, height, type);
  151.     for (int y = 0; y < height; y++) {
  152.       for (int x = 0; x < width; x++) {
  153.         bi.setRGB(x, y, image.getRGB(x * image.getWidth() / width, y * image.getHeight() / height));
  154.       }
  155.     }
  156.     return bi;
  157.   }
  158.   /**
  159.    * Creates a <code>BufferedImage</code> from an <code>Image</code>. This
  160.    * method can function on a completely headless system. This especially
  161.    * includes Linux and Unix systems that do not have the X11 libraries
  162.    * installed, which are required for the AWT subsystem to operate. The
  163.    * resulting image will be smoothly scaled using bilinear filtering.
  164.    * 
  165.    * @param source
  166.    *          The image to convert
  167.    * @param w
  168.    *          The desired image width
  169.    * @param h
  170.    *          The desired image height
  171.    * @return The converted image
  172.    * @param type
  173.    *          int
  174.    */
  175.   public static BufferedImage createHeadlessSmoothBufferedImage(BufferedImage source, int type,
  176.       int width, int height) {
  177.     if (type == ImageUtils.IMAGE_PNG && hasAlpha(source)) {
  178.       type = BufferedImage.TYPE_INT_ARGB;
  179.     } else {
  180.       type = BufferedImage.TYPE_INT_RGB;
  181.     }
  182.     BufferedImage dest = new BufferedImage(width, height, type);
  183.     int sourcex;
  184.     int sourcey;
  185.     double scalex = (double) width / source.getWidth();
  186.     double scaley = (double) height / source.getHeight();
  187.     int x1;
  188.     int y1;
  189.     double xdiff;
  190.     double ydiff;
  191.     int rgb;
  192.     int rgb1;
  193.     int rgb2;
  194.     for (int y = 0; y < height; y++) {
  195.       sourcey = y * source.getHeight() / dest.getHeight();
  196.       ydiff = scale(y, scaley) - sourcey;
  197.       for (int x = 0; x < width; x++) {
  198.         sourcex = x * source.getWidth() / dest.getWidth();
  199.         xdiff = scale(x, scalex) - sourcex;
  200.         x1 = Math.min(source.getWidth() - 1, sourcex + 1);
  201.         y1 = Math.min(source.getHeight() - 1, sourcey + 1);
  202.         rgb1 = getRGBInterpolation(source.getRGB(sourcex, sourcey), source.getRGB(x1, sourcey),
  203.             xdiff);
  204.         rgb2 = getRGBInterpolation(source.getRGB(sourcex, y1), source.getRGB(x1, y1), xdiff);
  205.         rgb = getRGBInterpolation(rgb1, rgb2, ydiff);
  206.         dest.setRGB(x, y, rgb);
  207.       }
  208.     }
  209.     return dest;
  210.   }
  211.   private static double scale(int point, double scale) {
  212.     return point / scale;
  213.   }
  214.   private static int getRGBInterpolation(int value1, int value2, double distance) {
  215.     int alpha1 = (value1 & 0xFF000000) >>> 24;
  216.     int red1 = (value1 & 0x00FF0000) >> 16;
  217.     int green1 = (value1 & 0x0000FF00) >> 8;
  218.     int blue1 = (value1 & 0x000000FF);
  219.     int alpha2 = (value2 & 0xFF000000) >>> 24;
  220.     int red2 = (value2 & 0x00FF0000) >> 16;
  221.     int green2 = (value2 & 0x0000FF00) >> 8;
  222.     int blue2 = (value2 & 0x000000FF);
  223.     int rgb = ((int) (alpha1 * (1.0 - distance) + alpha2 * distance) << 24)
  224.         | ((int) (red1 * (1.0 - distance) + red2 * distance) << 16)
  225.         | ((int) (green1 * (1.0 - distance) + green2 * distance) << 8)
  226.         | (int) (blue1 * (1.0 - distance) + blue2 * distance);
  227.     return rgb;
  228.   }
  229.   /**
  230.    * Determines if the image has transparent pixels.
  231.    * 
  232.    * @param image
  233.    *          The image to check for transparent pixel.s
  234.    * @return <code>true</code> of <code>false</code>, according to the result
  235.    */
  236.   public static boolean hasAlpha(Image image) {
  237.     try {
  238.       PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
  239.       pg.grabPixels();
  240.       return pg.getColorModel().hasAlpha();
  241.     } catch (InterruptedException e) {
  242.       return false;
  243.     }
  244.   }
  245. }

java 使用ImageIO.writer从BufferedImage生成jpeg图像遇到问题总结及解决 主要介绍了java 使用ImageIO.writer从BufferedImage生成jpeg图像遇到问题总结及解决的相关资料,需要的朋友可以参考下 立即下载

相关推荐

科研党必备:5分钟搞定MATLAB闪退问题(含R2020a-R2023b各版本适配)

本文针对科研人员常见的MATLAB闪退问题,提供了从R2020a到R2023b各版本的适配解决方案。通过分析六大诱因和版本定制化修复方法,帮助用户快速诊断和解决闪退问题,包括内存优化、高级调试和预防性维护等实用技巧,确保科研计算的连续性和稳定性。

t1u2v的博客 1968

JDK1.7 ImageIO的一个梗

上个星期我的leader就要我看 这个东西了,由于一个星期都在做项目上的东西,没时间看,今天终于把那个事情完结了。。 来脑补一下这个事情: 他们项目组的JDK原来是JDK1.6,现在要用JDK1.7,然后呢,图像处理这一块有点问题。 JDK1.7将encoder,decoder类删除掉了,所以呢代码就有问题了,就要我帮助他们改一改。 今天终于好了! 言归正传,了解下JDK1.7和JDK1

ps_cd_sc的博客 728

如何在 Windows 11 上安装 ChatGPT:CMD + 图形界面两种方式

我没说在 Windows 11 上装 ChatGPT 应用有多难,但你要是知道有哪几种官方途径可用,事情就会顺一点,尤其是对新手。对大多数用户来说,商店应用就是正确的选择。如果你在受管理的设备上,或者想避开商店,那么通过 Edge 或 Chrome 装 PWA 是完全站得住脚的替代方案。不管你选哪条路,真正的收获都是把 ChatGPT 从浏览器标签页里挪出来,放进一个它真正像个工具的地方。把它固定到任务栏、配好 Alt + 空格,你就会纳闷以前没它是怎么干活的。

山岚的运维笔记 302

java 缩放图片

import java.awt.Image; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder...

Davie's Happy Life 1974

基于YOLO+DeepSeek的农作物病虫害检测系统

本系统是一个基于YOLO+DeepSeek的农作物病虫害检测系统。 可使用YOLOV1-YOLOV12的任意模型进行目标检测。可以实现检测图片、批量检测图片、视频检测、摄像头检测四种方式。

qq_51977316的博客 1810

别再手动填序号了!用Python脚本在Arcgis属性表里实现分组自动编号(附完整代码)

本文详细介绍了如何利用Python脚本在Arcgis属性表中实现分组自动编号,告别低效的手工操作。通过核心代码解析和实战教程,帮助GIS工程师快速掌握自动化编号技术,提升工作效率并降低错误率。特别适合城市规划、国土调查等需要处理大量分组数据的场景。

weixin_42532473的博客 309

java:SWT 缩放图像(Image)

在SWT中下面两个方法都可以实现Image缩放, GC.drawImage(Image image, int srcX, int srcY, int srcWidth, int srcHeight, int dstX, int dstY, int dstWidth, int dstHeight); ImageData.scaledTo(int width, int height) 但是为了

10km的专栏 4822

RK3568 OpenHarmony3.2 蓝牙模块AP6275S适配(已更新)

OpenHarmony3.2 Release版默认是适配AP6275s这款蓝牙芯片的,但是打开蓝牙,发现无法扫描到设备、连接设备。目前平台soc为RK3568,根据项目要求,自定义外设。接下来将以解决bug为目的,学习和记录OpenHarmony平台下蓝牙模块的适配流程。RK809 CLK:32.768KHzUART1M1:与蓝牙模块通讯的串口:GPIO4_B6:GPIO4_A5WAKE_GPIO:未定义,硬件拉高1.8V: 未定义,悬空主要是打开串口,/dev/ttyS1,得到文件描述符fd。

Martian_Jonas的博客 2250

java图片缩放工具类,一个JAVA图形缩放处置工具类

一个JAVA图形缩放处理工具类调用的例子import java.io.FileOutputStream;import java.io.IOException;import javax.imageio.ImageIO;public class T {public static void main(String[] args) throws Exception, IOException {ImageI...

weixin_30611667的博客 222

2024全国村级行政边界数据

五级行政区划:村边界数据产品涵盖五级行政区划:(一级行政区)省级行政区共31个其中:(台湾、香港、澳门除外);(二级行政区)地级行政区共334个其中:7个地区、3个盟、30个自治州、294个地级市;(三级行政区)县级行政区共2851个其中:1355个县、117个自治县、49个旗、3个自治旗、363个县级市、962个市辖区、1个林区、1个特区;(四级行政区)乡级行政区共40497个其中:11626个乡、1034个民族乡、20117个镇、7566个街道、151个苏木、1个民族苏木、2个县辖区公所;

J_Giser的博客 3234

基于STM32F1XX 、HAL库的BH1745NUC-E2环境光传感器驱动应用C语言程序设计

printf("BH1745制造商ID: 0x%02X\r\n", BH1745_ReadManufacturerID(&hbh1745));#define BH1745_ADDR_HIGH 0x39 // ADDR引脚接VDD。#define BH1745_ADDR_LOW 0x38 // ADDR引脚接地。= 0xE0) // BH1745制造商ID为0xE0。// 清除RGBC测量使能位。printf("BH1745初始化失败\r\n");

PP_Cottage的博客 281

【工具类】——图片缩放

Graphics2D 是 Java 2D API 的核心类,用于在 Java 平台上渲染二维形状、文本和图像。它是 Graphics 类的扩展,提供了更复杂的图形操作功能,包括几何变换、颜色管理、文本布局等。// 替换为实际路径。在java中对于图片的处理一般都是使用Graphics2D�类来实现。// 指定原始图像文件路径和目标尺寸。

给你一半糖 544

基于Xilinx K7-410T的高速DAC之AD9129开发笔记(一)

引言:从本文开始,我们介绍下项目中设计的并行LVDS高速DAC接口设计,包括DAC与FPGA硬件接口设计、软件设计等。项目设计高速DAC采用了ADI公司的AD9129,该芯片最大更新速率5.7Gsps,该芯片在宽带通信应用、LTE、雷达信号产生、干扰机等领域有广泛应用。

FPGA_Designer 2535

java 实现下载的图片压缩_【JAVA秒会技术之玩转图片】图片下载和等比或指定大小压缩快速实现...

package com.netease.test;import java.awt.Color;import java.awt.Graphics2D;import java.awt.Image;import java.awt.RenderingHints;import java.awt.image.BufferedImage;import java.io.BufferedInputStream;im...

weixin_29300931的博客 286

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

java等比压缩图片_【JAVA秒会技术之玩转图片】图片下载和等比或指定大小压缩快速实现...

package com.netease.test;import java.awt.Color;import java.awt.Graphics2D;import java.awt.Image;import java.awt.RenderingHints;import java.awt.image.BufferedImage;import java.io.BufferedInputStream;im...

weixin_32282271的博客 209

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

Java 图片工具类

ImageUtil

qq_44785726的博客 452

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

java常用开发工具类之 图片水印,文字水印,缩放,补白工具类

  import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Image; import java.awt.geom.AffineTransform; import java.awt.i...

weixin_33895516的博客 158

图片剪切工具类

package cn.zh.utils; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotF...

hf312350968的专栏 151

Java图像处理工具类:实现图像缩放

使用Java实现一个简单的图像处理工具类,可完成图像安装一定比例缩放,代码如下: import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOEx...

机器熊的技术大杂烩 728

Java图形库与图形处理

1.背景介绍 Java图形库与图形处理是一种广泛应用的技术,它涉及到计算机图形学、图像处理、计算机视觉等领域。Java图形库与图形处理的核心概念包括图形库、图形处理、图像处理、计算机视觉等。在这篇文章中,我们将深入探讨这些概念,并详细讲解其核心算法原理、具体操作步骤和数学模型公式。 2.核心概念与联系 2.1 图形库 图形库是一种用于存储和管理图形数据的数据结构。图形库可以包含各种类型的图...

AI天才研究院 1647

Java的图片处理工具类

Java的图片处理工具类: 可实现以下常用功能:缩放图像、切割图像、图像类型转换、彩色转黑白、文字水印、图片水印等import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import

by2n的专栏 1426

java处理图片的所有类_Java的图片处理工具类

Java的图片处理工具类: 可实现以下常用功能:缩放图像、切割图像、图像类型转换、彩色转黑白、文字水Java的图片处理工具类:可实现以下常用功能:缩放图像、切割图像、图像类型转换、彩色转黑白、文字水印、图片水印等import java.awt.AlphaComposite;import java.awt.Color;import java.awt.Font;import java.awt.Grap...

weixin_31211703的博客 717

java 图片处理工具类_Java的图片处理工具类

import java.awt.AlphaComposite;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.Image;import java.awt.Toolkit;import java.awt.color.ColorS...

weixin_35141129的博客 262
上一篇: 打印任意尺寸等腰和等边三角形
下一篇: 对Tomcat和Eclipse整合使用的朋友一点建议
老紫竹
博客等级 码龄19年 1万+粉丝 1252原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值