OpenCV color detection in yellow - java

This is a program from OpenCV ColorBlobDetectionActivity.java sample, and I tried to modify it so that it would detect yellow objects when the screen is touched, but it always detects black object only even though I specified the color Scalar to be yellow. I have put comments of "NOTICE" in the places where I think would be relevant.
package com.example.road_guiding;
import java.util.List;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class ColorBlobDetectionActivity extends Activity implements View.OnTouchListener, CameraBridgeViewBase.CvCameraViewListener2 {
// private static final String TAG = "OCVSample::Activity";
private Scalar CONTOUR_COLOR;
private Scalar mBlobColorHsv;
private Scalar mBlobColorRgba;
//NOTICE
private Scalar temp;
private ColorBlobDetector mDetector;
private boolean mIsColorSelected = false;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
public void onManagerConnected(int paramAnonymousInt) {
switch (paramAnonymousInt) {
default:
super.onManagerConnected(paramAnonymousInt);
// Log.i("OCVSample::Activity", "OpenCV loaded successfully");
ColorBlobDetectionActivity.this.mOpenCvCameraView.enableView();
ColorBlobDetectionActivity.this.mOpenCvCameraView.setOnTouchListener(ColorBlobDetectionActivity.this);
return;
}
}
};
private CameraBridgeViewBase mOpenCvCameraView;
private Mat mRgba;
// private Size SPECTRUM_SIZE;
// private Mat mSpectrum;
public ColorBlobDetectionActivity() {
Log.i("OCVSample::Activity", "Instantiated new " + getClass());
}
private Scalar converScalarHsv2Rgba(Scalar paramScalar) {
Mat localMat = new Mat();
Imgproc.cvtColor(new Mat(1, 1, CvType.CV_8UC3, paramScalar), localMat, 71, 4);
return new Scalar(localMat.get(0, 0));
}
public Mat onCameraFrame( CameraBridgeViewBase.CvCameraViewFrame paramCvCameraViewFrame) {
this.mRgba = paramCvCameraViewFrame.rgba(); // mRbga = input frame with color
if (this.mIsColorSelected) {
this.mDetector.process(this.mRgba);
//contour info is ready in detector
List colorContour = this.mDetector.getContours();
// Log.e("OCVSample::Activity", "Contours count: " + localList.size());
Imgproc.drawContours(this.mRgba, colorContour, -1, this.CONTOUR_COLOR); //draw contour around detected area
this.mRgba.submat(4, 68, 4, 68).setTo(this.mBlobColorRgba);
// Producing spectrum
// Mat localMat = this.mRgba.submat(4, 4 + this.mSpectrum.rows(), 70, 70 + this.mSpectrum.cols());
// this.mSpectrum.copyTo(localMat);
}
return this.mRgba;
}
public void onCameraViewStarted(int paramInt1, int paramInt2) {
this.mRgba = new Mat(paramInt2, paramInt1, CvType.CV_8UC4); //width - - the width of the frames that will be delivered
this.mDetector = new ColorBlobDetector();
this.mBlobColorRgba = new Scalar(255.0);
this.mBlobColorHsv = new Scalar(255.0);
this.CONTOUR_COLOR = new Scalar(255.0, 0.0, 0.0, 255.0); //Specfiy the color of contour
//NOTICE
this.temp = new Scalar (237.0, 169.0, 50.0, 255.0);
//yellow to be used:
// this.mBlobColorRgba.val[0] = 237;
// this.mBlobColorRgba.val[1] = 169;
// this.mBlobColorRgba.val[2] = 50;
// this.mBlobColorRgba.val[3] = 255;
// this.mSpectrum = new Mat();
// this.SPECTRUM_SIZE = new Size(200.0, 64.0);
}
public void onCreate(Bundle paramBundle) {
// Log.i("OCVSample::Activity", "called onCreate");
super.onCreate(paramBundle);
// requestWindowFeature(1); // do not show app title
// getWindow().addFlags(128);
setContentView(R.layout.activity_color_blob_detection);
this.mOpenCvCameraView = ((CameraBridgeViewBase) findViewById(R.id.HelloOpenCvView));
this.mOpenCvCameraView.setCvCameraViewListener(this);
}
public boolean onTouch(View paramView, MotionEvent paramMotionEvent)
{
int cameraViewWidth = this.mRgba.cols(); // cameraViewWidth = i
int cameraViewHeight = this.mRgba.rows(); // cameraViewHeight = j
int xOffset = (this.mOpenCvCameraView.getWidth() - cameraViewWidth) / 2;
int yOffset = (this.mOpenCvCameraView.getHeight() - cameraViewHeight) / 2;
int touchX = (int)paramMotionEvent.getX() - xOffset;
int touchY = (int)paramMotionEvent.getY() - yOffset;
// Log.i("OCVSample::Activity", "Touch image coordinates: (" + n = touchX + ", " + i1=touchY + ")");
if ((touchX < 0) || (touchY < 0) || (touchX > cameraViewWidth) || (touchY > cameraViewHeight)) {
return false;
}
Rect touchedRect = new Rect();
if (touchX > 4) {
touchedRect.x = touchX - 4;
touchedRect.y = touchY - 4;
touchedRect.width = touchX + 4 - touchedRect.x;
}
for (int i5 = touchY + 4 - touchedRect.y;; i5 = cameraViewHeight - touchedRect.y) {
touchedRect.height = i5;
// Mat touchedRegionRgba = this.mRgba.submat(touchedRect);
Mat touchedRegionRgba = new Mat();
//NOTICE
Imgproc.cvtColor(new Mat(1, 1, CvType.CV_8UC3, temp), touchedRegionRgba, 71, 0);
Mat touchedRegionHsv = new Mat();
Imgproc.cvtColor(touchedRegionRgba, touchedRegionHsv, Imgproc.COLOR_RGB2HSV_FULL); //67
this.mBlobColorHsv = Core.sumElems(touchedRegionHsv); //calculate average color of touched region
int pixelCount = touchedRect.width * touchedRect.height;
for (int i = 0; i < this.mBlobColorHsv.val.length; i++) {
double[] arrayOfDouble = this.mBlobColorHsv.val;
arrayOfDouble[i] /= pixelCount;
}
touchedRegionRgba.release();
touchedRegionHsv.release();
break;
}
this.mBlobColorRgba = converScalarHsv2Rgba(this.mBlobColorHsv);
// Log.i("OCVSample::Activity", "Touched rgba color: (" + this.mBlobColorRgba.val[0] + ", " + this.mBlobColorRgba.val[1] + ", " + this.mBlobColorRgba.val[2] + ", " + this.mBlobColorRgba.val[3] + ")");
this.mDetector.setHsvColor(this.mBlobColorHsv);
// Imgproc.resize(this.mDetector.getSpectrum(), this.mSpectrum, this.SPECTRUM_SIZE);
this.mIsColorSelected = true;
return false;
}
public void onDestroy() {
super.onDestroy();
if (this.mOpenCvCameraView != null) {
this.mOpenCvCameraView.disableView();
}
}
public void onPause() {
super.onPause();
if (this.mOpenCvCameraView != null) {
this.mOpenCvCameraView.disableView();
}
}
public void onResume() {
super.onResume();
OpenCVLoader.initAsync("2.4.3", this, this.mLoaderCallback);
}
public void onCameraViewStopped() {
this.mRgba.release();
}
}
Any help would be appreciated, thanks!

