2018년 7월 8일 일요일

[Java] Image Processing with ImageJ


Download: ij152.zip


1. Image Create and Save
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public static void createJpegImage(int width, int height) {
    ImagePlus imp = IJ.createImage("created.jpg", "jpg", width, height, 32);
    ImageProcessor ip = imp.getProcessor();
    ip.setColor(Color.BLUE);
    ip.setLineWidth(4);
    ip.drawRect(10, 10, imp.getWidth() - 20, imp.getHeight() - 20); 
    IJ.save(imp, "D:/created.jpg");
    /* extension: 
     * ".tif", ".jpg", ".gif", ".zip", ".raw", ".avi", ".bmp",
     * ".fits", ".pgm", ".png", ".lut", ".roi", ".txt"
     */
    //imp.show();
}

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public static void createJpegImage2(int width, int height) {
    ImagePlus imp = IJ.createImage("created.jpg", "jpg", width, height, 32);
    ImageProcessor ip = imp.getProcessor();
    ip.setColor(Color.BLUE);
    ip.setLineWidth(4);
    ip.drawRect(10, 10, imp.getWidth() - 20, imp.getHeight() - 20); 
    IJ.saveAs(imp, "jpeg","D:/created.jpg");
    /* type:
     * "tiff", "jpeg", "gif", "zip", "raw", "avi", "bmp", "fits", "pgm", 
     * "png", "text image", "lut", "text"
     */
}


Output: D:\created.jpg



2. Image Load and Convert To Gray Scale
1
2
3
4
5
6
7
public static void convertToGray() {
    ImagePlus ip = IJ.openImage("D:/lena.png");
    ImageConverter ic = new ImageConverter(ip);
    FileSaver fs = new FileSaver(ip);
    ic.convertToGray8();
    fs.saveAsJpeg("D:/lena_gray.jpg");
}

Input: lena.png


Output: lena_gray.jpg



3. Image Convert to Jpeg
1
2
3
4
5
6
7
public static void convertToJpeg(int quality) {
    ImagePlus ip = IJ.openImage("D:/lena.png");
    FileSaver fs = new FileSaver(ip);
    FileSaver.setJpegQuality(quality);
    FileSaver.getJpegQuality();
    fs.saveAsJpeg("D:/lena.jpg");
}


4. Image Resize

4.1 ImagResize by Width (with the aspect ratio maintained)
1
2
3
4
5
6
7
8
public static void resizeImage() {
    ImagePlus imp = IJ.openImage("D:/lena.png");
    ImageProcessor ip = imp.getProcessor();
    ip = ip.resize(imp.getWidth()/2);
    imp.setProcessor(ip);
    FileSaver fs = new FileSaver(imp);
    fs.saveAsPng("D:/lena_half.png");
}


4.2 Image Resize by Width and Height
1
2
3
4
5
6
7
public static void resizeImage2() {
    ImagePlus imp = IJ.openImage("D:/lena.png");
    ImageProcessor ip = imp.getProcessor();
    ip = ip.resize(imp.getWidth(),imp.getHeight()/2);
    imp.setProcessor(ip);
    IJ.save(imp,"D:/lena_resized.png");
}

Output: lena_resized.png



4.3 Image Rescale
1
2
3
4
5
6
public static void rescaleImage() {
    ImagePlus imp = IJ.openImage("D:/lena.png");
    ImageProcessor ip = imp.getProcessor();
    ip.scale(1.0,0.5); //xScale, yScale
    IJ.save(imp,"D:/lena_rescaled.png");
}

Output: lena_rescaled.png (image size is not changed)



5. Image Crop
1
2
3
4
5
6
7
8
9
public static void cropImage() {
    ImagePlus imp = IJ.openImage("D:/lena.png");
    ImageProcessor ip = imp.getProcessor();
    ip.setRoi(0, 0, imp.getWidth()/2, imp.getHeight()/2); //x, y, w, h
    ip = ip.crop();
    imp.setProcessor(ip);
    FileSaver fs = new FileSaver(imp);
    fs.saveAsPng("D:/lena_crop.png");
}

Output: lena_crop.jpg



6. Image Smooth
1
2
3
4
5
6
7
public static void smoothImage() {
    ImagePlus imp = IJ.openImage("D:/lena.png");
    for( int i=0; i < 10; i++ ) 
        imp.getProcessor().smooth();
    FileSaver fs = new FileSaver(imp);
    fs.saveAsPng("D:/lena_smooth.png");
}

Input: lena.png


