Polygon shape does not show up in Java - java

I'm trying to make some shapes with Java, I created two rectangles and they show up normally, but lately I integrated a polygon shape code but it not showing up while running the program. Somebody help in this please!
Here is a screenshot after running:
Here is the code I use:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class shapes extends JPanel{
int midX = 120;
int midY = 60;
int radius[] = {118,40,90,40};
int nPoints = 16;
int[] X = new int[nPoints];
int[] Y = new int[nPoints];
int i;
double max;
public void paintComponent(Graphics gphcs){
super.paintComponent(gphcs);
this.setBackground(Color.WHITE);
gphcs.setColor(Color.BLUE);
gphcs.fillRect(25,25,100,30);
gphcs.setColor(Color.GRAY);
gphcs.fillRect(25,65,100,30);
gphcs.setColor(new Color(190,81,215));
gphcs.drawString("This is my text", 25, 120);
for (double current=0.0; i<nPoints; i++)
{
double x = Math.cos(current*((2*Math.PI)/max))*radius[i % 4];
double y = Math.sin(current*((2*Math.PI)/max))*radius[i % 4];
X[i] = (int) x+midX;
Y[i] = (int) y+midY;
}
gphcs.setColor(Color.RED);
gphcs.fillPolygon(X, Y, nPoints);
}
}
Acutally I wanted the polygon to show up as a star shape but it even didn't appear at all!
Thank you..

All your polygon co-ordinates are the same. Try
for (int i=0; i < nPoints; i++) {
double x = Math.cos(i * ((2 * Math.PI) / nPoints)) * radius[i % 4];
double y = Math.sin(i * ((2 * Math.PI) / nPoints)) * radius[i % 4];
X[i] = (int) x + midX;
Y[i] = (int) y + midY;
}

Related

Java hsb degrees or 255

