Image Pruning

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 69

IMAGE PRUNING USING BELIEF PROPAGATION

1. INTRODUCTION

Modern digital technology has made it possible to manipulate multi-dimensional signals


with systems that range from simple digital circuits to advanced parallel computers. The goal of
this manipulation can be divided into three categories:

 Image Processing image in -> image out


 Image Analysis image in -> measurements out
 Image Understanding image in -> high level description out

We will focus on the fundamental concepts of image processing. Space does not permit
us to make more than a few introductory remarks about image analysis. Image Understanding re-
quires an approach that differs fundamentally from the theme of this book.

Fu0072ther, we will restrict ourselves to two-dimensional (2D) image processing al-


though most of the concepts and techniques that are to be described can be extended easily to
three or more dimensions. We begin with certain basic definitions.

An image defined in the "real world" is considered to be a function of two real variables,
for example, a(x,y) with a as the amplitude (e.g. brightness) of the image at the real coordinate
position (x,y). An image may be considered to contain sub-images sometimes referred to as re-
gions-of-interest, ROIs, or simply regions.

This concept reflects the fact that images frequently contain collections of objects each of
which can be the basis for a region. In a sophisticated image processing system it should be pos-
sible to apply specific image processing operations to selected regions.

Thus one part of an image (region) might be processed to suppress motion blur while an-
other part might be processed to improve color rendition.The amplitudes of a given image will
almost always be either real numbers or integer numbers.
The latter is usually a result of a quantization process that converts a continuous range
(say, between 0 and 100%) to a discrete number of levels. In certain image-forming processes,
however, the signal may involve photon counting which implies that the amplitude would be in-
herently quantized.

In other image forming procedures, such as magnetic resonance imaging, the direct phys-
ical measurement yields a complex number in the form of a real magnitude and a real phase.
1.2PROJECT OVERVIEW:

An interactive image completion method is proposed based on Belief Propagation (BP). Blocked
area or area with loss of information in a target image is completed with BP combined with
texture synthesis in an interactive way. The target image is decomposed by BP into levels of
Intrinsic Mode Functions (IMF) images, while the user is allowed to indicate the structural image
edge to recover in the unknown image regions. For each level of IMF image, first the target
image patches along user-specified curves in the unknown region are completed. Then the
remaining target image patches are prioritized to complete according to image gradient feature.
The target image patches are completed based on the combination frequency feature values from
BP and the texture synthesis. Finally, levels of completed IMF images are compounded into the
result image. Experiments prove that the proposed algorithm is not only able to recover the
damaged structural and texture information of large scale, but also completely blocked image
structures.
2. SYSTEM ANALYSIS

2.1 FEASIBILITY STUDY:

In feasibility study an estimate is made of whether the identified user needs may be
satisfied using current software and hardware techniques. The study will decide if the proposed
system will be cost effective from a business point of view, and if it can be developed given
existing budgetary constraints.

The result should inform the decision whether to go ahead with a more detailed
analysis.The feasibility of the system is decided based on the following three distinct aspects,
which are considered in the investigation phase.

The development of a computer-based system is very likely to be plagued by resource


scarcity and stringent delivery schedules. It is necessary to evaluate the feasibility of a project at
the earliest possible time.

Wastage of manpower and financial resources and untold professional embarrassment can
be avoided if an ill-conceived system is identified early in the definition phase and aborted.
Scarcity of resources and project completion dates challenges the software development process.

It is both necessary and prudent to evaluate the feasibility of a project at the earliest
possible time. A feasibility study is not warranted for systems in which economic justification is
obvious, technical risk is low, few legal problems are accepted and no reasonable alternative exists.

An estimate is made of whether the identified user (client) may be satisfied using current
software and hardware technologies. The study will decide if the proposed system will be cost
effective from the business point of view and it can be developed in the given existing budgetary
constraints.

So, a detailed study was carried out to check the workability of the proposed system.
Feasibility study is the test of system proposal regarding its workability, impact on the
organization, ability to meet user needs, and effective use of resources.
Thus when a new application is proposed, it normally goes through a feasibility study
before it is approved for development. Feasibility and Risk Analysis are related in many ways. If
project risk is great, the feasibility of producing quality software is reduced. Our Project is feasible
when we are using the procedure in proper manner.

2.2 EXISTING SYSTEM


 Statistical-based methods,
 PDE-based methods,
 Exemplar-based methods.

Statistical - based methods

These methods are mainly used for the case of texture synthesis. Typically, what these
methods do is that, given an input texture, they try to describe it by extracting some statistics
through the use of compact parametric statistical models.

Then, in order to synthesize a new texture, these methods typically start with an output
image containing pure noise, and keep perturbing that image until its statistics match the
estimated statistics of the input texture.

Besides the synthesis of still images, parametric statistical models have been also
proposed for the case of image sequences.

However, the main drawback of all methods that are based on parametric statistical
models is that, as already mentioned, they are applicable only to the problem of texture synthesis,
and not to the general problem of image completion.

PDE - based methods

These methods, on the other hand, try to fill the missing region of an image through a
diffusion process, by smoothly propagating information from the boundary towards the interior
of the missing region.
According to these techniques, the diffusion process is simulated by solving a partial
differential equation (PDE), which is typically non-linear and of high order.

The main disadvantage of almost all PDE based methods is that they are mostly suitable
for image inpainting situations. This term usually refer to the case where the missing part of the
image consists of thin, elongated regions.

Furthermore, PDE-based methods implicitly assume that the content of the missing
region is smooth and non-textured.

For this reason, when these methods are applied to images where the missing regions are
large and textured, they usually oversmooth the image and introduce blurring artifacts.

Exemplar-based methods

These methods try to fill the unknown region simply by copying content from the
observed part of the image. All exemplar-based techniques for texture synthesis that have
appeared until now, were either pixel-based , or patch-based, meaning that the final texture was
synthesized one pixel, or one patch at a time by simply copying pixels or patches from the
observed image respectively.

Exemplar based method


Recent exemplar-based methods also place emphasis on the order by which the image
synthesis proceeds, usually using a confidence map for this purpose. There are two main
handicaps of related existing techniques.

First, the confidence map is computed based on heuristics and ad hoc principles that may
not apply in the general case and second, once an observed patch has been assigned to a missing
block of pixels, that block cannot change its assigned patch thereafter.

This last fact reveals the greediness of these techniques, which may lead to visual
inconsistencies.

2.3 PROPOSED SYSTEM:

We presenting an operator called seam carving for content-aware resizing of images


computed as the optimal paths on a single image and removing from an image.

This operator can be used for image manipulations including: image retargeting and
object removal. The operator can be easily integrated with various saliency measures, as well as
user input, to guide the resizing process.

In addition, we define a data structure for multi-size images that support continuous
resizing ability in real time we present a representation of multi-size images that encodes, for an
image of size (m×n), an entire range of retargeting sizes from a×b to m×n and allows the user to
retarget an image continuously in real time.

Seam carving

Seam carving is an image resizing algorithm developed by Shai Avidan and Ariel
Shamir. This algorithm alters the dimensions of an image not by scaling or cropping, but rather
by intelligently removing pixels from (or adding pixels to) the image that carry little importance.

The importance of a pixel is generally measured by its contrast when compared with its
neighbor pixels, but other measures may be used. Additionally, it's possible to define (or
autodetect) areas of high importance (faces, buildings, etc.) in which pixels may not be deleted,
and conversely, areas of zero importance which should be removed first.

From this information, the algorithm detects seams (continuous lines of pixels joining
opposite edges of the image) which have the lowest importance, and deletes those.

This shrinks the image by one horizontal or vertical line, depending on which direction
the seam ran. Seam carving can also be run in reverse by adding interpolated pixels along the
lowest energy seam.

With this technique, it's now possible to reduce or enlarge pictures by a wide range, while
still retaining details. In normal image scaling, it's often not possible to scale about factor greater
than 2 or less than 0.5, without losing much of the images quality.

ADVANTAGES OF PROPOSED SYSTEM

We here propose the image completion process with a handful of advantages providing
an image with visually plausible outcome without any inconsistencies, thereby providing the
necessary image enlarging.

A simple image operator called seam carving is used here that supports content-aware
image resizing for both reduction and expansion. A seam is an optimal 8-connected path of
pixels on a single image from top to bottom, or left to right, where optimality is defined by an
image energy function.

No user intervention is required by our method, which avoids greedy patch assignments
by maintaining many candidate source patches. In this way, each missing block of pixels is
allowed to change its assigned patch many times throughout the execution of the algorithm, and
is not enforced to remain tied to the first label that has been assigned to it during the early stages
of the completion process.
Our formulation applies not only to image completion, but also to texture synthesis and
image inpainting, thus providing a unified framework for all of these tasks.

To this end, a novel optimization scheme is proposed, the “Priority-BP” algorithm, which
carries 2 major improvements over standard belief propagation: “dynamic label pruning” and
“priority based message scheduling”.

Together, they bring a dramatic reduction in the overall computational cost of BP. It is to
be noted that both extensions are generic and can be used for the optimization of any MRF.
3. SYSTEM CONFIGURATION

3.1 HARDWARE SPECIFICATION:

 RAM : 4 GB
 Hard Drive : 1 TB

3.2 SOFTWARE SPECIFICATION:

 Platform : JAVA 1.5


 Operating System : Microsoft Windows NT 4.0 or
Windows 2000 or XP
 Tool Used : Swing and Collection API

3.3 ABOUT THE SOFTWARE:


FRONT END (JAVA)

INTRODUCTION:

Java was conceived by James Gosling, Patrick Naughton, ChrisWarth, Ed Frank and Mike Sheri-
dan at SUN Micro Systems Incorporation in 1991. It took 18 months to develop the first work-
ing version. This language was initially called “OAK”, but was renamed “JAVA” in 1995. Be-
fore the initial implementation of OAK in 1992 and the public announcement of Java in 1995,
many more contributed to the design and evolution of the language.

OVERVIEW OF JAVA:

The context of an applet is limited only by one’s imagination. For example, an applet can be an
animation with sound, an interactive game or a ticker tape with constantly updated stock prices.
Applets can be serious application like word processor or spreadsheet.

But Java is more than a programming language for writing applets. It is being used more and
more for writing An Object Oriented Programming Language(OOPL) developed at Sun Mi-
crosystems. A Virtual Machine Run Time Environment that can be embedded in web browser
(IE, NN). Java is a powerful but lean object oriented programming language. It has generated a
lot of excitement because it makes it possible to program for Internet by creating applets, pro-
grams that can be embedded in web page.standalone applications as well. It is becoming so pop-
ular that many people believe it will become standard language for both general purpose and In-
ternet programming. There are many buzzwords associated with Java, but because of its spectac-
ular growth in popularity, a new buzzword has appeared ubiquitous. Indeed, all indications are
that it will soon be everywhere.

Java builds on the strength of C++. It has taken the best features of C++ and discarded the more
problematic and error prone parts. To this lean core, it has added garbage collection (automatic
memory management), multithreading (the capacity for one program to do more than one thing
at a time), security capabilities. The result is simple, elegant, powerful and easy to use.

Java is actually a platform consisting of three components:

 Java Programming Language.


 Java Library of Classes and Interfaces.
 Java Virtual Machine.
It also has a Standardized set of Packages (Class, Interfaces):

 Creating Graphical User Interfaces


 Controlling Multimedia Data
 Communicating over Network
The following sections will say more about these components:

FEATURES OF JAVA:

PORTABILITY:
One of the biggest advantages Java offers is that it is portable. An application written in Java will
run on all the major platforms. Any computer with a Java based browser can run the applications
or applets written in the Java Programming Language. A programmer no longer has to write one
program to run on a Macintosh, another program to run on a windows machine, still another to
run on a UNIX machine, and so on. In other words, with Java, developers write their programs
only once. The virtual machine is what gives Java is cross platform capabilities.

Rather than being compiled into machine language, which is different for each operating systems
and computer architecture, Java code is compiled into byte codes. With other languages, the pro-
gram can understand. The problem is that other computers with different machine instruction set
cannot understand that language. Java code, on the other hand is compiled into byte codes rather
than a machine language. These byte codes go to the Java virtual machine, which executes them
directly or translate them into the language that is understood by the machine running it. In Sum-
mary, these means that with the JDBC API extending Java, A programmer writing Java
code can access all the major relational databases on any platform that supports the Java virtual
machine.

OBJECT_ORIENTED:

The Java programming language is object oriented, which makes program design focus on what
you are dealing with rather than on how you are going to do something. This makes it more use-
ful for programming in sophisticated projects because one can break the things down into under-
standable components. A big benefit is that these components can then be reused.

Object oriented languages use the paradigm of classes. In simplest term, a class includes both the
data and the functions to operate on the data. You can create an instance of a class, also called an
object, which will have all the data members and functionality of its class. Because of this, you
can think of a class as being like template, with each object being a specific instance of a particu-
lar type of class.

The class paradigm allows one to encapsulate data so that specific data values are those using the
data cannot see function implementation. Encapsulation makes it possible to make the changes in
code without breaking other programs that use that code. If for example the implementation of a
function is changed, the change is invisible to the programmer who invokes that function, and it
does not affect his/her program, except hopefully to improve it. Java includes inheritance, or the
ability to derive new classes from existing classes. The derived class, also called a subclass, in-
herits all the data and the functions of the existing class, referred to as the parent class. A sub-
class can add new data members to those inherited from the parent class. As far as methods are
concerned, the subclass can reuse the inherited methods as it is, changed them, and/or add its
own new methods.

EASY

In addition to being portable and object oriented, Java facilitates writing correct code. Program-
mers spend less time writing Java code and a lot less time debugging it. In fact, developers have
reported slashing development time by as much as two thirds.

The following is a list of some of Java’s features that make it easier to write correct code:

GARBAGE COLLECTION:

Automatically takes care of allocating and reallocating memory, a huge potential source of er-
rors. If an object is no longer being used (has no references to it), then it is automatically re-
moved from memory. Dynamic binding is possible and often very useful, but static binding with
strict type checking is used when possible.

SIMPLICITY:

Makes Java easier to learn and use correctly. Java keep it simple by having just one way to do
something instead of having several alternatives, as in some languages. Java also stays lean by
not including multiple inheritance, which eliminates the errors and ambiguity that arise when you
create a subclass that inherits from two or more classes. Java lets you add functionality to a class
throws by the use of interfaces.

JAVA INCLUDES A LIBRARY OF CLASSES AND INTERFACES:

The Java platform includes an extensive class library so that programmers can use already exist-
ing classes, as it is, create subclasses to modify existing classes, or implement interfaces to aug-
ment the capabilities of classes.

Both classes and interfaces contain data members (fields) and functions (methods), but there are
major differences. In a class, fields may be either variable or constant, and methods are fully im-
plemented. In an interface, fields must be constants, and methods are just prototypes with no im-
plementations. The prototypes give the method signature (the return type, the function name, and
the number of parameters with the type for each parameter), but the programmer must supply im-
plementations.

To use an interface, a programmer defines a class, declares that it implements the Interface, and
then implements all the methods in that interface as part of the class. These methods are imple-
mented in a way that is appropriate for the class in which the methods are being used. Interfaces
let one add functionality to a class and give a great deal of flexibility in doing it. In other words
interfaces provide most of the advantages of multiple inheritances without its disadvantages.

A package is a collection of related Java classes and interfaces. The following list, though not
complete, gives example of some Java packages and what they cover.

 Java.lang: The basic classes. This package is so basic that it automatically is included in
any Java program. It includes classes dealing with numeric, strings, objects, runtime, se-
curity, and threads.
 Java.io: Classes that manages reading data from input streams and writing data to the out-
put streams.
 Java.util: Miscellaneous utility classes, including generic data structures, bit sets, time,
date, the string manipulation, random number generation, system properties, notification
and enumeration of data structures.
 Java.net: Classes for network support.
 Java.awt: Classes that manage user interface components such as windows, dialog boxes,
buttons, and checkboxes, lists, menus, scrollbars, and text fields, the “AWT” stands for
Abstract Window Toolkit.
 Java.awt.image: Classes for managing image data, including color models, dropping
color flittering, setting pixel values, and grabbing snapshots.
 Java.applet: The Applet class, which provides the ability to write applets, this package
also includes several interfaces that, connect an applet to its documents and to its docu-
ment and to its document and to recourses for playing audio.
 Java.sql: The JDBC API, classes and interfaces that access databases and send SQL
Statements.

The first three packages listed, java.lang, java.io and java.util form the foundation, they are basic
classes and interfaces for general-purpose programming.

Java development kit version1.1 added some new packages, with JDBC being one of them.
Other new packages include such thing as Remote Method Invocation, Security and Java Beans,
the new API for creating reusable components.

In Java, packages serve as the foundation for building other packages, as discussed in the follow-
ing section.

EXTENSIBILITY:
A big plus for Java is the fact it can be extended. It was purposely written to be lean with the
emphasis on doing what it does very well, instead of trying to do everything from the beginning;
it was return so that extending it is very easy. Programmers can modify existing classes or write
their own new classes or they can write a whole new package. The JDBC API, the java.sql
package, is one example of a foundation upon which extensions are being built. Other extensions
are being added or worked on in area such as multimedia, Internet Commerce, conferencing, and
telephony.
In addition to extensions there are also main tools being developed to make existing capabilities
easier to use. For example, there is already a tool that greatly Simplifies creating and laying out
Graphical User Interfaces such as menus, Dialog boxes and buttons.

SECURITY:

It is important that a programmer not be able to write subversive code for Applications or ap-
plets. This is especially true with the Internet being used more and more extensively for services
such as electronic commerce and electronic distribution of software and multimedia content.

The Java platform builds in security in four ways.

 The way memory is Allocated and laid out: In Java an object’s location in memory is not
determined until The runtime, as opposed to C and C++, where the compiler makes mem-
ory layout Decisions. As the result, a programmer cannot look at a class definition and
figure out how it might be laid out in memory. Also since, Java has no pointers, a pro-
grammer cannot forge pointers to memory.
 The way incoming code is checked: The Java virtual machine doesn’t trust any incoming
code and subjects it to what is called byte code verification. The byte code Verifier, part
of the virtual machine, checks that the format of incoming code is correct.Incoming code
doesn’t forge pointers, it doesn’t violate access restrictions, it accesses objects what they
are.
 The way classes are loaded: The Java byte code loader, another part of the virtual ma-
chine, whether classes loaded during program execution are local or from across a net-
work. Imported classes cannot be substituted for built in classes, and built in classes can-
not accidentally reference classes brought in over a network.
 The way access is restricted for untested code: The Java security manager allows user to
restrict untested Java applets so that they cannot access the local network, files and other
resources.
JAVA PERFORMS WELL:

Java performance is better than one might expect. Java has many advantages, such as having
built in security and being interpreted as well as compiled, do have a cost attached to them. How-
ever, various optimizations have been built in, and the byte code Interpreter can run very fast the
cost it doesn’t have to do any checking. As a result, Java has done quite respectably in perfor-
mance tests. Its performance numbers for interpreting byte codes are usually more than adequate
to run interactive graphical end user applications.

For situations that require unusually high performance, byte codes can be translated on the fly,
generating the final machine code for the particular CPU on which the application is running at
run time. High level interpreted scripting language generally offer great portability and fast pro-
totyping but poor performance. Low level compiled language like C and C++ offer great perfor-
mance but require large amounts of time for writing and debugging code because of problems
with areas such as memory management, pointers and multiple inheritances. Java offers good
performance with the advantages of high level languages but without the disadvantages of C and
C++.

ROBUST:

The multi plat formed environment of the WEB places extraordinary demands on a program, be-
cause it must execute reliably in a variety of systems. Thus the ability to create robust programs
was given a high priority in the design of Java. To gain reliability, Java restricts you in a few key
areas to force you to find your mistakes early in program developments. At the same time, Java
frees you from having to worry about many of the most common cause of programming errors.
Because Java is strictly typed language, it checks your code at compile time. However, it also
checks your code at run time. In fact, many hard to track down bugs that often turn up in hard to
reproduce runtime situations are simply impossible to create in Java. Knowing that what you
have written will behave in a predictable way under diverse conditions is a key feature of Java to
understand how Java robust.
Consider two main reasons for program failure:

 Memory management mistakes and mishandled exceptional conditions (run time errors).
 Memory management can be difficult, tedious task in traditional programming environ-
ments.

For example in C/C++ the programmer must manually allocate and free all dynamic memory.
This sometimes leads to problems. For example some programmers some times forget the free
memory that has been previously allocated. Or worse, they may free some memory that another
part of their code is still using. Java virtually eliminates these problems by managing memory al-
locations and reallocations. Java helps in this area by providing object oriented exception han-
dling. In a well-written Java a program should manage program all run time errors.

SCALABILITY
Java platform is designed to scale well, from portable consumer electronic devices to powerful
desktop and server machines. The virtual machine takes a small foot print and Java byte code is
optimized to be small and compact. As a result, Java accommodates the need for low storage and
for low bandwidth transmission over the Internet. In addition the Java operating system offers a
standalone Java platform that eliminates host operating system overhead while still supporting
the full Java platform. API makes Java ideal for low cost network computers whose sole purpose
is to access the Internet.

MULTITHREADED:

Multithreading is simply the ability of a program to do more than one thing at a time. For exam-
ple an application could be faxing a document at the same time it is printing another document.
Or a program could process new inventory figures while it maintains a feed for current prices.
Multithreading is particularly important in multimedia. A multimedia program might often be
running a movie, running a audio track and displaying text all at the same time.
IMPORTANT TO THE INTERNET:

The Internet helped catapult Java to the forefront of programming and Java in turn has a pro-
found effect on the Internet. The reason is simple. Java expands the universe of objects that can
move about freely in cyberspace. In a network, there are two broad categories of objects trans-
mitted between the server, your personal computer, passive information and dynamic, active pro-
grams. For example, when you read your e-mail, you are viewing passive data. Even when you
download a program, the program’s code is still only passive data until you execute it. However,
there is a second type of object that can be transmitted to your computer, a dynamic, self execut-
ing program. Such a program would be an active agent on the client computer, yet it would be
initiated by the server. As desirable as dynamic, networked programs are, they also present seri-
ous problems in the areas of security and portability. Prior to Java cyberspace was effectively
closed to half the entities that now live there. Java addresses these concerns and doing so, has
opened the door to an exiting a new form of program.

JAVA SWINGS
Introduction to swing:
Swing contains all the components. It’s a big library, but it’s designed to have appropriate
complexity for the task at hand – if something is simple, you don’t have to write much code but
as you try to do more your code becomes increasingly complex. This means an easy entry point,
but you’ve got the power if you need it. Swing has great depth. This section does not attempt to
be comprehensive, but instead introduces the power and simplicity of Swing to get you started
using the library. Please be aware that what you see here is intended to be simple. If you need to
do more, then Swing can probably give you what you want if you’re willing to do the research
by hunting through the online documentation from Sun.

Benefits of swing:
Swing components are Beans, so they can be used in any development environment that supports
Beans. Swing provides a full set of UI components. For speed, all the components are
lightweight and Swing is written entirely in Java for portability. Swing could be called
“orthogonality of use;” that is, once you pick up the general ideas about the library you can apply
them everywhere. Primarily because of the beans naming conventions.Keyboard navigation is
automatic – you can use a Swing application without the mouse, but you don’t have to do any
extra programming. Scrolling support is effortless – you simply wrap your component in a
JScroll Pane as you add it to your form. Other features such as tool tips typically require a single
line of code to implement. Swing also supports something called “pluggable look and feel,”
which means that the appearance of the UI can be dynamically changed to suit the expectations
of users working under different platforms and operating systems. It’s even possible to invent
your own look and feel.

The swing component classes are


SWING COMPONENT CLASSES

1. JFrame

The components added to the frame are referred to as its contents; these are managed by the con-
tentPane. To add a component to a JFrame, we must use its contentPane instead.JFrame is a
Window with border, title and buttons. When JFrame is set visible, an event dispatching thread is
started. JFrame objects store several objects including a Container object known as the content
pane. To add a component to a JFrame, add it to the content pane.

JFrame Features

It’s a window with title, border, (optional) menu bar and user-specified components.It can be
moved, resized, iconified. It is not a subclass of JComponent.
Delegates responsibility of managing user-specified components to a content pane, an instance of
JPanel.

Centering JFrame’s
By default, a Jframe is displayed in the upper-left corner of the screen. To display a frame at a
specified location, you can use the setLocation(x, y) method in the JFrame class. This method
places the upper-left corner of a frame at location (x, y).

The Swing API keeps improving with abstractions such as the setDefaultCloseOperation method
for the JFrame

Creating a JFrame Window

Step 1: Construct an object of the JFrame class.

Step 2: Set the size of the Jframe.

Step 3: Set the title of the Jframe to appear in the title bar (title bar will be blank if no title is set).

Step 4: Set the default close operation. When the user clicks the close button, the program stops
running.

Step 5: Make the Jframe visible.

How to position JFrame on Screen?

frame.setLocationRelativeTo( null );

2. JWindow

JWindow is Swing’s version of Window and is descended directly from that class. Like Win-
dow, it uses BorderLayout by default. Almost all Swing components are lightweight except JAp-
plet, JFrame, JDialog, and JWindow.

3.Labels

JLabel, descended from JComponent, is used to create text labels.


A JLabel object provides text instructions or information on a GUI — display a single line of
read-only text, an image or both text and image.
We use a Swing JLabel when we need a user interface component that displays a message or an
image. JØLabels

 Provide text instructions on a GUI


 lRead-only text
 lPrograms rarely change a label’s contents
 lClass JLabel (subclass of JComponent)

4.JTextField

JTextField allows editing/displaying of a single line of text. New features include the ability to
justify the text left, right, or center, and to set the text’s font. When the user types data into them
and presses the Enter key, an action event occurs. If the program registers an event listener, the
listener processes the event and can use the data in the text field at the time of the event in the
program. JTextField is an input area where the user can type in characters. If you want to let the
user enter multiple lines of text, you cannot use Jtextfield’s unless you create several of them.
The solution is to use JTextArea, which enables the user to enter multiple lines of text.

5.JPasswordField

JPasswordField (a direct subclass of JTextField) you can suppress the display of input. Each
character entered can be replaced by an echo character. This allows confidential input for pass-
words, for example. By default, the echo character is the asterisk, *. When the user types data
into them and presses the Enter key, an action event occurs. If the program registers an event lis-
tener, the listener processes the event and can use the data in the text field at the time of the event
in the program. If you need to provide an editable text field that doesn’t show the characters the
user types – use the JPasswordField class.

6.JTextArea

JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction with
class JScrollPane to achieve scrolling. The underlying JScrollPane can be forced to always or
never have either the vertical or horizontal scrollbar.
7.JButton

The abstract class AbstractButton extends class JComponent and provides a foundation for a
family of button classes, including JButton. A button is a component the user clicks to trigger a
specific action.

There are several types of buttons in Java, all are subclasses of AbstractButton.

 command buttons: is created with class JButton. It generates ActionEvent.


 toggle buttons: have on/off or true/false values.
 check boxes: a group of buttons. It generates ItemEvent.
 radio buttons: a group of buttons in which only one can be selected. It generates Ite-
mEvent.

8.JRadioButton

JRadioButton is similar to JCheckbox, except for the default icon for each class. A set of radio
buttons can be associated as a group in which only one button at a time can be selected.

9.JCheckBox

JCheckBox is not a member of a checkbox group. A checkbox can be selected and deselected,
and it also displays its current state.

10.JComboBox

.JComboBox is like a drop down box — you can click a drop-down arrow and select an option
from a list. It generates ItemEvent. For example, when the component has focus, pressing a key
that corresponds to the first character in some entry’s name selects that entry. A vertical scrollbar
is used for longer lists.

4. SYSTEM DESIGN
4.1 NORMALIZATION:

The first stage is normalization is to reduce the data to its first normal form,
by removing repeating items showing them as separate records but including in
them the key fields of the original record

The next stage of reduction to the second normal form is to check that the
record, which one is first normal form, all the items in each record are entirely
dependent on the key of the record. If a data item is not dependent on the key of
the record, but on the other data item, then it is removed with its key to form
another record. This is done until each record contains data items, which are
entirely dependent on the key of their record.

The final stage of the analysis, the reduction of third normal form involves
examining each record, which one is in second normal form to see whether any
items are mutually dependent. If there are any item there are removed to a separate
record leaving one of the items behind in the original record and using that as the
key in the newly created record.

4.2 TABLE DESIGN:

The following tables are the table structure for this project

Table 1:

The Login contains the username and password show in the below table

Column name Type


Username Varchar(50)
password Varchar(50)

4.3 INPUT DESGIN:


The input was classified into various forms, sometimes the user give manual inputs like text

(numeric, string, character, special characters). Sometimes the user itself became a input like the

biometric inputs such as finger print, palm print, iris, foot print and so on. In our proposed

project the user gives input through manual options such as unique username and password for

access the application. The user gives input through neither keyboard nor any sensors. The user

can give any type of input randomly. he can use any window frames through GUI control. The

forms also entered manually by the user.

4.4. SFD/DFD:

SYSTEM FLOW DIAGRAM


Input Image (100%) Tools and Adjust the
Image Sobel

Prewitt

Laplace
Img Resize

Forward Pass Backward Pass Img <100% Pruning

Belief Propagation

Seam carving 100% Output Image

5. SYSTEM DESCRIPTION

MODULES:
1. Design and loading image
2. Tools and adjusting the image
3. Filtering
4. Pruning
5. Integrating resizer and filter

MODULES DESCRIPTION:

1. DESIGN AND LOADING IMAGE

In this module we are designing the screen and image viewer. Next we load the binary
image in order to display the image that demands pruning and image resizing.

2 TOOLS AND ADJUSTING THE IMAGE

The arrow keys on the keyboard are used to increase or decrease the width and height of
the image. The window with the picture must be the active window on screen for pressing the
arrow keys to work. And also to see the adjustment in the screen while resizing the image.

(i)Tools

Certain tools are central to the processing of digital images. These include mathematical
tools such as convolution, Fourier analysis, and statistical descriptions, and manipulative tools
such as chain codes and run codes.

(ii)Convolution

In image processing applications, the entire input function is often available for comput-
ing every sample of the output function. In that case, the constraint that each output is the effect
of only prior inputs can be relaxed. Convolution amplifies or attenuates each frequency compo-
nent of the input independently of the other components.

(iii)Fourier Analysis
Fourier analysis is a subject area which grew out of the study of Fourier series. The sub-
ject began with trying to understand when it was possible to represent general functions by sums
of simpler trigonometric functions.

The attempt to understand functions (or other objects) by breaking them into basic pieces
that are easier to understand is one of the central themes in Fourier analysis. Fourier analysis is
named after Joseph Fourier who showed that representing a function by a trigonometric series
greatly simplified the study of heat propagation.

3. FILTERING
-1 0 1
-2 0 2
Here we are filtering the image to avoid noise by three algorithms.
-1 0 1
They are:
 Sobel filter
 Prewitt filter
 Laplace filter

(i)Sobel Filter

The Sobel operator performs a 2-D spatial gradient measurement on an image and so
emphasizes regions of high spatial frequency that correspond to edges. Typically it is used to
find the approximate absolute gradient magnitude at each point in an input grayscale image.

The Sobel Edge filter is use to detect edges based applying a horizontal and vertical filter
in sequence. Both filters are applied to the image and summed to form the final result. The two
filters are basic convolution filters of the form:

Vertical Filter Horizontal Filter


1 2 1
0 0 0
-1 -2 -1
Fig 3.1 Interface of sobel filter
Fig 3.2 E-R diagram of sobel filter

(ii)Prewitt Filter

The Prewitt Edge filter is use to detect edges based applying a horizontal and vertical
filter in sequence. Both filters are applied to the image and summed to form the final result. The
two filters are basic convolution filters of the form:

Horizontal Filter Vertical Filter


1 1 1 -1 0 1
0 0 0 -1 0 1
-1 -1 -1 -1 0 1
Fig 3.3 E-R diagram of prewitt filter

(iii) Laplace Filter

Discrete laplace operator is often used in image processing e.g. in edge detection and
motion estimation applications. The discrete laplacian is defined as the sum of the second
derivatives Laplace operator#Coordinate expressions and calculated as sum of differences over
the nearest neighbours of the central pixel.

Implementation in Image Processing


For one, two and three dimensional signals, the discrete laplacian can be given as
convolution with the following kernels:

1D-Filter:

2D-Filter:

or, including the diagonals:

2D-Filter:

3D-Filter: is given by: first plane =  ;

second plane =  ; third plane =


These kernels are deduced by using discrete differential quotients

Fig 3.4 E-R diagram of laplace filter

4. PRUNING
Pruning is mainly done under Priority-BP algorithm with forward pass and backward
pass by labeling the node which to be scheduled. The actual message scheduling mechanism as
well as label pruning takes place during the forward pass. The role of the backward pass is then
just to ensure that the other half of the messages gets transmitted as well.

(i).Label pruning
The main idea of “label pruning” is that, as we are visiting the nodes of the MRF during
the forward pass, we dynamically reduce the number of possible labels for each node by discard-
ing labels that are unlikely to be assigned to that node. Its use is allowed only in conjunction with
our priority-based message scheduling scheme of visiting most confident
nodes first.

This keeps our method generic and, therefore, applicable to any energy function. A key
observation, however, relates to the fact that label pruning is a technique not meant to be used on
its own.

(ii)Message scheduling

We use a specific message scheduling scheme, whose goal will be twofold. On one hand,
it will make label pruning possible and favor the
circulation of cheap messages. On the other hand, it will speed up BP’s convergence. This issue
of BP message scheduling, although known to be crucial for the success of BP, it has been
largely overlooked until now.

(iii)Forward Pass

Each iteration of Priority-BP is divided into a forward and a backward pass. The actual
message scheduling mechanism as well as label pruning takes place during the forward pass.
This is also where one half of the messages gets transmitted. To this end, all nodes are visited in
order of priority. Each time we visit a node, say p, we mark it as “committed” meaning that we
must not visit him again during the current forward pass.

We also prune its labels and then allow him to transmit its “cheap” (due to pruning) mes-
sages to all of its neighbors apart from the committed ones. The priorities of all neighbors that re-
ceived a new message are then updated and the process continues with the next uncommitted (i.e
unvisited) node of highest priority until no more uncommitted nodes exist.

(iv)Backward Pass
The role of the backward pass is then just to ensure that the other half of the messages
gets transmitted as well. To this end, we do not make use of priorities but simply visit the nodes
in reverse order, with respect to the order of the forward pass and just transmit the remaining un-
sent messages from each node. For this reason, no label pruning takes place during this pass.

