Quantcast
Channel: Library Questions - Processing 2.x and 3.x Forum
Viewing all 2896 articles
Browse latest View live

Problem about my network pong

$
0
0

Hello everyone, First, i want to apologies if i make mistakes with my english, i'm french. So, here is my question : when i lunch my " server program " everything is ok, but when I lunch the " client program " nothing happen. I spent some hours but I can't find what's the problem... Can you help me please ?

I know I have to put my code here, but i don't understantd why when i try, the layout changes and it's illegible... May I sent it by email to the people who wants to help me ?


Reliably send images over net

$
0
0

Hello,

I’m trying to transfer images over net between Processing-sketches on different computers. I’ve been making making some small test sketches to test this out. I’m using built-in java library to convert PImage to JPEG-encoded byte-arrays (to keep size down) which I in turn send over the net.

However, I’ve never really done much networking programming before and I’m having trouble getting this to work reliably. Generally my problem is that very often I just get a part of the image, but not the whole thing.

I am not really looking for code help per se, just what approach I should take. Do I need to send the image in parts and then stitch it together (or the corresponding bytes together)? Will I then need some way to make sure the server know it received a whole part? Or should I just read from the buffer in a different way? Are there any ready-made solutions like libraries that can deal with this?

And generally my goal here is simply to transfer a image from one computer to another, am I going about this in the easiest and smartest way? Would be easier to just bounce this stuff off a web server somewhere?

Any pointers here would be hugely appreciated.

Here is my server code:

import processing.net.*;

Server server;
JPGEncoder jpg;
PImage img;

void setup() {
    size(1400, 800);
    jpg = new JPGEncoder();
    // Start a server at port 5204
    server = new Server(this, 5204);

    img = createImage(100, 100, RGB);
    println("Starting server");
}

void draw() {
    checkForIncomingImage();
    image(img, 0, 0);
}


void checkForIncomingImage() {
    Client nextClient = server.available();
    if (nextClient != null) {
        println("Client is available, reading bytes");

        byte[] byteBuffer = nextClient.readBytes();

        if (byteBuffer.length > 0) {
            println("Received data. Trying to decode.");
            try {
                img = jpg.decode(byteBuffer);
            } catch (IOException e) {
                println("IOException");
            } catch (NullPointerException e) {
                println("Probs incomplete image");
            } catch (ArrayIndexOutOfBoundsException e) {
                println("Probs also incomplete image (Out of Bounds)");
            }
        } else {
            println("Byte amount not above 0");
        }
    }
}

And here is my client code:

import processing.net.*;
import processing.video.*;

Client client;
Capture cam;
JPGEncoder jpg;

void setup() {
    jpg = new JPGEncoder();

    cam = new Capture(this, Capture.list()[1]);
    cam.start();

    // String server = "192.168.1.15";
    String server = "127.0.0.1";
    client = new Client(this, server, 5204);

    background(255);
    println("Starting client");
}

void draw() {

}

void keyTyped() {
    if (cam.available()) {
        println("Cam available. Going to read");
        cam.read();
        try {
            println("Getting image to memory");
            PImage img = cam.get();
            img.resize(500, 0);

            println("Encoding");
            byte[] encoded = jpg.encode(img, 0.1F);

            println("Writing to server");
            client.write(encoded);
        } catch (IOException e) {
            // Ignore failure to encode
            println("IOException");
        }


    }
}

You can also view the code at GitHub here: https://github.com/torbjornlunde/processing-experiments

Example of what an incomplete transfer of image looks like: proc-img-tranfser-example

How to fix this? Split function

$
0
0

Hi, I'm new with Processing and I have a problem when I try to split the data that I receive from the Serial Port from Arduino. I want to upload the data received into a database but the code doesn´t upload the data properly. I have printed the values of "serial" and "date" separately and I have realised that I am receiving all the data in the variable "serial" but nothing in the variable "date". So how can i fix this??