I was wondering if when you call color.HSBtoRGB if the hue value would be entered as a range of 0-255, 0-1, 0-360? I am inquiring because I am trying to convert an edge angle to a color but it is only giving me blue or purple? can anyone explain what I am doing?
public void sobelGrey(){
this.greyScale();
double edgex;
double edgey;
Picture pi = new Picture(this.getWidth(), this.getHeight());
Picture tou = new Picture(this.getWidth(), this.getHeight());
Pixel[][] Y = pi.getPixels2D();
Pixel[][] X = tou.getPixels2D();
Pixel[][] h = this.getPixels2D();
for (int y = 1; y< X.length-1; y++){
for(int x= 1; x<X[1].length-1; x++){
edgex =
h[y-1][x-1].getRed() * -1 +
h[y][x-1].getRed() * -2+
h[y+1][x-1].getRed() * -1+
h[y-1][x+1].getRed() * 1 +
h[y][x+1].getRed() * 2+
h[y+1][x+1].getRed() * 1;
Y[y][x].setRed((int)Math.abs(edgex/2));
Y[y][x].setGreen((int)Math.abs(edgex/2));
Y[y][x].setBlue((int)Math.abs(edgex/2));
}
}
for (int y = 1; y< X.length-1; y++){
for(int x= 1; x<X[1].length-1; x++){
edgex =
h[y-1][x-1].getRed() * -1 +
h[y-1][x].getRed() * -2+
h[y-1][x+1].getRed() * -1+
h[y+1][x-1].getRed() * 1 +
h[y+1][x].getRed() * 2+
h[y+1][x+1].getRed() * 1;
X[y][x].setRed((int)Math.abs(edgex/2));
X[y][x].setGreen((int)Math.abs(edgex/2));
X[y][x].setBlue((int)Math.abs(edgex/2));
}
}
for (int y = 1; y< X.length-1; y++){
for(int x= 1; x<X[1].length-1; x++){
int x1 = (int) Math.sqrt(Math.pow(X[y][x].getRed(), 2) + Math.pow(X[y][x].getGreen(), 2) + Math.pow(X[y][x].getBlue(), 2));
int y1 = (int) Math.sqrt(Math.pow(Y[y][x].getRed(), 2) + Math.pow(Y[y][x].getGreen(), 2) + Math.pow(Y[y][x].getBlue(), 2));
int hr = (int) (200/(2*Math.PI)*(Math.tanh(y1/ (x1+.000000000000001))));
int rgb = Color.HSBtoRGB(hr/255, hr, (int) Math.sqrt(Math.pow(x1, 2) + Math.pow(y1, 2)));
Color fixed = new Color(rgb&0xFF*7/10, (rgb>>8)&0xFF*80/255/10, (rgb>>16)&0xFF*4/10);
if( !(Math.sqrt(Math.pow(x1, 2) + Math.pow(y1, 2))< 40))
h[y][x].setColor(fixed);
else
h[y][x].setColor(Color.black);
}
}
pi.explore();
tou.explore();
explore();
}
i am using a computer science AP image processing from Eimacs, and using the swan
You declared hr (and the other variables) to be an int. Then in Color.HSBtoRGB(hr/255, ... you divide an int by an int. For all values of hr below 255, the result will be 0.
Probably it is sufficient to divide by 255.0 to force a floating point division.

Convert an image to cylindrical shape in java

I didn't find any examples in openCV to convert a flat image to cylindrical in java, I want it to render the image in 2d not 3d, also didn’t find any example code or book on it. Below is the image of pictures which I want to warp around a cup.
A good book and example code will be much appreciated.
This i have done so far. suggested my #Amitay to make image concave, using this example Wrap image around cylinder but stuck on convertion.
import java.io.File;
import org.bytedeco.javacpp.indexer.UByteBufferIndexer;
import org.bytedeco.javacpp.opencv_core.Mat;
import org.bytedeco.javacpp.opencv_core.*;
import static org.bytedeco.javacpp.opencv_highgui.imshow;
import static org.bytedeco.javacpp.opencv_highgui.waitKey;
import static org.bytedeco.javacpp.opencv_imgcodecs.CV_LOAD_IMAGE_COLOR;
import static org.bytedeco.javacpp.opencv_imgcodecs.imread;
/**
*
* #author BTACTC
*/
public class CupWrapping {
Mat image;
Mat dstImage;
int width;
int height;
public CupWrapping(File imageFile) {
image = imread(imageFile.getAbsolutePath(), CV_LOAD_IMAGE_COLOR);
width = image.size().width();
height = image.size().height();
dstImage = new Mat(width, height, image.type());
UByteBufferIndexer sI = image.createIndexer();
UByteBufferIndexer sD = dstImage.createIndexer();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
Point2f current_pos = new Point2f(x, y);
current_pos = convert_pt(current_pos, width, height);
Point top_left = new Point((int) current_pos.x(), (int) current_pos.y()); //top left because of integer rounding
//make sure the point is actually inside the original image
if (top_left.x() < 0
|| top_left.x() > width - 2
|| top_left.y() < 0
|| top_left.y() > height - 2) {
continue;
}
//bilinear interpolation
float dx = current_pos.x() - top_left.x();
float dy = current_pos.y() - top_left.y();
float weight_tl = (float) ((1.0 - dx) * (1.0 - dy));
float weight_tr = (float) ((dx) * (1.0 - dy));
float weight_bl = (float) ((1.0 - dx) * (dy));
float weight_br = (dx) * (dy);
byte value = (byte) (weight_tl * sI.get(top_left.y(), top_left.x())
+ weight_tr * sI.get(top_left.y(), top_left.x() + 1)
+ weight_bl * sI.get(top_left.y() + 1, top_left.x())
+ weight_br * sI.get(top_left.y() + 1, top_left.x() + 1));
sD.put(y, x,value);
}
}
imshow("", dstImage);
waitKey(0);
}
public Point2f convert_pt(Point2f point, int w, int h) {
//center the point at 0,0
Point2f pc = new Point2f(point.x() - w / 2, point.y() - h / 2);
//these are your free parameters
float f = w;
float r = w;
float omega = w / 2;
float z0 = (float) (f - Math.sqrt(r * r - omega * omega));
float zc = (float) ((2 * z0 - Math.sqrt(4 * z0 * z0 - 4 * (pc.x() * pc.x() / (f * f) + 1) * (z0 * z0 - r * r))) / (2 * (pc.x() * pc.x() / (f * f) + 1)));
Point2f final_point = new Point2f(pc.x() * zc / f, pc.y() * zc / f);
final_point.x() = final_point.x() + w / 2;
final_point.y() += h / 2;
return final_point;
}
public static void main(String[] args) {
File imageFile = new File("image/C13.jpg");
CupWrapping wrap = new CupWrapping(imageFile);
}
}
Look at this answer in Warp Image to Appear in Cylindrical Projection
You only need to change two things:
Because you want convex projection and not concave you need to change the line of code in the function convert_pt.
From:
float zc = (2*z0+sqrt(4*z0*z0-4*(pc.x*pc.x/(f*f)+1)*(z0*z0-r*r)))/(2* (pc.x*pc.x/(f*f)+1));
To
float zc = (2*z0-sqrt(4*z0*z0-4*(pc.x*pc.x/(f*f)+1)*(z0*z0-r*r)))/(2* (pc.x*pc.x/(f*f)+1));
Convert the all the rest of the code form c++ to java.
Good luck