We do update node priorities, though, so that they are available during the next forward
pass. Also, as we shall see, a node’s priority depends only on the current beliefs at that node. One
big advantage out of this is that keeping the node priorities up-to-date can be done very effi-
ciently in this
case, since only priorities for nodes with newly received messages need to be updated.

(v)Types of neighborhoods

Neighborhood operations play a key role in modern digital image processing. It is


therefore important to understand how images can be sampled and how that relates to the various
neighborhoods that can be used to process an image.
 Rectangular sampling
In most cases, images are sampled by laying a rectangular grid over an
image. This results in the type of sampling shown in Figure a and b.
 Hexagonal sampling
An alternative sampling scheme is shown in Figure c and is termed hexagonal
sampling.

Local operations produce an output pixel value b [m=mo,n=no] based upon the pixel val-
ues in the neighborhood of a[m=mo,n=no]. Some of the most common neighborhoods are the 4-
connected neighborhood and the 8-connected neighborhood in the case of rectangular sampling
and the 6-connected neighborhood in the case of hexagonal sampling illustrated in Figure that
follows.
Fig 3.5 Sampling types

5. INTEGRATING RESIZER AND FILTER

Here we integrate the three filter algorithms with the seam carving image resizing
algorithm and saving the image in to the resized image. After integrating the resizer and filter we
are testing and implementing.
ALGORITHM USING THIS PROJECT:

A pseudo code description of Priority-BP is contained in the following algorithm.

Nodes and Algorithm 1 Priority-BP

assign priorities to declare them uncommitted


for k = 1 to K do {K is the number of iterations}
execute Forward Pass and then Backward Pass
assign to each node p its label ˆxp that maximizes bp(・)

Forward Pass

for time = 1 to N do {N is the number of nodes}


p = “uncommitted” node of highest priority
apply “label pruning” to node p
forwardOrder[time] = p ; p→committed = true;
for any “uncommitted” neighbor q of node p do
send all messages mpq(・) from node p to node q
update beliefs bq(・) as well as priority of node q

Backward Pass

for time = N to 1 do
p = forwardOrder[time]; p→committed = false;
for any “committed” neighbor q of node p do
send all messages mpq(・) from node p to node q
update beliefs bq(・) as well as priority of node
MESSAGE PASSING

Fig a Fig b

Message passing

(a)If a node p wants to send a message m pq (xq ) to a neighboring node q, then it must make use
of the messages msp (xp ),mrp (xp ),mtp (xp ) coming from the rest of its neighbors. (b) If a node p
wants to calculate its belief bp (xp ) about any of the labels xp 2 L, it must then collect the
messages msp (xp ), mqp (xp ), mrp (xp ), mtp (xp ) coming from all of its neighboring nodes.
6. TESTING AND IMPLEMENTATION
TESTING

INTRODUCTION

Testing is a process to identify and correct the errors in the proposed system. Before imple-
menting the system, it should be tested in the manner that it works effectively under various conditions.
Every new system must be tested in various ways to make sure of its perfectas.

System testing is actually a series of different tests whose primary purpose is to fully exercise
the computer based system. Software is only one element of a larger computer based system. Ulti -
mately software is incorporated with other system elements and series of system integration and valida-
tion tests are conducted.

Testing presents an interesting anomaly for the software development. The testing phase cre -
ates a series of test cases that are intended to demolish the software that has been built. A good test
case is one that has a high probability of finding an as yet undiscovered error. A successful test is one
that uncovers as an yet undiscovered error.

STAGES IN THE TESTING PROCESS

The following are the various stages in the testing process.

 Unit testing
 Module testing
 Sub-system testing
 System testing
 Acceptance testing
 Task testing
 Behavioral testing
 Intertask testing
 User Interface testing
 Integration testing

Unit Testing

Unit testing focuses verification and validation effort on the smallest unit of software
design i.e., the module. The unit testing in always-white box oriented and a step can be
conducted in parallel for modules. The software developer does not turn the program to the ITG
group and go away.

It comprises the set of tests performed by an individual programmer prior to integration


of the unit into a larger system. The situation is illustrated as follows.

A program unit is usually small enough that the programmer who developed can test in a
great detail and certainly in greater detail that will be possible when the unit is integrated into an
evolving software product.

There are four categories of test that a programmer will typically perform on a program
unit.

 Functional tests

 Performance tests

 Stress tests

 Structure tests

Functional Tests

Functional test, where test cases involving exercising the code with nominal input values
for which the expected results are known, were done.

Performance Testing
This testing is designed to test the run time performance of software within the content of
an integrated system. This testing occurs through out all steps in the testing process. It is
concerned with the evaluation speed and memory utilization of the program.

Stress Tests

Stress testing, which is concerned with exercising the internal logic of a program and
traveling particular execution paths is done. The input is given in such away that starting form
request from client to the job completion all possible paths is tested.

Structure Tests

Structure testing is also referred to as White Box or Glass Box testing. The project is
tested for its execution in every module. The testing operation is successfully done and every
module performs properly.

Module Testing

A module is the collection of dependant components such as an object class, an abstract


data type or some collection of procedures and functions. The module encapsulates related
components that can be tested without other system modules.

Sub-System Testing

This phase involves testing collection of modules, which have been integrated into sub-
systems. Sub-systems may be independently designed and implemented.

The most common problem, which arises in large software systems, is sub-system
interface mismatches. The sub-system test process should therefore concentrate on the detection
of interface errors by rigorously exercising these interfaces.

System Testing
The sub-systems are integrated to buildup the entire system. The testing process is
concerned with finding errors, which is an outcome of unanticipated interaction between sub-
system and system components. If is also concerned with validating whether the system meets its
functional and non-functional requirements.

Accepting Testing

This is the final stage in the testing process before the system is accepted for operational
use. The system is tested data supplied by the system developed rather than simulated test data
acceptance testing may reveal error and omissions in the system requirement definition because
the real data exercises the system in different ways from the test. The systems facilities do not
really meet the users needs or the system performance in unacceptable.

Task Testing

The first step in the testing of real-time software is to test each task independently. That
is, the white and black box tests are designed and executed for each task. Each task is executed
independently during the tests. The task testing uncovers errors in logic and functions, but will
not uncover timing or behavioral errors.

Behavioural Testing

Using system modules created with case tools, it is possible to simulate the behavior of
external events. Using a technique that is similar to equivalence of partitioning, events and
categorized for testing.

Each of these events is tested individual and behavior of the executed system is examined
to detect an error that occurs as a Consequence of processing associated with these events. Once,
each class of events is tested, events are presented to the system in random order and with
frequency.
Intertask Testing

Once the errors in individual tasks and in system behavior have been isolated, testing
shifts to time-related errors the asynchronous task that are known to communicate with one
another are tested with different data rates and processing load to determine if inter task
synchronization errors will occur.

User Interface Testing

An interactive interface is a system that is dominated by interactive between the system


and external agents, such as human, devices or other programs.

The external agents are independent of the system o their input cannot be controlled,
although the system may solicit response from them. An interactive interface usually includes
only part of an entire application, one that can often be handled independently from the
computation part of the application.

The major concerns of an interactive interface are the communications protocol between
system and the external agents, the syntax of possible interactions the presentation of output the
flow of control within the system, the ease of understanding an user interface, performance and
error handling.

The dynamic model dominates interactive interfaces. Object in the model represent
interaction elements, such s input and output tokens and presentation formats. The functional
model describes which application functions are executed in response to input event sequences,
but the internal structure of the functions is usually unimportant to the behavior of the interface.

Integration Testing
Integration testing is a logical extension of unit testing. In its simplest form, two units
that have already been tested are combined into a component and the interface between them is
tested. A component, in this sense, refers to an integrated aggregate of more than one unit. In a
realistic scenario, many units are combined into components, which are in turn aggregated into
even larger parts of the program.

The idea is to test combinations of pieces and eventually expand the process to test your
modules with those of other groups. Eventually all the modules making up a process are tested
together. Beyond that, if the program is composed of more than one process, they should be
tested in pairs rather than all at once.

Integration testing identifies problems that occur when units are combined. By using a
test plan that requires you to test each unit and ensure the viability of each before combining
units, you know that any errors discovered when combining units are likely related to the
interface between units. This method reduces the number of possibilities to a far simpler level of
analysis

IMPLEMENTATION

Implementation is the stage of the project where the theoretical design is turned into a
working system. At this stage the main work load, the greatest upheaval and the major impact
on the existing system shifts to the user department.

If the implementation is not carefully planned and controlled, it can cause chaos and
confusion. Implementation includes all those activities that take place to convert from the old
system to the new one.

