0% found this document useful (0 votes)
543 views17 pages

Implementasi Filter (Sharpen, Gaussian Blur, Median) Image Dengan Java

Implementasi dari 3 (Sharpen, Gaussian Blur, Median) filter pada 3 buah gambar dengan menggunakan java. berisi source code yang siap pakai untuk melakukan filter pada gambar.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
543 views17 pages

Implementasi Filter (Sharpen, Gaussian Blur, Median) Image Dengan Java

Implementasi dari 3 (Sharpen, Gaussian Blur, Median) filter pada 3 buah gambar dengan menggunakan java. berisi source code yang siap pakai untuk melakukan filter pada gambar.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Pengolahan Citra Digital

Implementasi Filter Image

Oleh :
Anggit Prayogo (1411502493)

Program Studi Ilmu Komputer


Jurusan Ilmu Komputer dan Elektronika
Fakultas Matematika dan Ilmu Pengetahuan Alam
Universitas Gadjah Mada
Yogyakarta
2016
BAHASA

: JAVA

Source Code Gaussian Filter Image


import java.awt.image.*;
import java.awt.*;
import java.io.*;
import java.net.URL;
import javax.imageio.ImageIO;
import java.util.Arrays;
import javax.swing.*;
import javax.swing.event.*;

public class GaussianBlurFilter extends JFrame {


private BlurTestPanel blurTestPanel;
private JSlider radiusSlider;
private JCheckBox fasterBlurCheck;
public GaussianBlurFilter() {
super("Gaussian Blur Filter");
blurTestPanel = new BlurTestPanel();
add(blurTestPanel);
radiusSlider = new JSlider(1, 50, 1);
radiusSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
blurTestPanel.setRadius(radiusSlider.getValue());
}
});
fasterBlurCheck = new JCheckBox("Resize");
fasterBlurCheck.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
blurTestPanel.setFastBlur(fasterBlurCheck.isSelected());
}
});
JPanel controls = new JPanel(new FlowLayout(FlowLayout.LEFT));
controls.add(new JLabel("Radius: 1px"));
controls.add(radiusSlider);
controls.add(new JLabel("50px"));
controls.add(Box.createHorizontalStrut(12));
controls.add(fasterBlurCheck);
add(controls, BorderLayout.SOUTH);

pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static class BlurTestPanel extends JPanel {
private BufferedImage image = null;
private BufferedImage imageA;
private int radius = 1;
private boolean fasterBlur = false;
public BlurTestPanel() {
try {
imageA = GraphicsUtilities.loadCompatibleImage(getClass().getResource("Sapi.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
setOpaque(false);
}
public Dimension getPreferredSize() {
return new Dimension(imageA.getWidth(), imageA.getHeight());
}
protected void paintComponent(Graphics g) {
if (image == null) {
image = new BufferedImage(imageA.getWidth() + 2 * radius,
imageA.getHeight() + 2 * radius,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
g2.drawImage(imageA, radius, radius, null);
g2.dispose();
long start = System.nanoTime();
if (fasterBlur) {
image = changeImageWidth(image, image.getWidth() / 2);
image = getGaussianBlurFilterFilter(radius / 2, true).filter(image, null);
image = getGaussianBlurFilterFilter(radius / 2, false).filter(image, null);
image = changeImageWidth(image, image.getWidth() * 2);
} else {
image = getGaussianBlurFilterFilter(radius, true).filter(image, null);
image = getGaussianBlurFilterFilter(radius, false).filter(image, null);
}
long delay = System.nanoTime() - start;

System.out.println("time = " + (delay / 1000.0f / 1000.0f) + "ms for radius = " + radius);
}
int x = (getWidth() - image.getWidth()) / 2;
int y = (getHeight() - image.getHeight()) / 2;
g.drawImage(image, x, y, null);
}
public void setRadius(int radius) {
this.radius = radius;
image = null;
repaint();
}
private void setFastBlur(boolean fasterBlur) {
this.fasterBlur = fasterBlur;
image = null;
repaint();
}
}
public static BufferedImage changeImageWidth(BufferedImage image, int width) {
float ratio = (float) image.getWidth() / (float) image.getHeight();
int height = (int) (width / ratio);
BufferedImage temp = new BufferedImage(width, height,
image.getType());
Graphics2D g2 = temp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(), null);
g2.dispose();
return temp;
}
public static void printGaussianBlurFilterFilter(int radius) {
if (radius < 1) {
throw new IllegalArgumentException("Radius must be >= 1");
}
int size = radius * 2 + 1;
float[] data = new float[size * size];
float sigma = radius / 3.0f;
float twoSigmaSquare = 2.0f * sigma * sigma;
float sigmaRoot = (float) Math.sqrt(twoSigmaSquare * Math.PI);

float total = 0.0f;


int index = 0;
for (int y = -radius; y <= radius; y++) {
for (int x = -radius; x <= radius; x++) {
float distance = x * x + y * y;
data[index] = (float) Math.exp(-distance / twoSigmaSquare) / sigmaRoot;
total += data[index];
System.out.printf("%.3f\t", data[index]);
index++;
}
System.out.println("");
}
}
public static ConvolveOp getGaussianBlurFilterFilter(int radius,
boolean horizontal) {
if (radius < 1) {
throw new IllegalArgumentException("Radius must be >= 1");
}
int size = radius * 2 + 1;
float[] data = new float[size];
float sigma = radius / 3.0f;
float twoSigmaSquare = 2.0f * sigma * sigma;
float sigmaRoot = (float) Math.sqrt(twoSigmaSquare * Math.PI);
float total = 0.0f;
for (int i = -radius; i <= radius; i++) {
float distance = i * i;
int index = i + radius;
data[index] = (float) Math.exp(-distance / twoSigmaSquare) / sigmaRoot;
total += data[index];
}
for (int i = 0; i < data.length; i++) {
data[i] /= total;
}
Kernel kernel = null;
if (horizontal) {
kernel = new Kernel(size, 1, data);
} else {
kernel = new Kernel(1, size, data);
}
return new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);

}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
printGaussianBlurFilterFilter(3);
new GaussianBlurFilter().setVisible(true);
}
});
}
}

class GraphicsUtilities {
private GraphicsUtilities() {
}
// Returns the graphics configuration for the primary screen
private static GraphicsConfiguration getGraphicsConfiguration() {
return GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration();
}
public static BufferedImage createColorModelCompatibleImage(BufferedImage image) {
ColorModel cm = image.getColorModel();
return new BufferedImage(cm,
cm.createCompatibleWritableRaster(image.getWidth(),
image.getHeight()),
cm.isAlphaPremultiplied(), null);
}

public static BufferedImage createCompatibleImage(BufferedImage image) {


return createCompatibleImage(image, image.getWidth(), image.getHeight());
}

public static BufferedImage createCompatibleImage(BufferedImage image,


int width, int height) {
return getGraphicsConfiguration().createCompatibleImage(width, height,
image.getTransparency());
}
public static BufferedImage createCompatibleImage(int width, int height) {
return getGraphicsConfiguration().createCompatibleImage(width, height);
}

public static BufferedImage createCompatibleTranslucentImage(int width,


int height) {
return getGraphicsConfiguration().createCompatibleImage(width, height,
Transparency.TRANSLUCENT);
}
public static BufferedImage loadCompatibleImage(URL resource)
throws IOException {
BufferedImage image = ImageIO.read(resource);
return toCompatibleImage(image);
}
public static BufferedImage toCompatibleImage(BufferedImage image) {
if (image.getColorModel().equals(
getGraphicsConfiguration().getColorModel())) {
return image;
}
BufferedImage compatibleImage =
getGraphicsConfiguration().createCompatibleImage(
image.getWidth(), image.getHeight(),
image.getTransparency());
Graphics g = compatibleImage.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return compatibleImage;
}
public static BufferedImage createThumbnailFast(BufferedImage image,
int newSize) {
float ratio;
int width = image.getWidth();
int height = image.getHeight();
if (width > height) {
if (newSize >= width) {
throw new IllegalArgumentException("newSize must be lower than" +
" the image width");
} else if (newSize <= 0) {
throw new IllegalArgumentException("newSize must" +
" be greater than 0");
}
ratio = (float) width / (float) height;
width = newSize;
height = (int) (newSize / ratio);

} else {
if (newSize >= height) {
throw new IllegalArgumentException("newSize must be lower than" +
" the image height");
} else if (newSize <= 0) {
throw new IllegalArgumentException("newSize must" +
" be greater than 0");
}
ratio = (float) height / (float) width;
height = newSize;
width = (int) (newSize / ratio);
}
BufferedImage temp = createCompatibleImage(image, width, height);
Graphics2D g2 = temp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(), null);
g2.dispose();
return temp;
}
public static BufferedImage createThumbnailFast(BufferedImage image,
int newWidth, int newHeight) {
if (newWidth >= image.getWidth() ||
newHeight >= image.getHeight()) {
throw new IllegalArgumentException("newWidth and newHeight cannot" +
" be greater than the image" +
" dimensions");
} else if (newWidth <= 0 || newHeight <= 0) {
throw new IllegalArgumentException("newWidth and newHeight must" +
" be greater than 0");
}
BufferedImage temp = createCompatibleImage(image, newWidth, newHeight);
Graphics2D g2 = temp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(), null);
g2.dispose();
return temp;
}
public static BufferedImage createThumbnail(BufferedImage image,

int newSize) {
int width = image.getWidth();
int height = image.getHeight();
boolean isWidthGreater = width > height;
if (isWidthGreater) {
if (newSize >= width) {
throw new IllegalArgumentException("newSize must be lower than" +
" the image width");
}
} else if (newSize >= height) {
throw new IllegalArgumentException("newSize must be lower than" +
" the image height");
}
if (newSize <= 0) {
throw new IllegalArgumentException("newSize must" +
" be greater than 0");
}
float ratioWH = (float) width / (float) height;
float ratioHW = (float) height / (float) width;
BufferedImage thumb = image;
do {
if (isWidthGreater) {
width /= 2;
if (width < newSize) {
width = newSize;
}
height = (int) (width / ratioWH);
} else {
height /= 2;
if (height < newSize) {
height = newSize;
}
width = (int) (height / ratioHW);
}

BufferedImage temp = createCompatibleImage(image, width, height);


Graphics2D g2 = temp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(thumb, 0, 0, temp.getWidth(), temp.getHeight(), null);

g2.dispose();
thumb = temp;
} while (newSize != (isWidthGreater ? width : height));
return thumb;
}
public static BufferedImage createThumbnail(BufferedImage image,
int newWidth, int newHeight) {
int width = image.getWidth();
int height = image.getHeight();
if (newWidth >= width || newHeight >= height) {
throw new IllegalArgumentException("newWidth and newHeight cannot" +
" be greater than the image" +
" dimensions");
} else if (newWidth <= 0 || newHeight <= 0) {
throw new IllegalArgumentException("newWidth and newHeight must" +
" be greater than 0");
}
BufferedImage thumb = image;
do {
if (width > newWidth) {
width /= 2;
if (width < newWidth) {
width = newWidth;
}
}
if (height > newHeight) {
height /= 2;
if (height < newHeight) {
height = newHeight;
}
}
BufferedImage temp = createCompatibleImage(image, width, height);
Graphics2D g2 = temp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(thumb, 0, 0, temp.getWidth(), temp.getHeight(), null);
g2.dispose();
thumb = temp;

} while (width != newWidth || height != newHeight);


return thumb;
}
public static int[] getPixels(BufferedImage img,
int x, int y, int w, int h, int[] pixels) {
if (w == 0 || h == 0) {
return new int[0];
}
if (pixels == null) {
pixels = new int[w * h];
} else if (pixels.length < w * h) {
throw new IllegalArgumentException("pixels array must have a length" +
" >= w*h");
}
int imageType = img.getType();
if (imageType == BufferedImage.TYPE_INT_ARGB ||
imageType == BufferedImage.TYPE_INT_RGB) {
Raster raster = img.getRaster();
return (int[]) raster.getDataElements(x, y, w, h, pixels);
}
return img.getRGB(x, y, w, h, pixels, 0, w);
}
public static void setPixels(BufferedImage img,
int x, int y, int w, int h, int[] pixels) {
if (pixels == null || w == 0 || h == 0) {
return;
} else if (pixels.length < w * h) {
throw new IllegalArgumentException("pixels array must have a length" +
" >= w*h");
}
int imageType = img.getType();
if (imageType == BufferedImage.TYPE_INT_ARGB ||
imageType == BufferedImage.TYPE_INT_RGB) {
WritableRaster raster = img.getRaster();
raster.setDataElements(x, y, w, h, pixels);
} else {
img.setRGB(x, y, w, h, pixels, 0, w);
}
}
}