Java - plotting sine waves

I am using the following code to generate a sine wave:
The speed of this animation is slow-fast-slow.
Code:
public static final double SINE_TO_180 = 114.58865012930961, TIMES = 180, SINE_OF_90 = Math.sin(Math.toRadians(90));
public static void main(String[] args) throws Exception{
float velc = 200;
float angle = 45;
float resistance = 0f;
double multiple = (velc * 2.5 / SINE_TO_180);
int offset = 0;
double y = 0;
double x = 0;
double h = 0;
double cos = Math.cos(Math.toRadians(angle));
double sin = Math.sin(Math.toRadians(angle));
for(int i = offset; i < TIMES + 1 + offset; i ++){
y += ((Math.sin(Math.toRadians(i * 2)))) * multiple * sin;
if(y >= h)
h = y;
x += Math.sin(Math.toRadians(i)) * multiple * ((1 - resistance) * 1.5) * Math.abs(cos);
// x += multiple * cos;
// if(i + offset < TIMES / 2){
// x += Math.sin(Math.toRadians(i)) * multiple * ((1 - resistance) * 1.5);
// }else{
// x += Math.sin(Math.toRadians(TIMES / 2)) * multiple * (1 - resistance);
// }
}
y = Math.round(y);
//do round x?
x = Math.round(x);
System.out.println("X: " + x);
JFrame frm = new JFrame("Projectile!");
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BufferedImage b = new BufferedImage((int)x + 1, (int)h + 1, BufferedImage.TYPE_INT_RGB);
Graphics g = b.getGraphics();
y = 0;
x = 0;
JLabel l = new JLabel(new ImageIcon(b));
frm.add(l);
frm.pack();
frm.setVisible(true);
for(int i = offset; i < TIMES + 1 + offset; i ++){
y += ((Math.sin(Math.toRadians(i * 2)))) * multiple * sin;
x += Math.sin(Math.toRadians(i)) * multiple * ((1 - resistance) * 1.5) * Math.abs(cos);
// x += multiple * cos;
// if(i + offset < TIMES / 2){
// x += Math.sin(Math.toRadians(i)) * multiple * ((1 - resistance) * 1.5);
// }else{
// x += Math.sin(Math.toRadians(TIMES / 2)) * multiple * (1 - resistance);
// }
g.setColor(Color.red);
g.drawLine((int)x, (int)(h - y), (int)x, (int)(h - y));
l.setIcon(new ImageIcon(b));
frm.repaint();
Thread.sleep((int)(1000.0 / 24.0));
}
ImageIO.write(b, "png", new File("C:\\proj.png"));
}
Now I would like to change the sine animation to fast-slow-fast where it is slow at its peak so I tried the following result and got this: I would expect it to be the same just the animation speed different. Code:
public static void main(String[] args) throws Exception{
float velc = 200;
float angle = 45;
float resistance = 0f;
double multiple = (velc * 2.5 / SINE_TO_180);
int offset = 0;
double y = 0;
double x = 0;
double h = 0;
double cos = Math.cos(Math.toRadians(angle));
double sin = Math.sin(Math.toRadians(angle));
for(int i = offset; i < TIMES + 1 + offset; i ++){
y += (1 - Math.sin(Math.toRadians(i * 2))) * multiple * sin;
if(y >= h)
h = y;
// x += Math.sin(Math.toRadians(i)) * multiple * ((1 - resistance) * 1.5) * Math.abs(cos);
x += 2;
// x += multiple * cos;
// if(i + offset < TIMES / 2){
// x += Math.sin(Math.toRadians(i)) * multiple * ((1 - resistance) * 1.5);
// }else{
// x += Math.sin(Math.toRadians(TIMES / 2)) * multiple * (1 - resistance);
// }
}
y = Math.round(y);
//do round x?
x = Math.round(x);
System.out.println("X: " + x);
JFrame frm = new JFrame("Projectile!");
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BufferedImage b = new BufferedImage((int)x + 1, (int)h + 1, BufferedImage.TYPE_INT_RGB);
Graphics g = b.getGraphics();
y = 0;
x = 0;
JLabel l = new JLabel(new ImageIcon(b));
frm.add(l);
frm.pack();
frm.setVisible(true);
for(int i = offset; i < TIMES + 1 + offset; i ++){
y += (1 - Math.sin(Math.toRadians(i * 2))) * multiple * sin;
x += 2;
// x += Math.sin(Math.toRadians(i)) * multiple * ((1 - resistance) * 1.5) * Math.abs(cos);
// x += multiple * cos;
// if(i + offset < TIMES / 2){
// x += Math.sin(Math.toRadians(i)) * multiple * ((1 - resistance) * 1.5);
// }else{
// x += Math.sin(Math.toRadians(TIMES / 2)) * multiple * (1 - resistance);
// }
g.setColor(Color.red);
g.drawLine((int)x, (int)(h - y), (int)x, (int)(h - y));
l.setIcon(new ImageIcon(b));
frm.repaint();
Thread.sleep((int)(1000.0 / 24.0));
}
ImageIO.write(b, "png", new File("C:\\proj2.png"));
}
Anyone know what I am doing wrong because I expect the result to be the same as the first just different animation speeds?
if you want to have a smooth animation i would seperate the data and the animation;
first create your data - it is a (mathematical) function [meaning f(x)->y], so you can simply use an array for data
private int endOfX = 100; //adjust as you wish
private int[] data;
public void calculateData(){
data = new int[amendOfX ountPixels];
for(int x = 0; x < endOfX ; x++){
y = x*x; //this is an example, use your mathematical function here
}
}
so - now you can easily use this data to provide a smooth animation
public class AnimationOfFunction(){
public static void main(String[] args){
new AnimationOfFunktion().createAndShowGui(); //as from java tutorials
}
private BufferedImage img;
private Graphics gr;
private void createAndShowGui(){
calculateData(); first of all we create the data!
JFrame frame = new JFrame();//then create your frame here
JPanel panel = createContent(); //create your drawing panel here
frame.add(panel);//adding drawing panel
frame.pack(); //setting the proper size of frame
frame.setVisible(true); //show frame
startAnimation(panel); //this is important - after showing the frame you start your animation here!
}
}
so - this would be the start of you application, what to do now? first create a proper drawing panel:
private JPanel createContent(){
//create a anonym class
#surpress serial
JPanel panel = new JPanel(){
#override
public void paintComponent(Graphics gr){
super.paintComponent(gr);
gr.drawImage(img, 0,0, null);
}
}
panel.setPreferredSize(new Dimension(img.getWidth(), img.getHeight() ));
return panel;
}
and most important - you have to start the animation:
private void startAnimation(final JPanel panel){
//create a anonym class
Runnable r = new Runnable(){
private int py = 0; //previous values
private int py = 0; //previous values
#overrdie
public void run(){
for(int x = 0; x < endOfX ; x++){
int y = data[x];
//now we have x and y, so you can plot your function;
gr.drawLine(px, py, x,y); //you can scale here
int sleeptime = calculateSleepTime(px,py, x,y);
Thread.sleep(sleeptime);
//set the previouse values;
px = x;
py = y;
//important - repaint your panel to create an 'animation'
panel.repaint();
}
}
}
//having that runnable we must start that runnable within an thread
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.start();
}
so whats left to do? we must calculate the sleep time: if the distance between two points is 'big' we sleep longer, if the distance is short, we sleep less...
public int calculateSleeptime(int px, int py, int x, int y){
int distance = (y-py)*(y-py)+(x-px)*(x-px);
distance = (int)(Math.sqrt(distance);
int sleepTime = distance*100; //play with this value!
return sleeptime;
}
I have written that code all out of my head, i didn't have any IDE to check if it contains any spelling errors or compiling errors, please do that for yourself, as well as i didn't initiate the BufferedImage img ang Graphics gr. but obvious you can do that already!

how to build a brick pryramid using nested for loops

I'm working on a problem I'm having lots of trouble with. The concept of the question is to build a pyramid using bricks. The entire pyramid of bricks is centered in the window. I can draw one brick, then two, then three all the way up until 12 which makes up the base of the pyramid but all of the bricks are alined on the left edge on the left of the window instead of being centered in the window.
Using getWidth() and getHeight() i can do (getWidth()-BRICK_WIDTH) / 2; to get the center for the x coordinate of the brick. And then (getHeight() -BRICK_HEIGHT) / 2; for the center of the y coordinate of one brick. The only problem is i don't understand where to enter that code so it applies to all the bricks so each row of bricks is centered in the window.
import acm.program.*;
import acm.graphics.*;
public class Pyramid extends GraphicsProgram {
public void run() {
double xCoordinate = (getWidth() - BRICKWIDTH) / 2;
double yCoordinate = (getHeight() - BRICK_HEIGHT / 2);
for (int i = 0; i < BRICKS_IN_BASE; i++) {
for (int j = 0; j < i; j++) {
double x = j * BRICK_WIDTH;
double y = i * BRICK_HEIGHT;
GRect square = new GRect(x, y, BRICK_WIDTH, BRICK_HEIGHT);
add(square);
}
}
}
private static final int BRICK_WIDTH = 50;
private static final int BRICK_HEIGHT = 25;
private static final int BRICKS_IN_BASE = 12;
}
You should try something like this :
import acm.program.*;
import acm.graphics.*;
public class Pyramid extends GraphicsProgram
{
public void run()
{
// We calculate some values in order to center the pyramid vertically
int pyramidHeight = BRICKS_IN_BASE * BRICK_HEIGHT;
double pyramidY = (getHeight() - pyramidHeight) / 2;
// For each brick layer...
for (int i=BRICKS_IN_BASE ; i >= 1; i--)
{
// We calculate some values in order to center the layer horizontally
int layerWidth = BRICKWIDTH * i;
double layerX = (getWidth() - layerWidth) / 2;
double layerY = pyramidY + (i-1) * BRICK_HEIGHT;
// For each brick in the layer...
for(int j=0 ; j<i ; j++)
{
GRect square = new GRect(layerX + j*BRICK_WIDTH, layerY, BRICK_WIDTH, BRICK_HEIGHT);
add(square);
}
}
}
private static final int BRICK_WIDTH = 50;
private static final int BRICK_HEIGHT = 25;
private static final int BRICKS_IN_BASE = 12;
}
In this implementation, we first calculate the global width of the layer (because we already know how many bricks there will be in it) and we use it to find a global "point of start" of the layer, from which we find all the coordinates for all the rectangles.
You mean something like that?
double x = xCoordinate + j * BRICK_WIDTH;
double y = yCoordinate + i * BRICK_HEIGHT;

Java Perlin Noise Implementation Problems

Hey stackoverflow community! I have been reading about perlin noise for the past 2 weeks and tried implementing it on my own in the most basic way. Even so, my program does not work. It outputs near similar looking results all the time and the persistence does not seem to change anything. Here is my code:
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Noise extends JPanel{
public static int octaves = 4;
public static int size = 128;
public static float[][][] noise = new float[size][size][octaves];
public static float[][] perlinnoise = new float[size][size];
public static float p = (float) 1/4;
public static Random gen = new Random();
public static float GenerateNoise() {
return gen.nextFloat();
}
public static float SmoothNoise(int x, int y, int z) {
try{
float corners = (noise[x - 1][y - 1][z] + noise[x + 1][y - 1][z] + noise[x - 1][y + 1][z] + noise[x + 1][y + 1][z]) / 16;
float sides = (noise[x - 1][y][z] + noise[x + 1][y][z] + noise[x][y - 1][z] + noise[x][y + 1][z]) / 8;
float center = noise[x][y][z] / 4;
return corners + sides + center;
}catch(Exception e) {
return 0;
}
}
public static float InterpolatedNoise(float x, float y, int pX, int pY, int pZ) {
int intX = (int) x;
int intY = (int) y;
float fracX = x - intX;
float fracY = y - intY;
float v1 = SmoothNoise(pX, pY, pZ);
float v2 = SmoothNoise(pX + 1, pY, pZ);
float v3 = SmoothNoise(pX, pY + 1, pZ);
float v4 = SmoothNoise(pX + 1, pY + 1, pZ);
float i1 = Interpolate(v1, v2, fracX);
float i2 = Interpolate(v3, v4, fracX);
return Interpolate(i1, i2, fracY);
}
public static float Interpolate(float a, float b, float x) {
float ft = (float) (x * 3.1415927);
float f = (float) ((1 - Math.cos(ft)) * 0.5);
return (float) (a * (1 - f) + b * f);
}
public static float Perlin2D(float x, float y, int posX, int posY, int posZ) {
float total = 0;
for(int i = 0; i < octaves; i++) {
double f = Math.pow(2, i);
double a = Math.pow(p, i);
total = (float) (total + InterpolatedNoise((float)(x * f), (float)(y * f), posX, posY, posZ) * a);
}
return total;
}
public static void main(String [] args) {
for(int z = 0; z < octaves; z++) {
for(int y = 0; y < size; y++) {
for(int x = 0; x < size; x++) {
noise[x][y][z] = GenerateNoise();
}
}
}
for(int z = 0; z < octaves; z++) {
for(int y = 0; y < size; y++) {
for(int x = 0; x < size; x++) {
perlinnoise[x][y] = Perlin2D(x / (size - 1), y / (size - 1), x, y, z) / octaves;
}
}
}
JFrame f = new JFrame("Perlin Noise");
f.setSize(400, 400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new Noise());
f.setVisible(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(int y = 0; y < size; y++) {
for(int x = 0; x < size; x++) {
g.setColor(new Color(perlinnoise[x][y], perlinnoise[x][y], perlinnoise[x][y]));
g.fillRect(x * 2, y * 2, 2, 2);
}
}
repaint();
}
}
I do not understand why it is not working because it is exactly as the pseudo code in this article said to do it. Can anyone assist me in figuring this out? Thanks.
EDIT: Ok please can someone just explain the process required to do this PLEASE I am going crazy trying to figure this out. I have been trying to figure it out for the past 2 weeks and no one is giving me any help with it. Please if you know how to do this, please just explain it to me I would greatly appreciate it. Thanks.

Categories

Resources