The new system may be totally new, replacing an existing manual or automated system
or it may be a major modification to an existing system. Proper implementation is essential to
provide a reliable system to meet the organization requirements.
Successful implementation may not guarantee improvement in the organization using the
new system, but improper installation will prevent it.

7. CONCLUSION AND FUTURE SCOPE


CONCLUSION:

A novel approach unifying image completion, texture synthesis and image inpainting has been
presented in this paper. In order to prohibit visually inconsistent results, we try to avoid greedy
patch assignments, and instead pose all of these tasks as a discrete labeling problem with a well-
defined global objective function. To solve this problem, a novel optimization scheme, Priority-
BP, has been proposed, that carries two very important extensions over standard BP: priority-
based message scheduling and dynamic label pruning. This optimization scheme does not rely on
any image-specific prior knowledge and can thus be applied to all kinds of images. Furthermore,
it is generic (i.e applicable to any MRF energy) and thus 29 copes with one of the main limita-
tions of BP: its inefficiency to handle problems with a huge number of labels. Also, experimental
results on a wide variety of images have verified the effectiveness of our method.

FUTURE SCOPE:
One interesting avenue of future work would be to extend our framework so that it can be
used for other types of completion problems as well. It would be interesting to test our frame-
work on problems such as video completion or geometric completion.
Also, in the future, we plan to allow the inclusion of more “refinement terms” into our
energy function. We believe that this will be a very elegant and easy-to apply way for allowing
the user to impose either high-level or low-level constraints on to the completion process.

In this manner, the user could gain a finer control over the final result. Furthermore, this
would make our method suitable for problems such as, e.g, constrained texture synthesis. Finally,
besides image completion, we also plan to test our Priority-BP algorithm, which is a generic
MRF optimization scheme, to other labeling problems as well, for which the large cardinality of
their state-space causes them to have a very high computational cost.

8. FORMS AND REPORTS


The above screen is the login screen of this project, you will give username as admin and
password as admin, after click login, it consider you are authorized user then directly goes to the
menu page.

This is the basic view of the project. It acts like a tool and user friendly options, so that any
one can use this project. The buttons and lists are used for image manipulations as per our
proposals. The panels and window frames segregate the controllers.
The user can select the image which he/she want to made pruning with the help of load but-
ton. If the user clicks the load button the above screen appears. It shows only image files with
extensions like .jpg, .bmp, .png. if the user select any others files other than image then the
below error message will appear in the screen and the programs sequence interrupted.
The user can save the images in his preferred location by click the save button. Once the
user clicked that button the above screen appears.
The filters are used to classification of wanted and unwanted pixels of the images. Here
in our tool we proposed three filters such as sobel, prewitt, laplcae. The user’s choice is
accepted while performing the filter operation. The brush size option is used to increase
or decrease the brush size.
From the above tool we are choosing a below image and performing the pruning opera-
tion by click the E button and preserve other data by click the P button. N button is used
for nuclear operation and C button is used for reset the image manipulation. Once we se-
lect the removal area in the image and press the ERASE button to perform the operation.
Once the operation finished the image appear like the above screen. Note that the back
row plane didn’t visible and only the fog is shown. From the retarget button the user can
change the height and width with his own interest. The user gives the height and width in
the required field.
9. BIBLIOGRAPHY

[1] J. Portilla and E. P. Simoncelli, “A parametric texture model based on joint statistics of com-
plex wavelet coefficients.”
IJCV, vol. 40, no. 1, pp. 49–70, 2000.
[2] D. J. Heeger and J. R. Bergen, “Pyramid-based texture analysis/synthesis,” in SIGGRAPH,
1995, pp. 229–238.
[3] Y. W. S. Soatto, G. Doretto, “Dynamic textures,” in Intl. Conf. on Computer Vision, pp.
”439–446”.
[4] A. W. Fitzgibbon, “Stochastic rigidity: Image registration for nowhere-static scenes,” in
ICCV, 2001, pp. 662–669.
[5] M. Szummer and R. W. Picard, “temporal texture modeling,” in Proc. of Int. Conference on
Image Processing, vol. 3,
1996, pp. 823–826.
[6] G. Doretto and S. Soatto, “Editable dynamic textures.” in CVPR (2), 2003, pp. 137–142.
[7] M. Bertalmio, G. Sapiro, V. Caselles, and C. Ballester, “Image inpainting,” in Siggraph 2000,
Computer Graphics
Proceedings. ACM Press / ACM SIGGRAPH / Addison Wesley Longman, 2000, pp. 417–424.
[8] M. Bertalm´ıo, A. L. Bertozzi, and G. Sapiro, “Navier-stokes, fluid dynamics, and image and
video inpainting.” in CVPR
(1), 2001, pp. 355–362.
SOURCE CODE:

SAMPLE CODE

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.filechooser.FileFilter;
import java.io.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.util.Vector;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;

/**
* The menu for an image resizer.
*
*
*/
public class ImageResizer extends JFrame{

//VARIABLES

/**
* The resizer for the image.
*/
private Resizer theResizer;

/**
* Selects the filter to use for the resizing.
*/
private JComboBox theFilters;

/**
* Selects the timing to pause for before updating the picture
*/
private JComboBox pauseTimes;

/**
* The current brush that will draw on the image.
*/
private int brushType = OverlayPanel.BRUSH_NORMAL;

/**
* The size of the current brush that will draw on the image.
*/
private int brushSize = 10;

/**
* Spinner holding the current image width.
*/
private JSpinner imgWidth;

/**
* Spinner holding the current image height.
*/
private JSpinner imgHeight;

/**
* Panel to show that something is being worked on.
*/
private WorkingPanel worker;

/**
* The size in bytes of the java virtual machine at the start. This
* represents the critical amount of memory that is necessary for the
* program to run. If our free memory falls below (or is very close) to this
* critical amount then the virtual machine throws an OutOfMemoryError.
*/
private static long m_initialJVMSize;

//CONSTRUCTORS

/**
* Builds a new menu.
*
*/
public ImageResizer(){
super("Menu");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final ImageResizer cloneOfMe = this;


worker = new WorkingPanel();

//buttons
JButton loadImage = new JButton("Load Image");
loadImage.setPreferredSize(new Dimension(200, 30));
loadImage.setMinimumSize(loadImage.getPreferredSize());
loadImage.setMaximumSize(loadImage.getPreferredSize());
loadImage.setToolTipText("Load an image to resize");
loadImage.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
//if the button was clicked...
//first check to see if we are already working on something...
if(theResizer != null){
if(!theResizer.isDisplayable()){
theResizer = null;
}else{
//prompt to see if it's ok to continue...
int option = JOptionPane
.showConfirmDialog(null,
"An image is already being worked on, are you
sure you want to open a new one?"
+ "\nAll changes to the current image will be
lost.",
"File already open",
JOptionPane.YES_NO_OPTION);

if(option == JOptionPane.NO_OPTION){
return;
}else{
//destroy the current window
theResizer.dispose();
theResizer = null;
}
}
}

//load a new image


//prompt for a file location
JFileChooser fchooser = new JFileChooser();
FileFilter filter = new FileFilter(){
public boolean accept(File f){
if(f.getAbsolutePath().endsWith(".jpg")
|| f.getAbsolutePath().endsWith(".bmp")
|| f.getAbsolutePath().endsWith(".png")
|| f.isDirectory())
return true;
else
return false;
}

public String getDescription(){


return "Image files - (.jpg, .png, .bmp)";
}
};
fchooser.addChoosableFileFilter(filter);
fchooser.setAcceptAllFileFilterUsed(false);
fchooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

int returnVal = fchooser.showOpenDialog(null);


if(returnVal == JFileChooser.APPROVE_OPTION) {
//load the image now
try{
BufferedImage image = ImageIO.read(fchooser.getSelectedFile());
theResizer = new Resizer(cloneOfMe,
fchooser.getSelectedFile().getName(), image);
theResizer.setBrushType(brushType);
theResizer.setBrushSize(brushSize);
imgWidth.setValue(image.getWidth());
imgHeight.setValue(image.getHeight());
theResizer.requestFocus();
//all done :)
}catch(Exception e){
//print an error...
JOptionPane.showMessageDialog(null,
"ERROR: Could not open image file!",
"Error!",
JOptionPane.ERROR_MESSAGE);
theResizer = null;
}
}
}
});

//save button
JButton saveImage = new JButton("Save Image");
saveImage.setPreferredSize(new Dimension(200, 30));
saveImage.setMinimumSize(saveImage.getPreferredSize());
saveImage.setMaximumSize(saveImage.getPreferredSize());
saveImage.setToolTipText("Save resized image");
saveImage.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
if(theResizer == null){
//can't save anything when there's nothing open!
JOptionPane.showMessageDialog(null,
"ERROR: You must open an image first!",
"Error!",
JOptionPane.ERROR_MESSAGE);
return;
}