Here is the part of the code:

void draw()
{
   if  (myPort.available() > 0 && contador == 0){
        myPort.write("T2222222222");
        contador++;
        }

   val = myPort.readStringUntil('\n');  // read it and store it in val

   if (val != null){
         String[] a = split(val, '\n');
         serial = a[0];
         date  = a[1];
         db.connect();
         db.execute("INSERT INTO example (data, hora) VALUES ('%s', '%s')", serial, date);
         }
       }

ControlP5 ListBox problem in Processing V3

$
0
0

Hello

I'm new to Processing and I am using V3.2.4. I need to display a ListBox from the ControlP5 library with several text entries in the list and depending on which list item is selected I need to call other functions.

The code in a previous post below gets me close to what I need however when I paste the code into a new sketch it errors in a few places e.g.

The function captionLabel() does not exist

The function valueLabel() does not exist

The method group() from the type ControlEvent is deprecated

The method name() from the type ControlEvent is deprecated

I am aware that older code will not work in more recent versions of Processing and library functions change slightly e.g. captionLabel() becomes getCaptionLabel()

In this code the void draw()function does work however the ControlEvent() does not return anything in the println statement. This means that I cannot identify the item selected from the items in the listbox and therefore cannot move into other functions/actions.

 void controlEvent(ControlEvent theEvent) {
      if (theEvent.isGroup()) {
        // an event from a group e.g. scrollList
        println(theEvent.group().value()+" from "+theEvent.name());
        if (theEvent.name() == "myList") {  // if we got an event from myList
          println("choosed " + employee[int(theEvent.group().value())]); // look through the array
        }
      }
    }

I have made several unsuccessful attempts to get this to work in V3.2.4 and have run out of ideas. Any advice on what needs to change in the code will be greatly appreciated thanks.

This is the url to the forum post:

https://forum.processing.org/one/topic/how-to-get-controlp5-library-listbox-item-name.html

This is the code:

import controlP5.*;

ControlP5 controlP5;
//set the names here
String[] employee = {
  "empA", "empB", "empC", "empD", "empE", "empF"
};

ListBox l;
int cnt = 0;
void setup() {
  size(400, 400);
  frameRate(30);
  controlP5 = new ControlP5(this);
  l = controlP5.addListBox("myList", 100, 100, 120, 120);
  l.setItemHeight(15);
  l.setBarHeight(15);

  l.captionLabel().toUpperCase(true);
  l.captionLabel().set("something else");
  l.captionLabel().style().marginTop = 3;
  l.valueLabel().style().marginTop = 3; // the +/- sign
  //l.setBackgroundColor(color(100,0,0));

  for (int i=0;i<employee.length;i++) {
    l.addItem(employee[i], i);
  }
  l.setColorBackground(color(255, 128));
  l.setColorActive(color(0, 0, 255, 128));
}

void controlEvent(ControlEvent theEvent) {
  if (theEvent.isGroup()) {
    // an event from a group e.g. scrollList
    println(theEvent.group().value()+" from "+theEvent.name());
    if (theEvent.name() == "myList") {  // if we got an event from myList
      println("choosed " + employee[int(theEvent.group().value())]); // look through the array
    }
  }
}

void draw() {
  background(128);
  // scroll the scroll List according to the mouseX position
  // when holding down SPACE.
  if (keyPressed && key==' ') {
    //l.scroll(mouseX/((float)width)); // scroll taks values between 0 and 1
  }
  if (keyPressed && key==' ') {
    l.setWidth(mouseX);
  }
}

how to draw a waveform for an entire sound file ?

$
0
0

Hello, I would like to draw the waveform of an entire sound file.
I have seen the example from the documentation, but this is an osciloscope, which works with a buffer, whereas I would like to draw for the entire file, as in soundcloud for example.

import ddf.minim.*;
Minim minim;
AudioPlayer sound;

void setup() {
  size(300, 200);
  minim = new Minim(this);
  sound = minim.loadFile("mySound.wav");

  println(sound.length());

  for (int i=0; i < sound.length()-1024; i+=16) {
   println( sound.mix.get(i));
  }
  exit();
}

this did not work because, because get(i) "Gets the i sample in the buffer", wich size is 1024...
how to have all the sample value inside the file ?

thx.

Animated Gradient Colour Responder

$
0
0

This project needs an animated gradient, responding to an ambient colour every 5 seconds.

I am having difficulty getting the gradient animation to respond to color as seen by the laptop camera.

The animated gradient loop runs on a laptop. Every 5 seconds or so, the webcam will sample the ambient colour using the camera. What I am trying is to have the gradient colour update to that colour sampled. and then continue with the cycling of colours from there.

Any suggestions greatly appreciated.

    import processing.video.*;
    Capture cam;

    int Y_AXIS = 1;

    //Gradient colors
    color c1, c2;

    float rd1=100;
    float gr1=100;
    float bl1=255;

    float rd2=100;
    float gr2=255;
    float bl2=100;

    float rd1Change = 0.1;
    float gr1Change = 0.2;
    float bl1Change = 0.3;

    float rd2Change = 0.3;
    float gr2Change = 0.2;
    float bl2Change = 0.1;


    int get=1;

    int timer = 0;


    void setup() {
      size(1200, 800);
      noStroke();

      //webcam
      String[] cameras = Capture.list();
      cam = new Capture(this, cameras[0]);
      cam.start();
    }

    void draw() {
      //go cam
      if (cam.available() == true) {
        cam.read();
      }
      //draw cam
      image(cam, 0, 0, width, height);

      //get the color
      get = cam.get(width/2, 50);

      // set the gradient colors
      c1 = color(rd1, gr1, bl1);
      c2 = color(rd2, gr2, bl2);


      // color rotates - top
      rd1=rd1+ rd1Change;
      if (rd1 < 100 || rd1 > 255) {
        rd1Change *= -1;
      }

      gr1=gr1+ gr1Change;
      if (gr1 < 100 || gr1 > 255) {
        gr1Change *= -1;
      }


      bl1=bl1+ bl1Change;
      if (bl1 < 100 || bl1 > 255) {
        bl1Change *= -1;
      }


      // color rotates - bottom
      rd2=rd2+ rd2Change;
      if (rd2 < 100 || rd2 > 255) {
        rd2Change *= -1;
      }

      gr2=gr2+ gr2Change;
      if (gr2 < 100 || gr2 > 255) {
        gr2Change *= -1;
      }

      bl2=bl2+ bl2Change;
      if (bl2 < 100 || bl2 > 255) {
        bl2Change *= -1;
      }

      // make gradient

      setGradient(100, 100, width-200, height-200, c1, c2, Y_AXIS);
    }

    void setGradient(int x, int y, float w, float h, color c1, color c2, int axis ) {

      if (axis == Y_AXIS) {  // Top to bottom gradient
        for (int i = y; i <= y+h; i++) {
          float inter = map(i, y, y+h, 0, 1);
          color c = lerpColor(c1, c2, inter);
          stroke(c);
          line(x, i, x+w, i);

          // Timer
          if (millis()-timer > 5000) {
            timer = millis();

            // how do I  implement get colour back into gradient cycle?

          }
        }
      }
    }

Where is toxi.geom? I can not find it anyware.

$
0
0

I am trying to install Processing for the MPU6050 and MPUTeapot. MPUTeapot uses the library toxi.geom. But I can not even find the library.

Installing processing 3 with Maven

$
0
0

Hi. It's my first time with Maven. I searched for tutorials on installing Processing with Maven and I saw a couple but they are like outdated.

What I'm trying to do, is adding this dependency to my brand new project: https://search.maven.org/#artifactdetails|org.processing|processing-complete|3.2.3|pom

FYI, I create a project using Maven and imported it in IntelliJ. That looks good. Then, I added this snippet to the pom:

<dependency>
      <groupId>org.processing</groupId>
      <artifactId>processing-complete</artifactId>
      <version>3.2.3</version>
</dependency>

The I tried running this:

mvn clean install

Or just the mvn install part. And I get this message:

Failed to execute goal on project [...] Failure to find org.processing:processing-complete:jar:3.2.3 in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced

Any clue?


MySQL, - Please let me know why I get an error.

$
0
0

Code :

/**
 *    MySQL example 1
 *    github.com/fjenett/sql-library-processing
 *
 *    created 2005-05-10 by fjenett
 *    updated fjenett 20130718
 *    tested with Processing 2.0.x
 */

import de.bezier.data.sql.*;

MySQL msql;


void setup()
{
size( 100, 100 );

// this example assumes that you are running the
// mysql server locally (on "localhost")

// 1
// replace your mysql login:

String user     = "sql_user";
String pass     = "sql_pass";

// 2
// name of the database to use

String database = "sql_library_test_db";

// add additional parameters like this:
// sql_library_test_db?useUnicode=true&characterEncoding=UTF-8

// 3
// connect to database of server "localhost"

msql = new MySQL( this, "localhost", database, user, pass );

if ( msql.connect() )
{
    msql.query( "SELECT COUNT(*) FROM %s", "example1" );
    msql.next();
    println( "this table has " + msql.getInt(1) + " number of rows" );
}
else
{
    // connection failed !

    // - check your login, password
    // - check that your server runs on localhost and that the port is set right
    // - try connecting through other means (terminal or console / MySQL workbench / ...)
}
}

void draw()
{
// i know this is not really a visual sketch ...
}

Error : com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:

** BEGIN NESTED EXCEPTION **

java.net.SocketException MESSAGE: java.net.ConnectException: Connection refused: connect

STACKTRACE:

java.net.SocketException: java.net.ConnectException: Connection refused: connect at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:156) at com.mysql.jdbc.MysqlIO.(MysqlIO.java:284) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2569) at com.mysql.jdbc.Connection.(Connection.java:1485) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266) at java.sql.DriverManager.getConnection(DriverManager.java:664) at java.sql.DriverManager.getConnection(DriverManager.java:247) at de.bezier.data.sql.SQL.connect(SQL.java:179) at MySQL_example1.setup(MySQL_example1.java:59) at processing.core.PApplet.handleDraw(PApplet.java:2393) at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1540) at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:316)

** END NESTED EXCEPTION **

Last packet sent to the server was 8 ms ago. at com.mysql.jdbc.Connection.createNewIO(Connection.java:2643) at com.mysql.jdbc.Connection.(Connection.java:1485) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266) at java.sql.DriverManager.getConnection(DriverManager.java:664) at java.sql.DriverManager.getConnection(DriverManager.java:247) at de.bezier.data.sql.SQL.connect(SQL.java:179) at MySQL_example1.setup(MySQL_example1.java:59) at processing.core.PApplet.handleDraw(PApplet.java:2393) at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1540) at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:316)


Please let me know why I get an error.

Is there a more effective way to send coordinates than through split() or splittokens()?

$
0
0

So I'm trying to send coordinates between four players through a server using the networking library, and currently it seems like the easiest way to do that is to send a string such as:

positions= 0 + "," + ballX + "," + ballY + "," + p1 + "," + p2 + "\n"; myserver.write(positions);

And then receive it through:

void clientEvent(Client client) { receivemessage=client.readUntil("\n"); datain = splittokens(receivemessage,",\n"); }

However, this seems to lag behind a bit as the buffer fills up and it slowly drifts further and further from real time. Should I stop sending strings and parsing them with splittokens() in favour of some other method, or should I just make sure that the client clears the buffer every once in a while?

Flickering of graphics drawn over video

$
0
0

I'm having trouble with some code that I've patched together. I've managed to get this to mostly work, but when it runs the toplayer graphics over the video flicker, I think while the video updates. Is there a way to keep this from happening?

code below:

import ipcapture.*;

IPCapture cam1;

// Circular buffer
PImage[] cam1_buffer;

// These determine the size of the circular buffer and help iterate while writing and reading through them
int nFrames = 1;
int iWrite = 0, iRead = 1;

// Track color var
color trackColor;

//top layer drawing thing
PGraphics topLayer;

void setup() {

  size(704, 480);

  cam1 = new IPCapture(this, "http://" + "155.41.145.37/mjpg/video.mjpg", "", "");
  cam1.start();
  // If the camera resolution isn't explicitely defined the PImage.get() method will give strange results
  cam1.pixelWidth = 704;
  cam1.pixelHeight = 480;

  cam1_buffer = new PImage[nFrames];

  //Track color vars
  colorMode(RGB,255,255,255,100);
  trackColor = color(255,0,64);
  noFill();
  smooth();
  strokeWeight(4.0);
  stroke(0);

  //create a top layer for circles
  topLayer = createGraphics(width, height, g.getClass().getName());

}

void draw() {
  if (cam1.isAvailable()) {
    cam1.read();
    cam1_buffer[iWrite] = cam1.get();
  if(cam1_buffer[0] != null){
  // The original camera image is displayed correctly at 480x300 in the upper left corner
  image(cam1,0,0);
  }
}

  //Track colors below
  loadPixels();


  //Color tracking vars
  float closestDiff = 500.0f;
  int closestX = 0;
  int closestY = 0;

  //Loop through every pixel
  for (int x = 0; x < cam1.pixelWidth; x++){
    for (int y = 0; y < cam1.pixelHeight; y++){
      int loc = x + y*cam1.pixelWidth;

      //what is current color
      color currentColor = cam1.pixels[loc];
      float r1 = red(currentColor);
      float g1 = green(currentColor);
      float b1 = blue(currentColor);
      float r2 = red(trackColor);
      float g2 = green(trackColor);
      float b2 = blue(trackColor);

      //Using euclidean distance to compare colors
      float d = dist(r1,g1,b1,r2,g2,b2);

      //If current color is more similar to tracked color than
      //closest color, save current location and current difference
      if (d < closestDiff) {
        closestDiff = d;
        closestX = x;
        closestY = y;
      }
    }
  }

  //create a threshold
  //then create a circle at the tracked color

  if (closestDiff < 100) {
    topLayer.beginDraw();
    topLayer.noFill();
    topLayer.strokeWeight(4.0);
    topLayer.stroke(trackColor);
    topLayer.ellipse(closestX, closestY, 50, 50);
    topLayer.endDraw();
    image(topLayer, 0, 0);

  }
}

I'm trying to attach music files to text, but my .txt file isn't populating everything in my file.

$
0
0

Screenshot (22) Screenshot (23) Screenshot (24)

I have dragged it and it has the same exact name file.

NET/SERVER/CLIENT - DATA transmission

$
0
0

Hi, Are you all well? I wish you all good things.

I am really curious. I want you to help me. NET library (or something) → I created a server. Message communication between server and client works well.

But what I want is to send and receive data(File Data, EX) .txt, .csv, .png, .jpg).

To expert   1) Which way is better?   2) Is there a solution?   3) Which libraries are available?

Help.

G4P dropList

$
0
0

Is there a way to dynamically populate the G4P dropList control ? I would like to populate it with the Serial.list() function rather than using a text file. Also, I'm using the gold color scheme and the contrast of the text on the buttons and dropList is not very good. How can I change the text color to black and increase the text size?

TUIO library on processing with mac

$
0
0

Hello there, I started a new little project and got stuck right at the beginning. I downloaded the zip file of TUIO, decompressed it and then i copied the folder and put it inside the libraries directory of my sketchbook. I think this I got right so far. BUT: when I open the example file "tuioDemo" a large blank window appears, nothing happens. so is there something I have to change bc I'm on osx, or am I just dumb?

PS: I even put the library file into Processing/Contents/Java/Modes/java/libraries/


processing.org-site / libraries

$
0
0

IMG_0375

The "most pixels ever" library is represented two times on the library page.

Here shown on an iPhone.

Just thought I would let you know :)

Error with any sketch using sound library

$
0
0

Hi all, I'm new to processing, I've done a few tutorials, and it was working fine, but then when I tried to use the sound library none of the sketches run. I'm using processing specifically with the aim of working with sound, so I'm hoping there's a way to get this to work. As far as I can tell I've installed the library correctly. I'm pasting the error message I get below. Any help much appreciated, thanks!

A fatal error has been detected by the Java Runtime Environment:

#

Internal Error (0x20474343), pid=1132, tid=0x000000000000135c

#

JRE version: Java(TM) SE Runtime Environment (8.0_111-b14) (build 1.8.0_111-b14)

Java VM: Java HotSpot(TM) 64-Bit Server VM (25.111-b14 mixed mode windows-amd64 compressed oops)

Problematic frame:

C [KERNELBASE.dll+0x1a06d]

#

Failed to write core dump. Minidumps are not enabled by default on client versions of Windows

Recreate G4P gui element to resize

$
0
0

I recently started using the G4P library and the GUI builder tool and they're working great. However I have encountered a problem with resizing elements in the GUI when the window gets resized. According to https://forum.processing.org/two/discussion/4212/g4p-button-resizing this isn't actually possible.

I have tried to bypass this by assigning a new modified object to the actSelect variable. Any performance hit is acceptable as this will only happen if the user resizes the window. However, I have not been able to use g4p_controls.GAbstractControl.dispose() or g4p_controls.GAbstractControl.markForDisposal() correctly, so eventually I get an OutOfMemory exception because lots of unused objects accumulate. Also, the new GUI element (in this case a droplist) doesn't always respond to user input.

//how do I use these?
//actSelect.markForDisposal();
//actSelect.dispose();
//actSelect = null;

actSelect = new GDropList(base, 10, 10, width/3.0-20, 220, 10);
actSelect.setItems(actData, 0);
actSelect.addEventHandler(base, "actSelectEvent");

How can I do this correctly?

streaming from ip camera issue

$
0
0

Dear team,

We have an IP-camera (foscam C1). (cgi cmds=http://www.foscam.es/descarga/Foscam-IPCamera-CGI-User-Guide-AllPlatforms-2015.11.06.pdf)

we try to access the stream with Processing 3.

we used the IP_Capture example in the examples. The example works correctly. However when using our own ip-address it only takes a snapshot and doesn't refresh to new frames . We would be helped to which changes could get the frames refreshing. Tried some cgi-cmd's but not sure if that is the primary issue).

the code used:

import ipcapture.*;

IPCapture cam;

void setup() {
  size(640,360);
 // cam = new IPCapture(this, "http://195.235.198.107:3346/axis-cgi/mjpg/video.cgi?resolution=320x240", "", "");    //<-- EXAMPLE WORKS

 cam = new IPCapture(this, "http://abt_bfi_2017:cv_2017@192.168.0.16:88/cgi-bin/CGIProxy.fcgi?cmd=snapPicture2&usr=NAME&pwd=EXAMPLE","","");    //<-- OWN IP LINK WONT WORK



 cam.start();


}

void draw() {

  if (cam.isAvailable()) {
    cam.read();
    image(cam,0,0);
    println("hi");
  }
}

Analyse a Sound File Without Playback

$
0
0

I read up on examples of how to use FFT functions to create an audio visualiser as the audio is being played backed. Just wondering, is there a way to analyse a sound file without playing back? For example, read through the sound file and store the FFT analysis in a 2D array of spectrum[frame][band].

Viewing all 2896 articles
Browse latest View live