Output: lena_smooth.png




7. Image Rotate

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public static void rotateImage() {
    ImagePlus imp = IJ.openImage("D:/lena.png");
    ImageProcessor ip = imp.getProcessor();
    ImageProcessor ip_left = ip.rotateLeft();
    ImageProcessor ip_right = ip.rotateRight();
    imp.setProcessor(ip_left);
    IJ.save(imp,"D:/lena_left.png");
    imp.setProcessor(ip_right);
    IJ.save(imp,"D:/lena_right.png");
    ip.rotate(45);
    imp.setProcessor(ip);
    IJ.save(imp,"D:/lena_rotated.png");
}


Input: lena.png


Output: lena_left.png


Output: lena_right.png


Output: lena_rotated.png




8. Image Overlay
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public static void overlayImage() {
    
    ImagePlus imp = new ImagePlus("D:/lena.png");
    BufferedImage bi = imp.getBufferedImage();
    
    ImagePlus imp2 = imp.duplicate();
    imp2.setProcessor(imp2.getProcessor().resize(imp2.getWidth()/2));
    new ImageConverter(imp2).convertToGray8();
    BufferedImage bi2 = imp2.getBufferedImage();
    
    Graphics2D g = bi.createGraphics();
    g.drawImage(bi2, 0, 0, null);
    ImagePlus imp3 = new ImagePlus("combined", bi);
    FileSaver fs = new FileSaver(imp3);
    fs.saveAsJpeg("D:/lena_overlay.jpg");       
}


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public static void overlayImage2() {
    
    ImagePlus imp = new ImagePlus("D:/lena.png");
    BufferedImage bi = imp.getBufferedImage();
    
    ImagePlus imp2 = imp.duplicate();
    imp2.setProcessor(imp2.getProcessor().resize(imp2.getWidth()/2));
    new ImageConverter(imp2).convertToGray8();
    BufferedImage bi2 = imp2.getBufferedImage();

    BufferedImage combined = new BufferedImage(imp.getWidth(), imp.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = combined.createGraphics();
    g.drawImage(bi, 0, 0, null);
    g.drawImage(bi2, 0, 0, null);
    ImagePlus imp3 = new ImagePlus("combined", combined);
    FileSaver fs = new FileSaver(imp3);
    fs.saveAsJpeg("D:/lena_overlay2.jpg");       
}


Input: lena.png

output: lena_overlay.png




9. Image Partial Edit
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public static void grayPartialImage() {
    ImagePlus imp = new ImagePlus("D:/lena.png");
    ImageProcessor ip = imp.getProcessor();
    BufferedImage bufferedImage = imp.getBufferedImage();
    for(int y=0; y < bufferedImage.getHeight()/2; y++) {
        for(int x=0; x < bufferedImage.getWidth()/2; x++) {
            Color color = new Color(bufferedImage.getRGB(x, y));
            int grayLevel = (color.getRed() + color.getGreen() + color.getBlue()) / 3;
            int r = grayLevel;
            int g = grayLevel;
            int b = grayLevel;
            int rgb = (r << 16) | (g << 8) | b;
            bufferedImage.setRGB(x, y, rgb);
        }
    }
    ImagePlus grayImg = new ImagePlus("gray", bufferedImage);
    FileSaver fs = new FileSaver(grayImg);
    fs.saveAsJpeg("D:/lena_partial.jpg");       
}

Output:: lena_partial.jpg





1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public static void clearPartialImage() {
    ImagePlus imp = new ImagePlus("D:/lena.png");
    ImageProcessor ip = imp.getProcessor();
    BufferedImage bufferedImage = imp.getBufferedImage();
    for(int y=0; y < bufferedImage.getHeight()/2; y++) {
        for(int x=0; x < bufferedImage.getWidth()/2; x++) {
            int rgb = 0x00ffffff;
            bufferedImage.setRGB(x, y, rgb);
        }
    }
    ImagePlus grayImg = new ImagePlus("gray", bufferedImage);
    FileSaver fs = new FileSaver(grayImg);
    fs.saveAsJpeg("D:/lena_white.jpg");       
}

Output: lena_white.jpg












2018년 6월 27일 수요일

[Java] HTTP Server Examples


Download:

jetty-distribution-9.4.11.v20180605.zip

jetty-http-9.4.11.v20180605.jar
jetty-io-9.4.11.v20180605.jar
jetty-server-9.4.11.v20180605.jar
jetty-servlet-9.4.11.v20180605.jar
jetty-util-9.4.11.v20180605.jar
servlet-api-3.1.jar

1. Simple HTTP File Server
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package web;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;

public class HttpServer {

    Server server;

    public HttpServer() throws Exception {
    }
        
    void stop() throws Exception {
        server.stop();
    }

    void startDirList() throws Exception {
        server = new Server(8070);
        ResourceHandler resource_handler = new ResourceHandler();
        resource_handler.setDirectoriesListed(true);
        resource_handler.setWelcomeFiles(new String[]{ "index.html" });
        resource_handler.setResourceBase("D:\\");

        HandlerList handlers = new HandlerList();
        handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
        server.setHandler(handlers);

        server.start();
        server.join();
    }

    public static void testDirList() throws Exception {
        HttpServer http = new HttpServer();
        new Thread( () -> {
            for( int i = 0; i < 10; i++ ) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                http.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        http.startDirList();        
    }    

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

2. HTTP Server with Handler

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;

public class HttpServer {

    Server server;

    public HttpServer() throws Exception {
    }
        
    void stop() throws Exception {
        server.stop();
    }

    @SuppressWarnings("serial")
    public static class HelloServlet extends HttpServlet {
        @Override
        protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
            response.setContentType("text/html");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().println("<h1>Hello from HelloServlet</h1>");
        }
    }
    
    void startServlet() throws Exception {
        Server server = new Server(8080);
        ServletHandler handler = new ServletHandler();
        server.setHandler(handler);
        handler.addServletWithMapping(HelloServlet.class, "/*");

        server.start();
        server.join();
    }

    public static void testServlet() throws Exception {
        HttpServer http = new HttpServer();
        http.startServlet();        
    }    

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



2018년 6월 26일 화요일

[Python] Matplotlib


1. Plot Examples


1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#import matplotlib.pyplot as plt
#plt.show()
#plt.savefig('a.png')

def line_plot():
 from numpy import sin
 from matplotlib import pyplot
 x = [x*0.1 for x in range(100)]
 y = sin(x)
 pyplot.plot(x, y)
 pyplot.show()

def bar_chart():
 from random import seed
 from random import randint
 from matplotlib import pyplot
 seed(1)
 x = ['red', 'green', 'blue']
 y = [randint(0, 100), randint(0, 100), randint(0, 100)]
 pyplot.bar(x, y)
 pyplot.show()

def histogram_plot():
 from numpy.random import seed
 from numpy.random import randn
 from matplotlib import pyplot
 seed(1)
 x = randn(1000)
 pyplot.hist(x) #, bins=100)
 pyplot.show()

def scatter_plot():
 from numpy.random import seed
 from numpy.random import randn
 from matplotlib import pyplot
 seed(1)
 x = 20 * randn(1000) + 100
 y = x + (10 * randn(1000) + 50)
 pyplot.scatter(x, y)
 pyplot.show()

def box_whisker_plot(): 
 from numpy.random import seed
 from numpy.random import randn
 from matplotlib import pyplot
 seed(1)
 x = [randn(1000), 5 * randn(1000), 10 * randn(1000)]
 pyplot.boxplot(x)
 pyplot.show()

def pandas_plot():
 import matplotlib.pyplot as plt
 import pandas
 url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv"
 names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
 data = pandas.read_csv(url, names=names)
 data.hist()
 plt.show()
 data.plot(kind='density', subplots=True, layout=(3,3), sharex=False)
 plt.show()
 data.plot(kind='box', subplots=True, layout=(3,3), sharex=False, sharey=False)
 plt.show() 
 data1 = data[data.columns[2:4]]
 data1.plot()
 plt.show()
 data1.plot(kind='density')
 plt.show()
 data1 = data.loc[:,'pres':'mass']
 data1.plot(kind='density')
 plt.show()

def pandas_random():
 import pandas as pd
 import numpy as np
 np.random.seed(5)
 df = pd.DataFrame(np.random.randint(100, size=(100, 6)), 
       columns=list('ABCDEF'), 
       index=['R{}'.format(i) for i in range(100)])
 print(df)
 print(df.head())
 print(df[['C','E']].head())
 print(df[df.columns[2:4]].head())
 print(df.loc[:,df.columns.isin(list('ACE'))].head())
 print(df.loc['R6':'R10','C':'E'])
 print(df.iloc[2:6,2:5])
 print(df.iloc[0:6,0:2].copy())
 print(pd.DataFrame(df,columns=['B','E']).head())
 print(df.drop(['A','C'],axis=1).head())

def time_series_line_plot():
 from pandas import Series
 from matplotlib import pyplot
 series = Series.from_csv('daily-minimum-temperatures-in-me.csv', header=0)
 print(series.head())
 #series = series.astype(float)
 series.plot()
 pyplot.show()
 
def time_series_group_line_plot():
 from pandas import DataFrame
 from pandas import TimeGrouper
 from pandas import Series
 from matplotlib import pyplot
 series = Series.from_csv('daily-minimum-temperatures-in-me.csv', header=0)
 groups = series.groupby(TimeGrouper('A'))
 years = DataFrame()
 for name, group in groups:
  years[name.year] = group.values
 years.plot(subplots=True, legend=False)
 pyplot.show()
 
if __name__ == "__main__":
 #line_plot()
 #bar_chart()
 #histogram_plot()
 #scatter_plot()
 #box_whisker_plot()
 #time_series_line_plot()
 #time_series_group_line_plot()
 #pandas_plot()
 pandas_random()



[Python] pip install


1. pip install in proxy environment (pip_install.bat)
1
2
3
4
python -m pip install --proxy=192.168.0.1:8080 \
  --trusted-host pypi.org \ 
  --trusted-host pypi.python.org \
  --trusted-host files.pythonhosted.org %1


2. environment variables (env.bat)
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
rem PROMPT=$P$G
rem @set PATH=%~dp0bin;
@echo.
@echo Setting up environment for using MinGW with GCC from %~dp0.

@set BUILD_HOME=C:\Dev
@set PYTHONHOME=%BUILD_HOME%\Anaconda3
@set PYTHONPATH=%PYTHONHOME%\Lib
@set MINGW_HOME=%BUILD_HOME%\mingw32
@set JAVA_HOME=%BUILD_HOME%\jdk1.8.0_152
@set GROOVY_HOME=%BUILD_HOME%\groovy-3.0.0
@set GRAPHVIZ_HOME=%BUILD_HOME%\graphviz-2.38

@set PATH=%MINGW_HOME%/bin;%PATH%
@set PATH=%PYTHONHOME%;%PYTHONHOME%\Scripts;%PATH%
@set PATH=%JAVA_HOME%/bin;%PATH%
@set PATH=%GROOVY_HOME%/bin;%PATH%
@set PATH=%GRAPHVIZ_HOME%/bin;%PATH%
cmd.exe


3. spyder

runspyder.py

from spyder.app import start
start.main()

runspyder.bat

@echo off
@set BUILD_HOME=C:\ProgramData
@set PYTHONHOME=%BUILD_HOME%\Anaconda3
@set PYTHONPATH=%PYTHONHOME%\Lib
@set PATH=%PYTHONHOME%;%PYTHONHOME%\Scripts;%PATH%
@start python runspyder.py






2018년 6월 17일 일요일

[Python] Pandas


import pandas

1. Load DataFrame from CSV File without header
1
2
3
4
5
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = pandas.read_csv(url, names=names)
array = dataframe.values
X = array[:,0:len(array[0])-1]
Y = array[:,len(array[0])-1]


2. Load DataFrame from CSV File with header
1
2
3
4
dataframe = pandas.read_csv(url)
array = dataframe.values
X = array[:,0:len(array[0])-1]
Y = array[:,len(array[0])-1]


3 Make Dataframe with Random Numbers
1
2
3
df = pd.DataFrame(np.random.randint(100, size=(100, 6)),
 columns=list('ABCDEF'),
 index=['R{}'.format(i) for i in range(100)])


4. Data Handling with Pandas
1
 2
 3
 4
 5
 6
 7
 8
 9
10
print(df)
print(df.head())
print(df[['C','E']].head())
print(df[df.columns[2:4]].head())
print(df.loc[:,df.columns.isin(list('ACE'))].head())
print(df.loc['R6':'R10','C':'E'])
print(df.iloc[2:6,2:5])
print(df.iloc[0:6,0:2].copy())
print(pd.DataFrame(df,columns=['B','E']).head())
print(df.drop(['A','C'],axis=1).head())


5 Save DataFrame to CSV File (1)
1
df.to_csv(output_file_path, sep=',', index=False)


6. Save DataFrame to CSV File (2)

1
2
3
4
5
with open(out_file, 'w', newline='\n' ) as csv_file: #windows only(newline='\n')
 w = csv.writer( csv_file ) #, quoting=csv.QUOTE_ALL) #lineterminator='\n'
 w.writerow(titles)
 for line in lines:
  w.writerow(line)