JFileChooser fchooser = new JFileChooser();


FileFilter jpgfilter = new FileFilter(){
public boolean accept(File f){
if(f.getAbsolutePath().endsWith(".jpg")
|| f.isDirectory())
return true;
else
return false;
}

public String getDescription(){


return "JPG files - (.jpg)";
}
};
FileFilter bmpfilter = new FileFilter(){
public boolean accept(File f){
if(f.getAbsolutePath().endsWith(".bmp")
|| f.isDirectory())
return true;
else
return false;
}

public String getDescription(){


return "Bitmap files - (.bmp)";
}
};

FileFilter pngfilter = new FileFilter(){


public boolean accept(File f){
if(f.getAbsolutePath().endsWith(".png")
|| f.isDirectory())
return true;
else
return false;
}

public String getDescription(){


return "PNG files - (.png)";
}
};

fchooser.addChoosableFileFilter(pngfilter);
fchooser.addChoosableFileFilter(bmpfilter);
fchooser.addChoosableFileFilter(jpgfilter);
fchooser.setAcceptAllFileFilterUsed(false);
fchooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

int returnVal = fchooser.showSaveDialog(null);


if(returnVal == JFileChooser.APPROVE_OPTION) {
try{
File outputFile = fchooser.getSelectedFile();
FileFilter selected = fchooser.getFileFilter();
String formatname = outputFile.getName();
if(selected == jpgfilter && !formatname.endsWith(".jpg"))
formatname = formatname + ".jpg";
if(selected == pngfilter && !formatname.endsWith(".png"))
formatname = formatname + ".png";
if(selected == bmpfilter && !formatname.endsWith(".bmp"))
formatname = formatname + ".bmp";
outputFile = new File(outputFile.getParent()
+ System.getProperty("file.separator")
+ formatname);

formatname = formatname.substring(formatname.length() - 3,
formatname.length());
ImageIO.write(theResizer.getImage(), formatname, outputFile);
theResizer.requestFocus();
}catch(Exception e){
JOptionPane.showMessageDialog(null,
"ERROR: Could not save image file!",
"Error!",
JOptionPane.ERROR_MESSAGE);
}
}
}
});

//filter selection
Vector<String> filters = new Vector<String>();
filters.add("Sobel");
filters.add("Laplace");
filters.add("Prewitt");
theFilters = new JComboBox(filters);
theFilters.setPreferredSize(new Dimension(200, 30));
theFilters.setMinimumSize(theFilters.getPreferredSize());
theFilters.setMaximumSize(theFilters.getPreferredSize());
theFilters.setToolTipText("Select a filter to use for resizing");

Vector<String> pauses = new Vector<String>();


pauses.add("0");
pauses.add("0.2");
pauses.add("0.5");
pauses.add("1");
pauses.add("2");
pauses.add("5");
pauses.add("10");
pauses.add("60");
pauseTimes = new JComboBox(pauses);
pauseTimes.setPreferredSize(new Dimension(200, 30));
pauseTimes.setMinimumSize(pauseTimes.getPreferredSize());
pauseTimes.setMaximumSize(pauseTimes.getPreferredSize());
pauseTimes.setToolTipText("Select a time to pause to show seams");

//add the buttons


JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
buttonPanel.add(loadImage);
buttonPanel.add(saveImage);
buttonPanel.setBorder(new TitledBorder("Operations"));

JPanel filterPanel = new JPanel();


filterPanel.setLayout(new BoxLayout(filterPanel, BoxLayout.Y_AXIS));
filterPanel.add(theFilters);
filterPanel.setBorder(new TitledBorder("Filters"));

JPanel pausePanel = new JPanel();


pausePanel.setLayout(new BoxLayout(pausePanel, BoxLayout.Y_AXIS));
pausePanel.add(pauseTimes);
pausePanel.setBorder(new TitledBorder("Pause to show seams (seconds)"));

//now the preserve panel


JPanel preservePanel = new JPanel();
preservePanel.setLayout(new BoxLayout(preservePanel, BoxLayout.X_AXIS));
JButton preserveButton = new JButton("P");
preserveButton.setToolTipText("Select brush that marks areas of the image to preserve
when resizing");
preserveButton.setPreferredSize(new Dimension(45, 30));
preserveButton.setMinimumSize(preserveButton.getPreferredSize());
preserveButton.setMaximumSize(preserveButton.getPreferredSize());
JButton eraseButton = new JButton("E");
eraseButton.setToolTipText("Select brush that marks areas of the image to remove
first");
eraseButton.setPreferredSize(new Dimension(45, 30));
eraseButton.setMinimumSize(eraseButton.getPreferredSize());
eraseButton.setMaximumSize(eraseButton.getPreferredSize());
JButton nobrushButton = new JButton("N");
nobrushButton.setToolTipText("Select brush that erases brush strokes");
nobrushButton.setPreferredSize(new Dimension(45, 30));
nobrushButton.setMinimumSize(nobrushButton.getPreferredSize());
nobrushButton.setMaximumSize(nobrushButton.getPreferredSize());
JButton clearButton = new JButton("C");
clearButton.setToolTipText("Clear all brush strokes");
clearButton.setPreferredSize(new Dimension(45, 30));
clearButton.setMinimumSize(clearButton.getPreferredSize());
clearButton.setMaximumSize(clearButton.getPreferredSize());
preservePanel.add(preserveButton);
preservePanel.add(eraseButton);
preservePanel.add(nobrushButton);
preservePanel.add(clearButton);

final JLabel currentBrush = new JLabel("Current Brush: No Brush");


currentBrush.setHorizontalTextPosition(JLabel.CENTER);

//actions for the buttons


preserveButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
if(theResizer != null)
theResizer.setBrushType(OverlayPanel.BRUSH_PRESERVE);
currentBrush.setText("Current Brush: Preserve");
brushType = OverlayPanel.BRUSH_PRESERVE;
theResizer.requestFocus();
}
});
eraseButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
if(theResizer != null)
theResizer.setBrushType(OverlayPanel.BRUSH_ERASE);
currentBrush.setText("Current Brush: Erase");
brushType = OverlayPanel.BRUSH_ERASE;
theResizer.requestFocus();
}
});
nobrushButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
if(theResizer != null)
theResizer.setBrushType(OverlayPanel.BRUSH_NORMAL);
currentBrush.setText("Current Brush: No Brush");
brushType = OverlayPanel.BRUSH_NORMAL;
theResizer.requestFocus();
}
});
clearButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
if(theResizer != null){
int option = JOptionPane
.showConfirmDialog(null,
"This will clear all brush strokes, are you sure you
want to do this?",
"Clear brush strokes?",
JOptionPane.YES_NO_OPTION);

if(option == JOptionPane.NO_OPTION){
return;
}else
theResizer.clearBrushes();
theResizer.requestFocus();
}
}
});

//a spinner to select the brush size


SpinnerModel model =
new SpinnerNumberModel(brushSize, //initial value
1, //min
20, //max
1); //increment
final JSpinner bSize = new JSpinner(model);
((JSpinner.DefaultEditor)bSize.getEditor())
.getTextField().setEditable(false);
bSize.setPreferredSize(new Dimension(80,30));
bSize.setMinimumSize(bSize.getPreferredSize());
bSize.setMaximumSize(bSize.getPreferredSize());
bSize.setToolTipText("The size of the brush to draw on the image.");
JPanel bsPanel = new JPanel();
bsPanel.setLayout(new BoxLayout(bsPanel, BoxLayout.X_AXIS));
JLabel bsLabel = new JLabel("Brush Size: ");
bsLabel.setPreferredSize(new Dimension(120,30));
bsLabel.setMinimumSize(bsLabel.getPreferredSize());
bsLabel.setMaximumSize(bsLabel.getPreferredSize());
bsPanel.add(bsLabel);
bsPanel.add(bSize);
//spinner change listener
bSize.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent ce){
theResizer.setBrushSize((Integer)bSize.getValue());
theResizer.requestFocus();
}
});

JPanel brushPanel = new JPanel();


brushPanel.setLayout(new BoxLayout(brushPanel, BoxLayout.Y_AXIS));
brushPanel.add(bsPanel);
JPanel bspacer = new JPanel();
bspacer.setPreferredSize(new Dimension(10,10));
brushPanel.add(bspacer);
brushPanel.add(preservePanel);
JPanel cbrush = new JPanel();
cbrush.add(currentBrush);
brushPanel.add(cbrush);
brushPanel.setBorder(new TitledBorder("Brush Options"));

//retarget panel
JPanel retargetPanel = new JPanel();
retargetPanel.setLayout(new BoxLayout(retargetPanel, BoxLayout.Y_AXIS));
retargetPanel.setBorder(new TitledBorder("Retarget Image Size"));

SpinnerModel model1 =
new SpinnerNumberModel(3, //initial value
3, //min
2000, //max
1); //increment
imgWidth = new JSpinner(model1);
((JSpinner.DefaultEditor)imgWidth.getEditor())
.getTextField().setEditable(true);
imgWidth.setPreferredSize(new Dimension(80,30));
imgWidth.setMinimumSize(imgWidth.getPreferredSize());
imgWidth.setMaximumSize(imgWidth.getPreferredSize());

JPanel iwPanel = new JPanel();


iwPanel.setLayout(new BoxLayout(iwPanel, BoxLayout.X_AXIS));
JLabel iwLabel = new JLabel("Image Width: ");
iwLabel.setPreferredSize(new Dimension(120,30));
iwLabel.setMinimumSize(iwLabel.getPreferredSize());
iwLabel.setMaximumSize(iwLabel.getPreferredSize());
iwPanel.add(iwLabel);
iwPanel.add(imgWidth);

SpinnerModel model2 =
new SpinnerNumberModel(3, //initial value
3, //min
2000, //max
1); //increment
imgHeight = new JSpinner(model2);
((JSpinner.DefaultEditor)imgHeight.getEditor())
.getTextField().setEditable(true);
imgHeight.setPreferredSize(new Dimension(80,30));
imgHeight.setMinimumSize(imgHeight.getPreferredSize());
imgHeight.setMaximumSize(imgHeight.getPreferredSize());

JPanel ihPanel = new JPanel();


ihPanel.setLayout(new BoxLayout(ihPanel, BoxLayout.X_AXIS));
JLabel ihLabel = new JLabel("Image Height: ");
ihLabel.setPreferredSize(new Dimension(120,30));
ihLabel.setMinimumSize(ihLabel.getPreferredSize());
ihLabel.setMaximumSize(ihLabel.getPreferredSize());
ihPanel.add(ihLabel);
ihPanel.add(imgHeight);

JPanel sizeButtons = new JPanel();


sizeButtons.setLayout(new BoxLayout(sizeButtons, BoxLayout.X_AXIS));
JButton retargetButton = new JButton("Retarget");
retargetButton.setPreferredSize(new Dimension(90,30));
retargetButton.setMinimumSize(retargetButton.getPreferredSize());
retargetButton.setMaximumSize(retargetButton.getPreferredSize());
JButton eraseRButton = new JButton("Erase");
eraseRButton.setPreferredSize(new Dimension(90,30));
eraseRButton.setMinimumSize(eraseRButton.getPreferredSize());
eraseRButton.setMaximumSize(eraseRButton.getPreferredSize());
JPanel buttonSpacer = new JPanel();
buttonSpacer.setPreferredSize(new Dimension(20,10));
sizeButtons.add(eraseRButton);
sizeButtons.add(buttonSpacer);
sizeButtons.add(retargetButton);
retargetButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
//check the resizer is active
if(theResizer == null)
return;
if(!theResizer.isDisplayable()){
theResizer = null;
return;
}
//retarget the image
Thread retargeter = new Thread(){
public void run(){
try{
worker.show();
cloneOfMe.setVisible(false);
theResizer.setVisible(false);

//retarget
theResizer.retarget(((Integer)imgWidth.getValue()).intValue(),
((Integer)imgHeight.getValue()).intValue());

worker.hide();
cloneOfMe.setVisible(true);
theResizer.setVisible(true);
theResizer.requestFocus();
}catch(Exception e){
e.printStackTrace();
System.exit(1);
}
}
};

retargeter.start();

}
});

eraseRButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
//check the resizer is active
if(theResizer == null)
return;
if(!theResizer.isDisplayable()){
theResizer = null;
return;
}

//retarget the image


Thread retargeter = new Thread(){
public void run(){
try{
worker.show();
cloneOfMe.setVisible(false);
theResizer.setVisible(false);
//erase selected region the image
theResizer.eraseRegion(false);

worker.hide();
cloneOfMe.setVisible(true);
theResizer.setVisible(true);
theResizer.requestFocus();
}catch(Exception e){
e.printStackTrace();
System.exit(1);
}
}
};

retargeter.start();
}
});

retargetPanel.add(iwPanel);
retargetPanel.add(ihPanel);
retargetPanel.add(sizeButtons);

//main content pane


JPanel contentPane = new JPanel();
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
contentPane.setLayout(gridbag);
contentPane.setPreferredSize(new Dimension(220,530));

JLabel titleLabel = new JLabel("RANGE");


titleLabel.setFont(new Font("Arial",Font.BOLD, 16));

c.weightx = 0;
c.gridy = 0;
c.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(titleLabel,c);
contentPane.add(titleLabel);

JPanel spacerPanel2 = new JPanel();


spacerPanel2.setPreferredSize(new Dimension(10,10));
c.weightx = 0;
c.gridy = 1;
c.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(spacerPanel2,c);
contentPane.add(spacerPanel2);

c.weightx = 0;
c.gridy = 2;
c.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(buttonPanel,c);
contentPane.add(buttonPanel);

JPanel spacerPanel = new JPanel();


spacerPanel.setPreferredSize(new Dimension(10,10));
c.weightx = 0;
c.gridy = 3;
c.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(spacerPanel,c);
contentPane.add(spacerPanel);

c.weightx = 0;
c.gridy = 4;
c.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(filterPanel,c);
contentPane.add(filterPanel);

c.weightx = 0;
c.gridy = 5;
c.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(pausePanel,c);
contentPane.add(pausePanel);

c.weightx = 0;
c.gridy = 6;
c.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(brushPanel,c);
contentPane.add(brushPanel);

c.weightx = 0;
c.gridy = 7;
c.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(retargetPanel,c);
contentPane.add(retargetPanel);

JPanel spacerPanel3 = new JPanel();


spacerPanel3.setPreferredSize(new Dimension(10,20));
c.weightx = 0;
c.gridy = 8;
c.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(spacerPanel3,c);
contentPane.add(spacerPanel3);

JLabel helpLabel = new JLabel("Use the arrow keys to resize.");


c.weightx = 0;
c.gridy = 9;
c.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(helpLabel,c);
contentPane.add(helpLabel);

//setup the frame


this.setContentPane(contentPane);
this.pack();
this.setResizable(false);
this.setLocation(150,150);
this.setVisible(true);
}

//FUNCTIONS

/**
* Gets the currently selected filter.
*
* @return The currently selected filter.
*/
public Filter getSelectedFilter(){
try{
return (Filter)Class.forName((String)theFilters.getSelectedItem())
.newInstance();
}catch(Exception exp){
exp.printStackTrace();
System.exit(1);
}
return null;
}

/**
* Gets the time to pause for to show the seams.
*
* @return The time to pause and show the seams.
*/
public int getPause(){
String stime = (String)pauseTimes.getSelectedItem();
double itime = Double.parseDouble(stime);
return (int)(itime * 1000);
}

/**
* Sets the values in the image size spinners.
*
* @param width The new width.
* @param height The new height.
*/
public void setImageSize(int width, int height){
imgWidth.setValue(width);
imgHeight.setValue(height);
}

//MAIN FUNCTION

/**
* Creates a new image resizer, ready to resize
* images.
*
*/
public static void main(String[] args){
//start up a gui window and we're away!
try{
final ImageResizer IR = new ImageResizer();

//monitor the memory so we can exit gracefully...


Thread memMonitor = new Thread(){
public void run() {
while(true) {
try {
Thread.sleep(3000);
System.gc();

if((Runtime.getRuntime().maxMemory() -
Runtime.getRuntime().totalMemory()) <
m_initialJVMSize+300000) {

IR.dispose();

System.gc();

//gp through all the java threads and kill them off...
Thread [] theGroup = new Thread[Thread.activeCount()];
Thread.enumerate(theGroup);
for(int i = 0; i < theGroup.length; i++) {
Thread t = theGroup[i];
if(t!=null) {
if(t!=Thread.currentThread()) {
if(t.getName().startsWith("Thread")) {
t.interrupt();
}
else if(t.getName().startsWith("AWT-
EventQueue")) {
t.interrupt();
}
}
}
}
theGroup=null;

JOptionPane.showMessageDialog(null,
"Not enough memory. \nPlease load
"+
"a smaller image or use "+
"larger heap size by setting the " +
"-Xmx flag on the JVM." +
"\nThe program will now exit.",
"Out Of Memory",

JOptionPane.WARNING_MESSAGE);
System.err.println("Not enough memory. Please load a smaller
"+
"image or use larger heap size.");
System.err.println("Now exiting...");
System.exit(-1);
}
} catch(InterruptedException ex) {
ex.printStackTrace();
}
}//end while block
}//end run function
};//end thread function
memMonitor.setPriority(Thread.NORM_PRIORITY);
memMonitor.start();
} catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}
}

You might also like