Source Code Image Sharpen Filter


package ImageSharpenFilter;
import java.awt.*;
import java.awt.image.*;
public class ImageSharpenFilter {
static BufferedImage gambar;
static boolean imageLoaded = false;
public static void main(String[] args) {
ImageObserver myImageObserver = new ImageObserver() {
@Override
public boolean imageUpdate(Image gambar, int flags, int x, int y, int width, int height) {
if ((flags & ALLBITS) != 0) {
imageLoaded = true;
System.out.println("Gambar Berhasil Difilter!");
return false;
}
return true;
}
};
String imageURL = "sapi.JPG";
Image sourceImage = Toolkit.getDefaultToolkit().getImage(imageURL);
sourceImage.getWidth(myImageObserver);
while (!imageLoaded) {
try {

Thread.sleep(100);
} catch (InterruptedException e) {
}
}
GraphicsEnvironment graphicsEnvironment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice graphicsDevice = graphicsEnvironment.getDefaultScreenDevice();
GraphicsConfiguration graphicsConfiguration = graphicsDevice.getDefaultConfiguration();
gambar = graphicsConfiguration.createCompatibleImage(sourceImage.getWidth(null),
sourceImage.getHeight(null), Transparency.BITMASK);
Graphics graphics = gambar.createGraphics();
graphics.drawImage(sourceImage, 0, 0, null);
graphics.dispose();
Kernel kernel = new Kernel(3, 3,
new float[]{
-1, -1, -1,
-1, 9, -1,
-1, -1, -1});
BufferedImageOp op = new ConvolveOp(kernel);
gambar = op.filter(gambar, null);
Frame frame = new Frame("Hasil Sharpen Filter");
frame.add(new CustomPaintComponent());
int frameWidth = 500;
int frameHeight = 500;
frame.setSize(frameWidth, frameHeight);
frame.setVisible(true);
}

static class CustomPaintComponent extends Component {


@Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
int x = 0;
int y = 0;
g2d.drawImage(gambar, x, y, this);
}
}
}
Source Code Median Filter
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;
import javax.imageio.*;
class MedianFilter{
public static void main(String[] a)throws Throwable{
File f=new File("Sapi.jpg");
Color[] pixel=new Color[9];
int[] R=new int[9];
int[] B=new int[9];
int[] G=new int[9];
File output=new File("MedianSapi.jpg");
BufferedImage img=ImageIO.read(f);
for(int i=1;i<img.getWidth()-1;i++)
for(int j=1;j<img.getHeight()-1;j++)
{
pixel[0]=new Color(img.getRGB(i-1,j-1));
pixel[1]=new Color(img.getRGB(i-1,j));
pixel[2]=new Color(img.getRGB(i-1,j+1));
pixel[3]=new Color(img.getRGB(i,j+1));
pixel[4]=new Color(img.getRGB(i+1,j+1));
pixel[5]=new Color(img.getRGB(i+1,j));
pixel[6]=new Color(img.getRGB(i+1,j-1));
pixel[7]=new Color(img.getRGB(i,j-1));
pixel[8]=new Color(img.getRGB(i,j));
for(int k=0;k<9;k++){
R[k]=pixel[k].getRed();
B[k]=pixel[k].getBlue();
G[k]=pixel[k].getGreen();
}
Arrays.sort(R);

Arrays.sort(G);
Arrays.sort(B);
img.setRGB(i,j,new Color(R[4],B[4],G[4]).getRGB());
}
ImageIO.write(img,"jpg",output);
}
}

Original

Media Filter

Sharpen Filter

Gaussian Filter

Original

Media Filter

Sharpen Filter

Gaussian Filter

Original

Media Filter

Sharpen Filter

Gaussian Filter

You might also like