Sorry i don't know Java but i can suggest the general logic to detect "Yellow" color. You should convert the RGB image into YUV image and then equalize the Y-channel. As Y-channel is for luminance, so you reduce the effects of illumination changes by doing so.
-Then convert back your image to RGB from YUV
-Convert the image to HSV now.
-Now try to calculate only those pixels which possibly represent "Yellow" color. For that, use the following conditions:
The pixel should have S>0 (or some other value near to 0) to eliminate the white pixels which create problem in the caculation.
The pixel should have V>0 to remove the "Black pixels" which have V=0
If the H> 22 && H<37 then increase the yellowPixelCount by 1.
-So, by following the above mentioned procedure, you can count the "yellow" pixels in the image. And, if the count is greater than the threshold then you can predict that it is "yellow" color.
PS: Don't forget to count the total number of pixel which fullfill the criteria 1 & 2 so that you can use that value to find the percentage of yellow component to predict whether the image has yellow color or not.
if (condition 1 & 2 satisfied)
{
totalPixelCount++;
if(condition 3 satisfied)
{
yellowPixelCount
}
}
% of yellow componet = yellowPixelCount/totalPixelCount*100

Related

How to change the number graphically when receiving data?

Good afternoon, I am using stm32 Blue Pill on USB raised com - port, development environment "IAR".
The problem is the following, when I connect through the application, the number "3"
does not change to the number "50" after the arrow, but on the contrary is shown next !
See Figure 1.2. I work under the protocol.
How do you achieve this?
I'm using the controlP5 library and cp5.addNumberbox.
Data in "IAR".
int Bullet = 50; // variable for result
sprintf((char *)str, "(,%d,-Ђ",Bullet); // sending a command with data to stm32.
In the code of the Displaydata tab, the line "case 40" is the symbol (
The command can also be sent through the terminal using a virtual com port.
Command: (, 50 ,! Figure 3.
I'll have to lay out the whole little project for you to check it out.
Com_Interface1:
import processing.serial.*;
import controlP5.*;
ControlP5 cp5;
DropdownList serialPortsList;
Serial serialPort;
final int BAUD_RATE = 9600;
char parity = 'N';
int dataBits = 8;
float stopBits = 1.0;
public void setup() {
background(50);
size(700, 420, P3D);
surface.setTitle("TEST");
surface.setResizable(false);
setupUI();
smooth();
frameRate(30);
writeOutgioing[lengthmas-1]=1;
String[] portNames = Serial.list();
//serialPort.clear(); // Why does not it work?
for (int i = 0; i < portNames.length; i++) serialPortsList.addItem(portNames[i], i);
}
public void toplug (int theValue)
{ // Start button on click sends a commad 1.
println("Button click events: "+theValue);
strata =!strata;
if (!strata) {
connection.setLabel("Пуск");
serialPort.dispose();
Vin.setText("Voltage K.V - ");
inputPULI.setLabel("Bullet");
} else {
connection.setLabel("СТОП");
serialports((int)serialPortsList.getValue());
writeOutgioing[0]=1;
writeOut();
}
}
public void serialports(int theValue) {
try {
serialPort = new Serial(this, Serial.list()[theValue], BAUD_RATE, parity, dataBits, stopBits);
serialPort.bufferUntil('\n');
println("COM connected: "+ Serial.list()[theValue] );
/*Send.unlock();
connection.unlock();*/ // locking buttons in applications if not connected via rs-232.
}
catch(Exception e) {
System.err.println("Error opening serial port" + Serial.list()[theValue]);
e.printStackTrace();
}
}
/*void controlEvent(ControlEvent event){
println(event.getController().getName(),"changed value to",event.getValue(),"inputPULI = ",PUL,"inputNapryzenieKV = ",NapryzenieKV,"CheckBoxuvum= ",
UV/UM,"P4 = ",std2,);
}*/
Displaydata:
void Displaydata() {
switch(x)
{
case 20:
// What to write?
// label(testRead[1]+" Мин."); // ImageButton
// min=testRead[1];
break;
case 30:
// What to write?
// P4.setText("std2"+ testRead[1]); // CheckBox
break;
case 40:
inputPULI.setLabel("Bullet: " + testRead[1] );
break;
case 70:
inputNapryzenieKV.setLabel("Voltage: " + testRead[1] );
break;
case 60:
Vin.setText("Voltage K.V: " + testRead[1] + " " + testRead[2]);
break;
case 50:
// What to write?
//CheckBoxuvum.setText("UV/UM - " +testRead[1] ); // RadioButton
break;
default:
println("DisplayData(): no case selected.");
break; // technically not necessary, but I like my switches tidy
}
}
GUI:
int PUL;
float NapryzenieKV;
boolean strata=false;
ImageButton button;
Numberbox inputPULI;
Numberbox inputNapryzenieKV;
RadioButton CheckBoxuvum;
CheckBox P4;
Textlabel Vin;
Button connection;
Button Send;
public void setupUI()
{
cp5 = new ControlP5(this);
PFont fontn = createFont("Times New Roman", 18);
PFont p = createFont("Times New Roman", 18);
ControlFont font=new
ControlFont(p);
cp5.setFont(font);
connection = cp5.addButton("toplug")
.setCaptionLabel("ПУСК")
.setPosition(387, 30)
.setSize(150, 30);
serialPortsList = cp5.addDropdownList("Порт")
.setPosition(130, 30)
.setSize(150, 200)
.setItemHeight(30)
.setBarHeight(30);
PImage[] imgs = {loadImage("button101.png"), loadImage("button102.png"), loadImage("button103.png")};
Send = cp5.addButton("toapply")
//.setCaptionLabel("Apply")
//.setPosition(510, 370)
//.setSize(150, 30);
.setPosition(590, 330)
.setImages(imgs)
.updateSize();
//.lock()
Vin = cp5.addTextlabel("naprazhenie kondencatora")
.setText("Voltage K.V")
.setFont(p)
.setColor(color(#00ffff))
.setPosition(45, 320);
CheckBoxuvum = cp5.addRadioButton("UV/UM")
.setPosition(155, 360)
.setSize(15, 15)
.setColorActive(color(255))
.setItemsPerRow(2)
.setSpacingColumn(85)
.addItem("+", 1)
.addItem("-", 2);
P4 = cp5.addCheckBox("std2")
.setPosition(150, 190)
.setSize(15, 15)
.setItemsPerRow(1)
.setSpacingColumn(30)
.setSpacingRow(20)
.addItem("Check", 2);
inputPULI = cp5.addNumberbox("PUL")
.setLabel("Bullet")
.setPosition(220, 220)
.setSize(80, 30)
.setColorValue(0xffffff00)
.setFont(p)
.setScrollSensitivity(1.1)
.setDirection(Controller.HORIZONTAL)
.setRange(1, 199)
.setValue(3);
Label labelinputPULI = inputPULI.getCaptionLabel();
labelinputPULI.setFont(font);
labelinputPULI.setColor(color(#00ffff));
labelinputPULI.toUpperCase(false);
labelinputPULI.setText("Bullet");
labelinputPULI.align(ControlP5.LEFT_OUTSIDE, CENTER);
labelinputPULI.getStyle().setPaddingLeft(-25);
inputNapryzenieKV = cp5.addNumberbox("NapryzenieKV")
.setLabel("Voltage")
.setPosition(150, 270)
.setSize(80, 30)
.setColorValue(0xffffff00)
.setFont(p)
.setScrollSensitivity(1.1)
.setMin(25)
.setMax(99)
.setMultiplier(0.01)
.setDirection(Controller.HORIZONTAL)
.setValue(25);
Label labelinputNapryzenieKV = inputNapryzenieKV.getCaptionLabel();
labelinputNapryzenieKV.setFont(font);
labelinputNapryzenieKV.setColor(color(#00ffff));
labelinputNapryzenieKV.toUpperCase(false);
labelinputNapryzenieKV.setText("Напряжение");
labelinputNapryzenieKV.align(ControlP5.LEFT_OUTSIDE, CENTER);
labelinputNapryzenieKV.getStyle().setPaddingLeft(-45);
textFont(fontn);
{
// button dimensions
int w = 99;
int h = 25;
// test with generated images
button = new ImageButton(555, 230, w, h,
new PImage[]{
loadImage("0.png"), // off
loadImage("1.png"), // 10
loadImage("2.png"), // 20
loadImage("3.png"), // 30
loadImage("4.png"), // 40
loadImage("5.png"), // 50
loadImage("6.png"), // 60
});
}
}
void mousePressed() {
button.mousePressed(mouseX, mouseY);
println(button.min);
}
// test images to represent loaded state images
PImage getImage(int w, int h, int c) {
PImage img = createImage(w, h, RGB);
java.util.Arrays.fill(img.pixels, c);
img.updatePixels();
return img;
}
// make a custom image button class
class ImageButton {
// minutes is the data it stores
int min = 0;
// images for each state
PImage[] stateImages;
// which image to display
int stateIndex;
// position
int x, y;
// dimensions: width , height
int w, h;
// text to display
String label = "ВЫКЛ";
ImageButton(int x, int y, int w, int h, PImage[] stateImages) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.stateImages = stateImages;
}
void mousePressed(int mx, int my) {
// check the cursor is within the button bounds
boolean isOver = ((mx >= x && mx <= x + w) && // check horizontal
(my >= y && my <= y + h) ); // check vertical
if (isOver) {
min += 10;
stateIndex++;
if (min>60) {
min = 0;
stateIndex = 0;
label = "ВЫКЛ";
} else {
label = (str(min) + "Мин");
}
}
}
void draw() {
// if the images and index are valid
if (stateImages != null && stateIndex < stateImages.length) {
image(stateImages[stateIndex], x, y, w, h);
} else {
println("error displaying button state image");
println("stateImages: ");
printArray(stateImages);
println("stateIndex: " + stateIndex);
}
// display text
//text(label, x + 17, y + h - 8);
}
}
void controlEvent(ControlEvent theEvent) {
if (theEvent.isFrom(CheckBoxuvum)) {
//myColorBackground = 0;
print("got an event from "+CheckBoxuvum.getName()+"\t\n");
// checkbox uses arrayValue to store the state of
// individual checkbox-items. usage:
println(CheckBoxuvum.getArrayValue());
int col = 0;
for (int i=0; i<CheckBoxuvum.getArrayValue().length; i++) {
int n = (int)CheckBoxuvum.getArrayValue()[i];
print(n);
if (n==1) {
//myColorBackground += CheckBoxuvum.getItem(i).internalValue();
}
}
println();
}
if (theEvent.isGroup()) {
// check if the Event was triggered from a ControlGroup
println("event from group : "+theEvent.getGroup().getValue()+" from "+theEvent.getGroup());
} else if (theEvent.isController()) {
println("event from controller : "+theEvent.getController().getValue()+" from "+theEvent.getController());
}
}
Protocol:
int lengthmas = 7;
int RC = 0x21; // -128 separating byte в java
int[] writeOutgioing = new int[lengthmas];
String incomingData= null;
String outgoingData=null;
String[] testRead = new String[lengthmas];
int x;
void readInc() {
while ( serialPort.available() > 0)
{
incomingData = serialPort.readStringUntil(RC);
testRead = split (incomingData, ',' );
if (testRead != null)
{
x = (int) testRead[0].charAt(0);
Displaydata();
}
}
}
void writeOut() {
outgoingData=str(writeOutgioing[0])+str(writeOutgioing[1])+str(writeOutgioing[2])+str(writeOutgioing[3])+str(writeOutgioing[4])+str(writeOutgioing[5])+str(writeOutgioing[6]); // sending data as a string.
serialPort.write(outgoingData);
}
Senddata:
public void toapply()
{
}
loop:
void draw()
{
background(50);
button.draw();
if (strata)
{
readInc();
}
}
code:
inputPULI = cp5.addNumberbox("PUL")
.setLabel("Bullet")
.setPosition(220, 220)
.setSize(80, 30)
.setColorValue(0xffffff00)
.setFont(p)
.setScrollSensitivity(1.1)
.setDirection(Controller.HORIZONTAL)
.setRange(1, 199)
.setValue(3);
Label labelinputPULI = inputPULI.getCaptionLabel();
labelinputPULI.setFont(font);
labelinputPULI.setColor(color(#00ffff));
labelinputPULI.toUpperCase(false);
labelinputPULI.setText("Bullet");
labelinputPULI.align(ControlP5.LEFT_OUTSIDE, CENTER);
labelinputPULI.getStyle().setPaddingLeft(-25);
I figured it out myself, I had to write setLabel->setValueLabel

Java Asteroids game how to be able to fire multiple shots without having the first shot disappear?

So for my final in Java class, we are making an Asteroid game (except a simpler version that the official one, because not enough time).
The problem is when our ship fires a shot (SPACE bar) we add(shot, x, y), but then when we click SPACE bar again it just takes that shot and puts it back to original x, y. So right now we can only fire off one shot at a time to be on the screen. We would like to be able to be able to fire off multiple shots and have them all be visible and stuff.
Not sure how to do that though. Any help is welcome thank you.
P.S. if needed i will add our code.
P.S.S. sorry for posting this again i thought i could edit the post later, thats why i didn't include the code but apparently not.
package week7Homework;
import acm.program.GraphicsProgram;
import java.util.*;
import java.awt.event.*;
import acm.graphics.*;
import java.awt.Color;
import java.awt.Image;
public class space8bit extends GraphicsProgram
{
/* Initialize everything that is needed */
final int WIN_HEIGHT = 800;
final int WIN_WIDTH = 1900;
GImage space = new GImage("/College/IT219/Week7/src/week7Homework/outerspace.png");
GImage ship = new GImage("/College/IT219/Week7/src/week7Homework/ship.png");
GImage explosion = new GImage("/College/IT219/Week7/src/week7Homework/explosion.png");
GImage [] ast = new GImage[6];
Random rand = new Random();
pewpew shots = new pewpew();
int shipx;
int shipy;
public void init()
{
setSize(WIN_WIDTH, WIN_HEIGHT);
add(space);
ship.setLocation(50,330);
ship.scale(.8);
add(ship);
addKeyListeners( );
//scale explosion
explosion.scale(.5);
}
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode( );
if (key == KeyEvent.VK_UP)
{ ship.move(0, -15); }
/*else if (key == KeyEvent.VK_SPACE)
{ xMove = MV_AMT; }*/
else if (key == KeyEvent.VK_DOWN)
{ ship.move(0, 15); }
else if (key == KeyEvent.VK_SPACE)
{shipx = (int)ship.getX()+195;
shipy = (int)ship.getY() + 80;
add(shots,shipx,shipy);
}
}
public void asteriods()
{
GImage ast1 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1300,100);
GImage ast2 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1750,250);
GImage ast3 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1650,350);
GImage ast4 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1550,650);
GImage ast5 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1450,600);
GImage ast6 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1350,750);
ast [0] = ast1;
ast [1] = ast2;
ast [2] = ast3;
ast [3] = ast4;
ast [4] = ast5;
ast [5] = ast6;
add(ast[0]);
add(ast[1]);
add(ast[2]);
add(ast[3]);
add(ast[4]);
add(ast[5]);
}
public void run()
{
asteriods();
while(true)
{
pause(120);
int random1x = rand.nextInt(-1+1+6)-9;
int random2x = rand.nextInt(-1+1+6)-15;
int random3x = rand.nextInt(-1+1+6)-25;
int random4x = rand.nextInt(-1+1+6)-16;
int random5x = rand.nextInt(-1+1+6)-8;
int random6x = rand.nextInt(-1+1+6)-13;
ast[0].move(random1x, 0);
ast[1].move(random2x, 0);
ast[2].move(random3x, 0);
ast[3].move(random4x, 0);
ast[4].move(random5x, 0);
ast[5].move(random6x, 0);
shots.move(50, 0);
for (int i = 0; i < ast.length; i++)
{
//integer that gets bounds of all rectangles and ovals in the arrays.
GRectangle asteroidBounds = ast[i].getBounds();
//check for collision with other objects
if (shots.getBounds().intersects(asteroidBounds))
{
int shotX = (int)shots.getX();
int shotY = (int)shots.getY();
pause(10);
remove(ast[i]);
add(explosion, shotX-100, shotY - 50);
remove(shots);
pause(25);
remove(explosion);
}
else if (ship.getY() <= 0)
{
ship.move(0, 15);
}
else if (ship.getY() >= WIN_HEIGHT - 168)
{
ship.move(0, -15);
}
}
}
}
}
ALSO HERE IS A SAMPLE CODE, much shorter but does the same thing. Just press SPACEBAR and you will see what im talking about.
package week7Homework;
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
import java.awt.event.*;
public class collisionTry extends GraphicsProgram
{
final int WIN_WIDTH = 500;
final int WIN_HEIGHT = 500;
GOval ship = new GOval(100, 250, 50, 50);
GImage bullet = new GImage("/College/IT219/Week7/src/week7Homework/bullet.gif", 50, 50);
GImage bullet2;
boolean bulletFired;
public void init()
{
setSize(WIN_WIDTH, WIN_HEIGHT);
addKeyListeners();
}
public void run()
{
GRect rect = new GRect(400, 200, 50, 150);
add(rect);
rect.setColor(Color.BLACK);
rect.setFilled(true);
add(ship);
ship.setColor(Color.BLACK);
ship.setFilled(true);
while (true)
{
pause(50);
rect.move(-1, 0);
//bullet.move(5, 0);
if (bulletFired == true)
{
bullet.move(5, 0);
}
if (bullet.getBounds().intersects(rect.getBounds()))
{
remove(rect);
remove(bullet);
}
}
}//run
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_SPACE)
{
int shipX = (int)ship.getX();
int shipY = (int)ship.getY();
add(bullet, shipX+50, shipY+25);
bulletFired = true;
}
else if (key == KeyEvent.VK_UP){
ship.move(0, -5);
}
}
}
It's 'cause you only have 1 bullet in the entire game
if (bulletFired == true) {
bullet.move(5, 0);
}
You're telling that one bullet to go back to (5, 0)
You need to find some way of making a new bullet object each time you press space:
if (key == KeyEvent.VK_SPACE) {
int shipX = (int)ship.getX();
int shipY = (int)ship.getY();
Bullet firedBullet = new Bullet(/* params if any, x? y? */);
add(firedBullet, shipX+50, shipY+25);
bulletFired = true;
}
Though this is my vision of how I'd do things, which probably won't work with your game (I don't know what classes you have, their roles etc). But hopefully you can see what I'm getting at and adapt it.
Now because you have multiple bullets, you also have to take care of their lifetimes. You fired 1000 bullets at the start of the game, they go off-screen. You don't want to waste time drawing them for the rest of the game. So whatever list/array you're using to keep track of objects to draw, you gotta periodically find and remove the ones that have gone off-screen.

How would I go about "monitoring" the center of the screen?

In Java I want to essentially focus on the 1 pixel at the dead center of the screen and detect/call an action if there is a change of color (ex. Center is focused on a white background, and suddenly I open up a green background, that 1 pixel was detected as going from white -> green). I know I would need the height and width of the resolution and determine the center from that.
The only problem now is I have no idea what code I would need to further move on with this process. Can someone guide me through what I can do? I know this is kinda broad since it doesn't include any code.
Here is a quick and dirty example, maybe it helps:
public class PixelBot {
private final Robot bot;
private boolean running = true;
private int lastPixelValue = 0;
public static void main(String[] args) throws Exception {
new PixelBot();
}
public PixelBot() throws AWTException {
this.bot = new Robot();
this.runInBackground();
}
private void checkPixel() {
Rectangle areaOfInterest = getAreaOfInterest();
BufferedImage image = bot.createScreenCapture(areaOfInterest);
int clr = image.getRGB(0, 0);
if (clr != lastPixelValue) {
int red = (clr & 0x00ff0000) >> 16;
int green = (clr & 0x0000ff00) >> 8;
int blue = clr & 0x000000ff;
System.out.println("\nPixel color changed to: Red: " + red + ", Green: " + green + ", Blue: " + blue);
Toolkit.getDefaultToolkit().beep();
lastPixelValue = clr;
} else {
System.out.print(".");
}
}
private Rectangle getAreaOfInterest() {
// screen size may change:
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
// half of screen, minus 1 pixel to be captured:
int centerPointX = (int) (screenSize.getWidth() / 2 - 1);
int centerPointY = (int) (screenSize.getHeight() / 2 - 1);
Point centerOfScreenMinusOnePixel = new Point(centerPointX, centerPointY);
return new Rectangle(centerOfScreenMinusOnePixel, new Dimension(1, 1));
}
private void runInBackground() {
new Thread(new Runnable() {
#Override
public void run() {
while (running) {
checkPixel();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
public void stop() {
this.running = false;
}
}

TowerDefense image import (eclipse,java)

I've been working on a tower defense game using eclipse and I cannot manage to print out the picture of my tower. Here is some code from the main tower class :
public class MainTower {
public String TextureFile = "";
public Image texture;
//tower array that holds up to 150 towers
public static final MainTower[] towerList = new MainTower[150];
//Connecting the Lightning tower to the Main tower class
public static final MainTower towerOfLight = new LightningTower(0).getTextureFile("Lightning");
public MainTower(int id) {
if(towerList[id] != null){
System.out.println("[Tower Initialization] Two towers with the same id" + id);
} else {
towerList[id] = this;
this.id = id;
}
}
public MainTower getTextureFile(String str) {
this.TextureFile = str;
this.texture = new ImageIcon("/res/tower/" + this.TextureFile + "png").getImage();
return null;
}
}
The location is correct the image is a 25x25 png image called Lightning. Here is some code from the layout class :
for(int x = 0; x<15; x++) {
for(int y = 0; y<2; y++) {
if(MainTower.towerList[x *2 +y] != null)
GUI.drawImage(MainTower.towerList[x * 2 + y].texture, (int) (12 + 12 + 250 + 40 + 12 +(x * towerWidth)), (12*50) + 20 + (y * (int)towerHeight), null);
GUI.drawRect((int) (12 + 12 + 250 + 40 + 12 +(x * towerWidth)), (int) ((12*50) + 20 + ((y * towerHeight))), (int)towerWidth,(int)towerHeight);
}
}
}
I've created a grid (boxes) at the bottom of the screen where I wish to place my towers so the player can choose. So I was wondering where am i going wrong so the picture doesn't print out.
Here is the LightningTower class:
//Creating a class for Lightning towers
public class LightningTower extends MainTower{
//Setting up Lightning tower id
public LightningTower(int id){
super(id);
}
}

How to combine 2 images to form hybrid image?

I am implementing hybrid image with ImageJ and stuck at merging low filter image and high filter image to form a hybrid image.
This is what I already done.I have 2 images from Gaussian Blur and Laplician of Gaussian filer. I need to merge these 2 images by layer after that. Any idea how to achieve it?
import ij.*;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import ij.plugin.filter.*;
import ij.plugin.*;
import ij.io.*;
import java.io.*;
public class HybridImage_Plugin implements PlugInFilter{
int cfsize=3;
String img_lowPass;
String img_highPass;
private double[][] filter;
private double sigma;
float w=2 ,delta=0 , thr=0;
int mode=0;
//dialogbox
private boolean GUI()
{
GenericDialog gd = new GenericDialog("Enter Values", IJ.getInstance());
gd.addNumericField("Sigma (3,5,9,17,35)", cfsize, 0);
gd.addStringField("Low-Pass", "/home/atrx/ImageJ/plugins/hybridimage/l1.tif");
gd.addStringField("High-Pass", "/home/atrx/ImageJ/plugins/hybridimage/l2.tif");
return getUserParams(gd);
}
//get parameters
private boolean getUserParams(GenericDialog gd)
{
gd.showDialog();
if (gd.wasCanceled())
{
return false;
}
cfsize = (int) gd.getNextNumber();
img_lowPass = gd.getNextString();
img_highPass= gd.getNextString();
return true;
}
public int setup(String arg, ImagePlus imp) {
return PlugInFilter.NO_IMAGE_REQUIRED;
}
public void run(ImageProcessor ip) {
int[][] result;
if(GUI() == false)
{
return;
}
else
{
Opener opener1 = new Opener();
Opener opener2 = new Opener();
ImagePlus imp1= opener1.openImage(img_lowPass);
ImagePlus imp2= opener2.openImage(img_highPass);
//imp1.show("Low Pass Image");
//imp2.show("HighPass Image");
ImageProcessor ip1 = imp1.getProcessor();
ImageProcessor ip2 = imp2.getProcessor();
//lowpass filter(Gaussian Blur)
ip1.blurGaussian(cfsize);
showProcessor(ip1,"Low Pass Filtered Image");
//highpass filter(LoG)
int csize = ip2.getHeight();
int rsize = ip2.getWidth();
Rectangle rect = ip2.getRoi();
int d0,a0,acr,dow,it;
int i,x,y;
double h12, h21, ft, h1h2, h2h1, fmu, dh, dv;
double r, dt, dmx, dmn;
float logaus[] = new float[(rect.width>rect.height)? rect.width : rect.height];
float gaus[] = new float[(rect.width>rect.height)? rect.width : rect.height];
float dgaus[] = new float[(rect.width>rect.height)? rect.width : rect.height];
long zcn =0;
byte pixels[] = (byte[])ip2.getPixels();
int img_in[] = new int[rect.width*rect.height];
if (cfsize<0) cfsize=3;
if (cfsize>35) cfsize=35;
if(w<0) w=0;
int fsize = (int)(cfsize*w);
if (fsize%2 == 0)
{
fsize += 1;
}
double dimg[] = new double[rect.height*rect.width];
double dr[] = new double[rect.height*rect.width];
i=0;
for(y=rect.y;y<(rect.y+rect.height);y++)
{
for(x=rect.x;x<(rect.x+rect.width);x++)
{
img_in[i] = (pixels[(y*rsize)+x]&0xff);
i++;
}
}
int size = rect.width + fsize -1;
int image[] = new int[(rect.width+fsize-1)*(rect.height+fsize-1)];
int extension= (fsize/2);
for( i=0; i<rect.height;i++)
{
System.arraycopy(img_in,(i*rect.width),image,( ((i+extension)*(rect.width+fsize-1))+ extension ),rect.width);
}
h1h2= h2h1 = h12 =0.0;
for(i=1; i<( (fsize+1) /2);i++)
{
w = (float)cfsize/(float)2.0/(float)1.414;
ft = i/w;
gaus[i] = (float)Math.exp(-ft*ft/2);
h1h2 += 2.0 *(gaus[i]);
logaus[i] =(float)(1-ft*ft)*(float)Math.exp(-ft*ft/2);
h2h1 += 2.0*(logaus[i]);
dgaus[i] =(float)ft*(float)Math.exp(-ft*ft/2);
}
fmu = (h2h1 + 1)* (h1h2+1);
int prel[] = new int[rect.width+1];
dmx = -99999.9;
dmn = 99999.9;
int limit = ((rect.width+fsize-1)*(rect.height+fsize-1));
for(d0=0;d0<rect.height;d0++)
{
for(a0=0;a0<rect.width;a0++)
{
acr = a0 + fsize/2;
dow = d0 + fsize/2;
dh = dv = 0.0;
h1h2 = h2h1 = 0.0;
for (int j=1; j<(fsize+1)/2; j++)
{
int a0d0, a0d1, a1d0, a1d1;
h12=h21=0.0;
for(i=1;i<(fsize+1)/2;i++)
{
a0d0 = acr-i+((dow-j)*size);
a0d1 = acr-i+((dow+j)*size);
a1d0 = acr+i+((dow-j)*size);
a1d1 = acr+i+((dow+j)*size);
h12 += logaus[i]*(image[a0d0] + image[a0d1]+
image[a1d0] + image[a1d1]);
h21 += gaus[i]* (image[a0d0] + image[a0d1] +
image[a1d0] + image[a1d1]);
}
a0d0 = acr-j+dow*size;
a0d1 = acr+(dow-j)*size;
a1d0 = acr+j+dow*size;
a1d1 = acr+(dow+j)*size;
h1h2 += gaus[j] * (h12+ image[a0d0]+image[a0d1]+
image[a1d0]+image[a1d1]);
h2h1 += logaus[j]*(h21+ image[a0d0]+ image[a0d1] +
image[a1d0] + image[a1d1] );
if(thr != 0.0)
{
dh += dgaus[j] * ( image[a1d0] - image[a0d0] );
dv += dgaus[j] * ( image[a1d1] - image[a0d1] );
}
}
dt = dimg[d0*rect.width+a0] = h1h2 + h2h1 + (2*image[dow*size+acr]) ;
if (dt > dmx) dmx = dt;
if (dt < dmn) dmn = dt;
if( thr!= 0.0)
{
dr[(d0*rect.width)+a0] = Math.abs(dh) + Math.abs(dv);
}
}
}
dmx = (dmx-dmn) / 2;
dmn += dmx;
int row=0, column=0;
for(d0=0;d0<rect.height;d0++)
{
for(a0=0;a0<rect.width;a0++)
{
int id = (d0*rect.width) +a0;
int index = rsize*(rect.y+d0) + (a0+rect.x);
int k = 15;
it = (int)(dt = (dimg[id] - (dmn-delta*dmx))*255 / (dmx*(1+Math.abs(delta))));
switch(mode){
case 0:
pixels[index] = (byte)((dt-dmn+dmx)/dmx*127);
break;
case 1:
pixels[index] = (byte)Math.abs(it);
break;
case 2:
pixels[index] = (byte)( ((dt!=0)?((dt>0) ? 1: -1) : 0) * 192);
break;
case 3:
default:
r = dr[id];
it = ( (dt!=0) ? ((dt>0) ? 1: -1) : 0);
if( it==0 && r>=thr)
{
k = 255;
zcn++;
}
else
{
if( (it*prel[a0]<0 || it*prel[a0+1]<0) && r>=thr)
{
k = 255;
zcn++;
}
}
prel[a0+1] = it;
if(k==255 || mode!=3)
pixels[index] = (byte)k;
break;
}
}
}
showProcessor(ip2,"High Pass Filtered Image");
}
}
static void showProcessor(ImageProcessor ip, String title){
ImagePlus win = new ImagePlus(title,ip);
win.show();
}
}
Have you tried performing a weighted sum?
OUT = w*LPF + (1 - w)*HPF
This kind of sum is used everywhere. In particular, image blending, alpha matting and even in some optimization schemes.
However because there are patches of varying spatial frequencies all around your image, you may have to make the weight adaptive. You also have to choose which one you want to emphasize more. Do you want the low pass or high pass information to stand out more? Depending on which you want, you might want to use information in either one of those images and run it through some distance or similarity measure to get the right weight.

Categories

Resources