Results 1 to 12 of 12
  1. #1
    Fabian fenech is offline Member
    Join Date
    Apr 2011
    Posts
    5
    Rep Power
    0

    Default Motion Detection desperate in need of help!!

    Hi All,
    I have a problem with a motion detection code
    I am try to get coordinates where there is motion unfortunatly i am not getting the right coordinates, If someone can help me below there is the code and it can work with any clip

    Thanks and Regards,
    Fabian Fenech

    package motiondetectioneffect;


    /**
    * Copyright: Copyright (c) 2002 by Konrad Rzeszutek
    *
    *
    *
    *
    * This file is part of Motion Detection toolkit.
    *
    * Motion Detection toolkit is free software; you can redistribute it and/or modify
    * it under the terms of the GNU General Public License as published by
    * the Free Software Foundation; either version 2 of the License, or
    * (at your option) any later version.
    *
    * Motion Detection toolkit is distributed in the hope that it will be useful,
    * but WITHOUT ANY WARRANTY; without even the implied warranty of
    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    * GNU General Public License for more details.
    *
    * You should have received a copy of the GNU General Public License
    * along with Foobar; if not, write to the Free Software
    * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
    *
    */

    import java.awt.*;
    import java.awt.event.*;
    import javax.media.*;
    import javax.media.control.TrackControl;
    import javax.media.Format;
    import javax.media.format.*;
    import javax.media.protocol.*;
    import javax.media.datasink.*;
    import javax.media.control.*;
    import javax.swing.JFrame;
    /**
    * Sample program to test the MotionDetectionEffect.
    */
    public class TestMotionDetection extends Frame implements ControllerListener {

    Processor p;
    DataSink fileW = null;
    Object waitSync = new Object();
    boolean stateTransitionOK = true;
    public JFrame frame;
    int mouseX,mouseY = 0;
    public TestMotionDetection() {
    super("Test Motion Detection");
    MouseMotionListener popup = new MouseMotionListener() {

    public void mouseDragged(MouseEvent e) {
    throw new UnsupportedOperationException("Not supported yet.");
    }

    public void mouseMoved(MouseEvent e) {
    mouseX=e.getX();
    mouseY=e.getY();
    System.out.println("You clicked on "+mouseX+","+mouseY);
    }
    };
    addMouseMotionListener(popup);


    //frame = new JFrame("Test Motion Detetction");
    //frame.setSize(400, 400);
    //frame.setVisible(true);
    //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
    }
    /**
    * Given a datasource, create a processor and use that processor
    * as a player to playback the media.
    *
    * During the processor's Configured state, the MotionDetectionEffect
    * and TimeStampEffect is
    * inserted into the video track.
    *
    */
    public boolean open(MediaLocator ds) {

    try {
    p = Manager.createProcessor(ds);
    } catch (Exception e) {
    System.err.println("Failed to create a processor from the given datasource: " + e);
    return false;
    }

    p.addControllerListener(this);


    // Put the Processor into configured state.
    p.configure();
    if (!waitForState(p.Configured)) {
    System.err.println("Failed to configure the processor.");
    return false;
    }

    // So I can use it as a player.

    p.setContentDescriptor(null);
    // Obtain the track controls.
    TrackControl tc[] = p.getTrackControls();

    if (tc == null) {
    System.err.println("Failed to obtain track controls from the processor.");
    return false;
    }

    // Search for the track control for the video track.
    TrackControl videoTrack = null;

    for (int i = 0; i < tc.length; i++) {
    if (tc[i].getFormat() instanceof VideoFormat) {
    videoTrack = tc[i];
    break;
    }
    }

    if (videoTrack == null) {
    System.err.println("The input media does not contain a video track.");
    return false;
    }


    // Instantiate and set the frame access codec to the data flow path.

    try {

    Codec codec[] = { new MotionDetectionEffect()};
    videoTrack.setCodecChain(codec);
    } catch (UnsupportedPlugInException e) {
    System.err.println("The processor does not support effects.");
    }

    // Realize the processor.

    p.prefetch();
    if (!waitForState(p.Prefetched)) {
    System.err.println("Failed to realize the processor.");
    return false;
    }
    // Display the visual & control component if there's one.

    // Get the player. Or construct the player from the processor

    setLayout(new BorderLayout());

    Component cc;

    Component vc;
    if ((vc = p.getVisualComponent()) != null) {
    add("Center", vc);
    }

    if ((cc = p.getControlPanelComponent()) != null) {
    add("South", cc);
    }

    // Start the processor.
    p.start();

    setVisible(true);

    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    p.close();
    System.exit(0);
    }
    });

    p.start();

    return true;
    }

    public void addNotify() {
    super.addNotify();
    pack();
    }

    /**
    * Block until the processor has transitioned to the given state.
    * Return false if the transition failed.
    */
    boolean waitForState(int state) {
    synchronized (waitSync) {
    try {
    while (p.getState() != state && stateTransitionOK)
    waitSync.wait();
    } catch (Exception e) {}
    }
    return stateTransitionOK;
    }


    /**
    * Controller Listener.
    */
    public void controllerUpdate(ControllerEvent evt) {

    System.out.println(this.getClass().getName()+evt);
    if (evt instanceof ConfigureCompleteEvent ||
    evt instanceof RealizeCompleteEvent ||
    evt instanceof PrefetchCompleteEvent) {
    synchronized (waitSync) {
    stateTransitionOK = true;
    waitSync.notifyAll();
    }
    } else if (evt instanceof ResourceUnavailableEvent) {
    synchronized (waitSync) {
    stateTransitionOK = false;
    waitSync.notifyAll();
    }
    } else if (evt instanceof EndOfMediaEvent) {
    p.close();
    System.exit(0);
    }
    }

    public static void main(String [] args) {
    // myExample frame=new myExample();
    // frame.setVisible(true);
    String ar = "file:///C://Downloads//tennis.avi";

    // if (ar.length == 0) {
    // prUsage();
    // System.exit(0);
    // }
    //JMFPlayer p = new JMFPlayer(f,
    // argv.length == 0 ? "file:///C://Downloads//tennis1.avi"
    // : argv[0]);
    String url = "file:///C://Downloads//AVI//ahdem.avi";

    if (url.indexOf(":") < 0) {
    prUsage();
    System.exit(0);
    }

    MediaLocator ml;
    if ((ml = new MediaLocator(url)) == null) {
    System.err.println("Cannot build media locator from: " + url);
    System.exit(0);
    }

    TestMotionDetection fa = new TestMotionDetection();

    if (!fa.open(ml))
    System.exit(0);
    }

    static void prUsage() {
    System.err.println("Usage: java TestMotionDetection <url>");
    }


    }


    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */

    package motiondetectioneffect;

    /**
    * A motion detection algoritm for use with the Java Media Framework API (JMF).
    * The main idea of the algorithm is to compare the pixelcolours of two successive frames in an incoming videostream.
    * To prevent noise to be mistaken for motion each frame is divided into many small squares for which only the mean colour is used for compairson.
    * @version 2002-09-26
    * @author Mattias Hedlund, mathed-8.
    * @author Fredrik Jonsson, frejon-9.
    * @author David Ňberg, davabe-9 all students at LuleŚ University of Technology.
    */

    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.media.*;
    import javax.media.format.*;
    import java.awt.*;
    import java.awt.geom.Point2D;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.Writer;

    public class MotionDetectionEffect implements Effect {
    /**
    * The initial square side.
    */
    private final static int INITIAL_SQUARE_SIZE = 5;

    public final static Format[] supportedFormat = new Format[] { //
    new RGBFormat(null, //
    Format.NOT_SPECIFIED, //
    Format.byteArray, //
    Format.NOT_SPECIFIED, //
    24, //
    3, 2, 1, //
    3, Format.NOT_SPECIFIED, //
    Format.TRUE, //
    Format.NOT_SPECIFIED) //
    };

    private Format inputFormat;

    private Format outputFormat;

    private Format[] inputFormats;

    private Format[] outputFormats;

    private int[] bwPixels;

    private byte[] bwData;

    /**
    * Visual mode is set.
    */
    private boolean visualize = true;

    /**
    * Server mode is set.
    */
    private boolean serverActive = true;

    /**
    * Update requested is set.
    */
    private boolean updateRequested;

    private int avg_ref_intensity;

    private int avg_img_intensity;

    /**
    * The RGBFormat of the inbuffer.
    */
    private RGBFormat vfIn = null;

    /**
    * Four different thresholds. Set initial values here.
    */
    private int[] threshs = { 10, 15, 20, 25 };
    //private int[] threshs = { 20, 30, 40, 50 };

    private int det_thresh = threshs[1];

    /**
    * The corresponding colours to the four different thresholds.
    */
    private int[] colors = { 0x00FF0000, 0x00FF9900, 0x00FFFF00, 0x00FFFFFF };

    /**
    * The mean values of all squares in an image.
    */
    private int[] newImageSquares = null;

    /**
    * The mean values of all squares in an image.
    */
    private int[] oldImageSquares = null;

    /**
    * The difference of all the mean values of all squares in an image.
    */
    private int[] changedSquares = null;
    private int[][] changedSquares1 = null;
    /**
    * The number of squares fitted in the image.
    */
    private int numberOfSquaresWide;

    /**
    * The number of squares fitted in the image.
    */
    private int numberOfSquaresHigh;

    /**
    * The number of squares fitted in the image.
    */
    private int numberOfSquares;

    /**
    * The square side, in pixels.
    */
    private int sqSide = INITIAL_SQUARE_SIZE;
    /**
    * The square area, in pixels.
    */
    private int sqArea = 0;

    /**
    * The amount of pixels left when all normal sized squares have been removed.
    */
    private int sqWidthLeftover = 0;

    /**
    * The amount of pixels left when all normal sized squares have been removed.
    */
    private int sqHeightLeftover = 0;

    /**
    * Optional, less processing is needed if some pixels are left out during some of the calculations.
    */
    int[][] arrayPixPos;

    private int pixelSpace = 0;
    public int xPos = 0;
    public int yPos = 0;
    /**
    * Image property.
    */
    private int imageWidth = 0;

    /**
    * Image property.
    */
    private int imageHeight = 0;

    /**
    * Image property.
    */
    private int imageArea = 0;

    /**
    * Initialize the effect plugin.
    */
    public MotionDetectionEffect() {
    inputFormats = new Format[] { new RGBFormat(null, Format.NOT_SPECIFIED, Format.byteArray, Format.NOT_SPECIFIED, 24, 3, 2, 1, 3, Format.NOT_SPECIFIED, Format.TRUE, Format.NOT_SPECIFIED) };

    outputFormats = new Format[] { new RGBFormat(null, Format.NOT_SPECIFIED, Format.byteArray, Format.NOT_SPECIFIED, 24, 3, 2, 1, 3, Format.NOT_SPECIFIED, Format.TRUE, Format.NOT_SPECIFIED) };

    }
    // this is array is created a 2 d array with the pixel numbers in it

    public void intiArrayPos(){
    int count = 0;
    for(int i = 0;i<numberOfSquaresHigh; i++){
    for(int t = 0 ; t< numberOfSquaresWide;t++){
    arrayPixPos[i][t] = count++;
    }

    }
    }
    public void findPos(int sqrposition){

    int rem = sqrposition % numberOfSquaresWide;
    int floor = (sqrposition / numberOfSquaresWide);
    yPos = (numberOfSquaresHigh- floor);
    //yPos = floor ;
    xPos = (rem );
    }
    public void findPosBeg(int sqrposition){

    int rem = sqrposition % imageWidth;
    int floor = (sqrposition / imageWidth);
    yPos = (imageHeight- floor);
    //yPos = floor ;
    xPos = (rem );
    }
    /**
    * Get the inputformats that we support.
    * @return All supported Formats.
    */
    public Format[] getSupportedInputFormats() {
    return inputFormats;
    }

    /**
    * Get the outputformats that we support.
    * @param input the current inputformat.
    * @return All supported Formats.
    */
    public Format[] getSupportedOutputFormats(Format input) {
    if (input == null) {
    return outputFormats;
    }
    if (matches(input, inputFormats) != null) {
    return new Format[] { outputFormats[0].intersects(input) };
    } else {
    return new Format[0];
    }
    }

    /**
    * Set the input format.
    *
    */
    public Format setInputFormat(Format input) {
    inputFormat = input;
    return input;
    }

    /**
    * Set our output format.
    *
    */
    public Format setOutputFormat(Format output) {

    if (output == null || matches(output, outputFormats) == null)
    return null;

    RGBFormat incoming = (RGBFormat) output;

    Dimension size = incoming.getSize();
    int maxDataLength = incoming.getMaxDataLength();
    int lineStride = incoming.getLineStride();
    float frameRate = incoming.getFrameRate();
    int flipped = incoming.getFlipped();
    int endian = incoming.getEndian();

    if (size == null)
    return null;
    if (maxDataLength < size.width * size.height * 3)
    maxDataLength = size.width * size.height * 3;
    if (lineStride < size.width * 3)
    lineStride = size.width * 3;
    if (flipped != Format.FALSE)
    flipped = Format.FALSE;

    outputFormat = outputFormats[0].intersects(new RGBFormat(size, maxDataLength, null, frameRate, Format.NOT_SPECIFIED, Format.NOT_SPECIFIED, Format.NOT_SPECIFIED, Format.NOT_SPECIFIED, Format.NOT_SPECIFIED, lineStride, Format.NOT_SPECIFIED, Format.NOT_SPECIFIED));

    return outputFormat;
    }

    /**
    * Process the buffer. This is where motion is analysed and optionally visualized.
    *
    */

    public synchronized int process(Buffer inBuffer, Buffer outBuffer) {
    int outputDataLength = ((VideoFormat) outputFormat).getMaxDataLength();
    validateByteArraySize(outBuffer, outputDataLength);
    outBuffer.setLength(outputDataLength);
    outBuffer.setFormat(outputFormat);
    outBuffer.setFlags(inBuffer.getFlags());

    byte[] inData = (byte[]) inBuffer.getData();
    byte[] outData = (byte[]) outBuffer.getData();
    int[] sqAvg = null;
    int[] refsqAvg = null;

    vfIn = (RGBFormat) inBuffer.getFormat();
    Dimension sizeIn = vfIn.getSize();

    int pixStrideIn = vfIn.getPixelStride();
    int lineStrideIn = vfIn.getLineStride();
    int pixstide = vfIn.getPixelStride();
    imageWidth = (vfIn.getLineStride()) / 3; //Divide by 3 since each pixel has 3 colours.
    imageHeight = ((vfIn.getMaxDataLength()) / 3) / imageWidth;
    imageArea = imageWidth * imageHeight;

    int r, g, b = 0; //Red, green and blue values.

    if (oldImageSquares == null) { //For the first frame.
    changeSqSize(INITIAL_SQUARE_SIZE);
    updateRequested = true;
    }

    //Copy all data from the inbuffer to the outbuffer. The purpose is to display the video input on the screen.
    System.arraycopy(inData, 0, outData, 0, outData.length);

    // Simplify the image to black and white, image information shrinks to one third of the original amount. Less processing needed.
    bwPixels = new int[outputDataLength / 3];
    for (int ip = 0; ip < outputDataLength; ip += 3) {
    int bw = 0;
    r = (int) inData[ip] & 0xFF;
    g = (int) inData[ip + 1] & 0xFF;
    b = (int) inData[ip + 2] & 0xFF;
    bw = (int) ((r + b + g) / (double) 3);
    bwPixels[ip / 3] = bw; //Now containing a black and white image.
    }

    if (updateRequested) {
    try {
    updateRequested = false;
    updateSquares();
    return BUFFER_PROCESSED_OK;
    } catch (IOException ex) {
    Logger.getLogger(MotionDetectionEffect.class.getNa me()).log(Level.SEVERE, null, ex);
    }
    } else {
    try {
    updateSquares();
    } catch (IOException ex) {
    Logger.getLogger(MotionDetectionEffect.class.getNa me()).log(Level.SEVERE, null, ex);
    }
    oldNewChange();
    int c = 0;
    int temp = 0;


    for (int f = 0; f < changedSquares.length; f++) {
    if (changedSquares[f] > det_thresh) {
    c++;
    temp= f;
    }
    }

    //if (c > 10 && serverActive)
    if (c > 10 && serverActive) {
    // try{
    //System.out.println("changed square "+temp+"Motion detected (motion at " + c + "areas");

    // findPos(temp);
    // System.out.println("xPos "+ xPos+ "yPos "+yPos+ "C " + c);
    // multicast.send("Motion detected"); // - Disabled
    // } catch(IOException e){}
    }

    // If chosen, the detected motion is presented on top of the video input, thus covering the edges of the moving object.





    if (visualize) {
    for (int i = 1; i <= numberOfSquares; i++) { // For all blobs
    temp= i;
    if ((changedSquares[i - 1] > threshs[0])) { // Critical threshold, if less, then no motion is said to have occured.
    if (((i % numberOfSquaresWide) != 0) && (numberOfSquares - i) > numberOfSquaresWide) {//Normal square, the other cases is not presented!
    int begin = ((((i % numberOfSquaresWide) - 1) * sqSide) + ((i / numberOfSquaresWide) * imageWidth * sqSide)) * 3; //Calculate start of square.
    //System.out.println("this is fucken begin"+begin);
    //if (begin > 400000 && begin < 670000){
    // if statment to check previous next pixel up and downn

    findPosBeg(begin);
    if(changedSquares [i-5]< threshs[3]) {
    if((changedSquares [i-5]< threshs[3])){

    }
    }
    System.out.println(yPos);
    if (changedSquares[i - 1] > threshs[3]) { //Very strong motion.

    b = (byte) (colors[3] & 0xFF);
    g = (byte) ((colors[3] >> 8) & 0xFF);
    r = (byte) ((colors[3] >> 16) & 0xFF);
    } else if (changedSquares[i - 1] > threshs[2]) { //Strong motion.
    b = (byte) (colors[2] & 0xFF);
    g = (byte) ((colors[2] >> 8) & 0xFF);
    r = (byte) ((colors[2] >> 16) & 0xFF);
    } else if (changedSquares[i - 1] > threshs[1]) { //Weak motion.
    b = (byte) (colors[1] & 0xFF);
    g = (byte) ((colors[1] >> 8) & 0xFF);
    r = (byte) ((colors[1] >> 16) & 0xFF);
    } else { //The Weakest motion detected.
    b = (byte) (colors[0] & 0xFF);
    g = (byte) ((colors[0] >> 8) & 0xFF);
    r = (byte) ((colors[0] >> 16) & 0xFF);
    }
    //173730 < 184530 175890
    // public point[] getWritableTileIndices(outBuffer);
    for (int k = begin; k < (begin + (sqSide * imageWidth * 3)); k = k + (imageWidth * 3)) { //Ev <=
    for (int j = k; j < (k + (sqSide * 3)); j = j + 3) {
    try {
    outData[j] = (byte) b;
    outData[j + 1] = (byte) g;
    outData[j + 2] = (byte) r;
    //System.out.println(begin);
    //etienne 77771874- 27010389
    for (int s =103; s < 10367; s++ ){
    outData[s] = (byte) b;
    outData[s + 1] = (byte) g;
    outData[s + 2] = (byte) r;
    }

    } catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Nullpointer: j = " + j + ". Outdata.length = " + outData.length);
    System.exit(1);
    }
    }
    // }
    }

    }
    }
    }
    }
    }

    return BUFFER_PROCESSED_OK;
    }

    // Methods for interface PlugIn
    public String getName() {
    return "Motion Detection Codec";
    }

    public void open() {
    }

    public void close() {
    }

    public void reset() {
    }

    // Methods for interface javax.media.Controls
    public Object getControl(String controlType) {
    System.out.println(controlType);
    return null;
    }

    public Object[] getControls() {
    return null;
    }

    // Utility methods.
    public Format matches(Format in, Format outs[]) {
    for (int i = 0; i < outs.length; i++) {
    if (in.matches(outs[i]))
    return outs[i];
    }

    return null;
    }

    // Credit : example at Oracle Technology Network for Java Developers
    byte[] validateByteArraySize(Buffer buffer, int newSize) {
    Object objectArray = buffer.getData();
    byte[] typedArray;

    if (objectArray instanceof byte[]) { // Has correct type and is not null
    typedArray = (byte[]) objectArray;
    if (typedArray.length >= newSize) { // Has sufficient capacity
    return typedArray;
    }

    byte[] tempArray = new byte[newSize]; // Reallocate array
    System.arraycopy(typedArray, 0, tempArray, 0, typedArray.length);
    typedArray = tempArray;
    } else {
    typedArray = new byte[newSize];
    }

    buffer.setData(typedArray);
    return typedArray;
    }

    /**
    * Sets the current pixelspace, default is zero.
    * This is mainly for use where limited processing capacity are availible. Some pixels are left out in the calculations.
    * @param newSpace the space between two successive pixels.
    */
    private void setPixelSpace(int newSpace) {
    pixelSpace = newSpace;
    }

    /**
    * Changes the size of the square shaped area that divides the detection area into many small parts.
    * @param newSide the side of the square, in pixels.
    */
    private void changeSqSize(int newSide) {
    sqSide = newSide;
    sqArea = newSide * newSide;
    System.out.println(imageWidth+"number of squares wide ");
    System.out.println(imageHeight+"number of squares high ");
    int wid = (imageWidth / sqSide); //The number of squares wide.
    int hei = (imageHeight / sqSide); //The number of squares high.
    sqWidthLeftover = imageWidth % sqSide;
    sqHeightLeftover = imageHeight % sqSide;
    if (sqWidthLeftover > 0) {
    wid++;
    }
    if (sqHeightLeftover > 0) {
    hei++;
    }

    numberOfSquaresWide = wid;
    numberOfSquaresHigh = hei;
    numberOfSquares = wid * hei;

    newImageSquares = new int[numberOfSquares];
    oldImageSquares = new int[numberOfSquares];
    changedSquares = new int[numberOfSquares];
    arrayPixPos = new int [numberOfSquaresHigh][numberOfSquaresWide];
    intiArrayPos();

    System.out.println(numberOfSquares+"number of squares ");
    System.out.println(numberOfSquaresWide+"number of squares wide ");
    System.out.println(numberOfSquaresHigh+"number of squares high ");
    }

    /**
    * Calculates the average colour in each square thus indirect eliminate noise.
    * @param startX the starting position of this square, in pixels, left edge.
    * @param startY the starting position of this square, in pixels, bottom edge.
    * @param sqWidth the width of this square, in pixels.
    * @param sqHeight the height of this square, in pixels.
    * @return The average greyscale value for this square.
    */
    private int averageInSquare(int startX, int startY, int sqWidth, int sqHeight) {
    int average = 0;

    // System.out.println("pos x"+startX);
    for (int i = 0; i < sqHeight; i = i + 1 + pixelSpace) {// For all pixels
    for (int j = 0; j < sqWidth; j = j + 1 + pixelSpace) {
    average += bwPixels[(((startY + i) * imageWidth) + (startX + j))]; //Sum all the pixel values.
    }
    }
    average = average / (sqWidth * sqHeight); //Divide by the number of pixels to get the average value.
    // System.out.println("avrage"+average);
    return average;

    }

    /**
    * Backup the most recent frame examined. For the new frame, calculate the average greyscale value for all squares.
    */
    private void updateSquares() throws IOException {
    System.arraycopy(newImageSquares, 0, oldImageSquares, 0, newImageSquares.length);
    setContents(newImageSquares);
    int sqCount = 0; //Keep track of the current square
    for (int j = 0; j < (imageHeight); j = j + sqSide) { //For all squares
    for (int i = 0; i < (imageWidth); i = i + sqSide) {
    if (i <= (imageWidth - sqSide) && j <= (imageHeight - sqSide)) {
    newImageSquares[sqCount] = averageInSquare(i, j, sqSide, sqSide); //No edge!
    } else if (i > (imageWidth - sqSide) && j <= (imageHeight - sqSide)) {
    newImageSquares[sqCount] = averageInSquare(i, j, sqWidthLeftover, sqSide); //Right edge!
    } else if (i <= (imageWidth - sqSide) && j > (imageHeight - sqSide)) {
    newImageSquares[sqCount] = averageInSquare(i, j, sqSide, sqHeightLeftover); //Bottom edge!
    } else if (i > (imageWidth - sqSide) && j > (imageHeight - sqSide)) {
    newImageSquares[sqCount] = averageInSquare(i, j, sqWidthLeftover, sqHeightLeftover); //Bottom right edge!
    }
    sqCount++;
    //System.out.println("xpos"+j + "ypos"+i);
    }
    }
    }

    /**
    * Calculate the difference per square between currently stored frames.
    */
    private void oldNewChange() {
    for (int i = 0; i <= (numberOfSquares - 1); i++) { //For all squares
    int difference = Math.abs((newImageSquares[i]) - (oldImageSquares[i])); //Compare each square with the corresponding square in the previous frame.
    changedSquares[i] = difference; //Save the difference.
    // System.out.println(difference);
    }
    }

    public synchronized void updateModel(boolean visualize, boolean serverActive, boolean simplified, int[] threshs, int[] colors, int sqSide, int det_thresh) {

    this.visualize = visualize;
    this.serverActive = serverActive;
    if (sqSide != this.sqSide)
    changeSqSize(sqSide);
    if (!simplified) {
    System.out.println((colors == null) + " " + (this.colors == null));
    System.arraycopy(colors, 0, this.colors, 0, colors.length);
    System.arraycopy(threshs, 0, this.threshs, 0, colors.length);
    this.det_thresh = det_thresh;
    System.out.println("New det_threhsh: " + this.det_thresh);
    }
    updateRequested = true;
    }

    /**
    *Check if the visualize variable is set.
    *@returns the current value.
    */
    public boolean isVisual() {
    return visualize;
    }

    /**
    *Get the current threshold values in a vector.
    *@returns the current values.
    */
    public int[] getThreshholds() {
    return threshs;
    }

    /**
    *Check if the server is active.
    *@returns the current value.
    */
    public boolean isServerActive() {
    return serverActive;
    }

    public int[] getColors() {
    return colors;
    }

    /**
    *Get the current square side.
    *@returns the current value.
    */
    public int getSqSide() {
    return sqSide;
    }


    //write to text
    static public void setContents( int[] aContents)throws FileNotFoundException, IOException {
    File aFile = new File("C:\\downloads\\blah.txt");

    if (aFile == null) {
    throw new IllegalArgumentException("File should not be null.");
    }
    if (!aFile.exists()) {
    throw new FileNotFoundException ("File does not exist: " + aFile);
    }
    if (!aFile.isFile()) {
    throw new IllegalArgumentException("Should not be a directory: " + aFile);
    }
    if (!aFile.canWrite()) {
    throw new IllegalArgumentException("File cannot be written: " + aFile);
    }
    //use buffering
    Writer output = new BufferedWriter(new FileWriter(aFile));
    try {
    //FileWriter always assumes default encoding is OK!
    for (int s = 0; s< aContents.length; s++){
    output.write( aContents.toString() );

    }
    }
    finally {
    output.close();
    }
    }



    }

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,225
    Rep Power
    20

    Default

    That is far too much code to try and figure out your problem...and it's also unformatted, since it's not in code tags.

    Can you narrow your problem down at all?

  3. #3
    Fabian fenech is offline Member
    Join Date
    Apr 2011
    Posts
    5
    Rep Power
    0

    Default Longer describtion of motion detection

    Hi my main problem is to get the X Y postion of the moving object i am loading a tennis clip and i want to get coordinates while moving.
    This program i downloaded from internet and emended it for my needs.
    Basicly this program will get a buffered images the current frame and the next frame convert them in a 1Dimentional array and than in black and white image so to be a faster process and where it find movment it change the colour of the moving object.

    I tried to create a method called findPosBeg where i pass a variable called begin from the method process in my opion is the postion of were the movment is made but could be that i am wrong coz it not working as i wish the cordinates are wrong.


    I tried to put mouseactionlistener which is not working neighter so that i can know what the coordinates supost to be.

    I have also made a method called setContents(int[] aContents, String Name) where an array of string is writen in a text file but when i open it as i need the data there is only garbage

    Here is a link were to download my program if you want it is netbeans project.
    http://www.maltasupport.com/kevin/Mo...tionEffect.rar

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,225
    Rep Power
    20

    Default

    There may be someone here willing to go through testing out your program, but most of us do not have the time to download projects and sift through them to find out the problem.

    How about showing us (in code tags) the code you have tried, and describe what it is doing wrong. Before doing that, though, ensure you have gathered any useful information together, like what values are actually being passed around (not what you think are being passed around).

  5. #5
    Fabian fenech is offline Member
    Join Date
    Apr 2011
    Posts
    5
    Rep Power
    0

    Default

    Sorry for not understanding what your request were, I am using this as part of my thesis which i shall handel next month and your help is really appreciated.

    I will start with the MouseMotionListener this method is made in the main class(TestMotionDetection) in the constractor. This is not working in all the frame but is only working in the bottom of the frame where there is the bar where play stop the clip etc.

    MouseMotionListener popup = new MouseMotionListener() {

    public void mouseMoved(MouseEvent e) {
    mouseX=e.getX();
    mouseY=e.getY();
    System.out.println("You clicked on "+mouseX+","+mouseY);


    The second one is the setContents(int[] aContents, String Name) where this is made to write int[] array but instead it is writing garbage in the text file. Following there is the method i am using for this method
    static public void setContents( int[] aContents,String name)throws FileNotFoundException, IOException {
    //name = "C:\\downloads\\blah.txt";
    File aFile = new File(name);
    aContents.toString();
    if (aFile == null) {
    throw new IllegalArgumentException("File should not be null.");
    }
    if (!aFile.exists()) {
    throw new FileNotFoundException ("File does not exist: " + aFile);
    }
    if (!aFile.isFile()) {
    throw new IllegalArgumentException("Should not be a directory: " + aFile);
    }
    if (!aFile.canWrite()) {
    throw new IllegalArgumentException("File cannot be written: " + aFile);
    }
    //use buffering
    Writer output = new BufferedWriter(new FileWriter(aFile));
    try {
    //FileWriter always assumes default encoding is OK!
    for (int s = 0; s< aContents.length; s++){
    output.write( aContents.toString() );

    }
    }
    finally {
    output.close();
    }
    }

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,225
    Rep Power
    20

    Default

    If you didn't know how code tags worked you could have asked.
    [ code] code in here [ /code] (without spaces).

    And green? Seriously?

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,225
    Rep Power
    20

    Default

    So, what is the garbage?
    Can you print a sample?
    What values do you expect in there?

  8. #8
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,763
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Tolls View Post
    And green? Seriously?
    Anything wrong with green?

    kind regards,

    Loretta
    cenosillicaphobia: the fear for an empty beer glass

  9. #9
    Fabian fenech is offline Member
    Join Date
    Apr 2011
    Posts
    5
    Rep Power
    0

    Default

    Sorry again for green and tags hope this time i am doing it good.

    I will start with the MouseMotionListener this method is made in the main class(TestMotionDetection) in the constractor. This is not working in all the frame but is only working in the bottom of the frame where there is the bar where play stop the clip etc.

    Java Code:
    public void mouseMoved(MouseEvent e) {
    mouseX=e.getX();
    mouseY=e.getY();
    System.out.println("You clicked on "+mouseX+","+mouseY);
    The second one is the setContents(int[] aContents, String Name) where this is made to write int[] array but instead it is writing garbage in the text file. Following there is the method i am using for this method The result have to be numbers.

    Java Code:
    static public void setContents( int[] aContents,String name)throws FileNotFoundException, IOException {
    //name = "C:\\downloads\\blah.txt";
    File aFile = new File(name);
    aContents.toString(); 
    if (aFile == null) {
    throw new IllegalArgumentException("File should not be null.");
    }
    if (!aFile.exists()) {
    throw new FileNotFoundException ("File does not exist: " + aFile);
    }
    if (!aFile.isFile()) {
    throw new IllegalArgumentException("Should not be a directory: " + aFile);
    }
    if (!aFile.canWrite()) {
    throw new IllegalArgumentException("File cannot be written: " + aFile);
    }
    //use buffering
    Writer output = new BufferedWriter(new FileWriter(aFile));
    try {
    //FileWriter always assumes default encoding is OK!
    for (int s = 0; s< aContents.length; s++){
    output.write( aContents.toString() );
    }
    }
    finally {
    output.close();
    }
    }

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,225
    Rep Power
    20

    Default

    It's not garbage.
    It's the type of the thing you are toString()ing and the memory address.
    That's because an int[] does not have a toString() method of its own, so it defaults to the one in Object.

    If you want a specific format for this array to print out then you'll have to write some code to do it.

    As for the mouse stuff, what have you attached that listener to?

  11. #11
    Fabian fenech is offline Member
    Join Date
    Apr 2011
    Posts
    5
    Rep Power
    0

    Default

    I did the add mouse motion listener in the same method only.


    Java Code:
       MouseMotionListener popup = new MouseMotionListener() {
    
                public void mouseDragged(MouseEvent e) {
                    throw new UnsupportedOperationException("Not supported yet.");
                }
    
                public void mouseMoved(MouseEvent e) {
                   mouseX=e.getX();
            mouseY=e.getY();
    	System.out.println("You clicked on "+mouseX+","+mouseY);
                }
            };
             addMouseMotionListener(popup);

  12. #12
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,225
    Rep Power
    20

    Default

    But what have you added it to?
    I can't read that mass of code in the original post, so you'll have to say.
    Which Component have you added the mouse listener to?

Similar Threads

  1. Replies: 1
    Last Post: 01-20-2011, 05:59 PM
  2. help i'm desperate
    By AniMaind in forum New To Java
    Replies: 17
    Last Post: 01-08-2011, 02:05 AM
  3. Desperate for some help if possible :(
    By SBOSlayer in forum New To Java
    Replies: 1
    Last Post: 11-30-2010, 11:44 PM
  4. help on motion detection
    By MarkWilson in forum Advanced Java
    Replies: 4
    Last Post: 12-07-2009, 07:45 AM
  5. Multithreading + Networking (desperate)
    By bluebarca in forum New To Java
    Replies: 1
    Last Post: 11-07-2007, 03:14 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •