We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Maybe fileFilter is what you need for this last post. For example: https://forum.processing.org/two/discussion/comment/38761/#Comment_38761
More at: https://forum.processing.org/two/search?Search=FileFilter
Kf
Ok, so I did some changes. However, as I suspected, the images have different sizes. So when you try to resize all images to a single size, some images will look distorted since they are not square and the code is forcing them to a square grid. Adding to this, a small image can be stretch out to a bigger space, which also causes distortion. I implemented an alternative solution and it is probably closer to what you want (maybe [?] ). I implemented resize as the percentage of the original image's dimensions. Use the arrow key UP or DOWN to increased or decrease the image's dimension by 10% increment/decrements. The value are constrained from 0 to 1.5 meaning that you can shrink the image to 10% of its original (source) size or augmented to 150%. Notice that if you set the resizing to zero, then you will be showing the images without any modification. The actual percentage being applied to the fragments/mini-images is displayed in the title.
Notice also that I am printing what fragments are being loaded and the actual size of those fragments.
One last thing. There is no need to press the ENTER key to update changes. Changes are updated after you press the key. If you do a mouse click, or any key different to UP or DOWN, it will just generate a new drawing (picking random fragments) with the current resize setting.
Kf
import java.util.List;
import java.io.FileFilter;
import java.io.FilenameFilter;
final int len=25;
final int NMAX=25;
PImage pic;
ArrayList<PImage> imgContainer;
int n=NMAX;
int value = 250;
float resizeX, resizeY;
void setup() {
size(800, 800, P2D);
resizeX=0.4;
resizeY=0.4;
imageMode(CENTER);
colorMode(RGB, 255);
background(250, 250, 250);
rectMode(CENTER);
//imageMode(CENTER);
pic=loadImage("hand.jpg");
pic.resize(width, height);
//c1 = color(200, 25, 25);
//c2 = color(25, 255, 200);
loadAllMiniImages();
println("It has been chosen to work with "+n+" images. Check="+imgContainer.size());
noLoop();
noStroke();
}
void draw() {
background(255);
pic.loadPixels();
for (int y = 0; y < height; y+=147) {
for (int x = 0; x < width; x+=147) {
int index=y*width+x;
color pixelValue = pic.pixels[index];
color rgb = pixelValue;
int r = (rgb >> 16) & 0xFF; // Faster way of getting red(argb)
int g = (rgb >> 8) & 0xFF; // Faster way of getting green(argb)
int b = rgb & 0xFF;
//How far is the current color from white
float dista=dist(r, g, b, 255, 255, 255);
//50 is a threshold value allowing close to white being identified as white
//This value needs to be adjusted based on your actual background color
//Next block is processed only if the pixel not white
if (dista>0) {
float pixelBrightness = brightness(pixelValue);
int imgPicked=(int)random(n);
PImage selected=imgContainer.get((int)imgPicked);
PImage acopy=selected.get();
if (resizeX!=0 || resizeY!=0) {
acopy.resize((int)(acopy.width*resizeX), (int)(acopy.height*resizeY));
}
image(acopy, x, y);
}
}
}
}
void keyPressed() {
if (keyCode==UP) {
resizeX+=0.1;
resizeY+=0.1;
}
if (keyCode==DOWN) {
resizeX-=0.1;
resizeY-=0.1;
}
resizeX=constrain(resizeX, 0, 1.5);
resizeY=constrain(resizeY, 0, 1.5);
surface.setTitle("Size= "+resizeX);
redraw();
}
void mouseReleased() {
redraw();
}
final FileFilter FOLDER_FILTER = new FileFilter() {
@ Override boolean accept(final File path) {
return path.isDirectory();
}
};
final FilenameFilter PIC_FILTER = new FilenameFilter() {
final String[] exts = {
".png" //, ".jpg", ".jpeg", ".gif"
};
@ Override boolean accept(final File path, String name) {
name = name.toLowerCase();
for (final String ext : exts) if (name.endsWith(ext)) return true;
return false;
}
};
void loadAllMiniImages() {
File dataFolder = dataFile("test_segments");
File[] imgDirs = dataFolder.listFiles(FOLDER_FILTER);
imgDirs = (File[]) append(imgDirs, dataFolder);
println(imgDirs.length, "folders found:");
printArray(imgDirs);
List<File[]> imgPaths = new ArrayList<File[]>();
for (File dir : imgDirs) imgPaths.add(dir.listFiles(PIC_FILTER));
println("\nImage paths found for all folders:");
int totalLength = 0;
for (File[] paths : imgPaths) {
totalLength += paths.length;
println();
//printArray(paths);
}
println("Total images found in all subfolders:", totalLength);
//NOW only process up to NMAX images if there are more than NMAX images.
//Otherwise only use the images available.
if (totalLength>NMAX) {
n=NMAX;
} else {
n=totalLength;
}
imgContainer=new ArrayList<PImage>();
int ctr=0;
for (File[] paths : imgPaths) {
for (File f : paths) {
PImage pimg1=loadImage(f.getPath());
println("["+ctr+"] "+f.getPath()+" Dimensions="+pimg1.width+"x"+pimg1.height);
imgContainer.add(pimg1);
ctr++;
//Only load 50 images
if (ctr==n)
break;
}
}
}
This is the code for sketch2. Not many changes. I believe it is now loading 50 images. It will be great if you can test it with other patterns. Not many changes except I am not using the threshold variable this time and I am making sure I am only loading 50 instead of 99.
Kf
import java.util.List;
import java.io.FileFilter;
import java.io.FilenameFilter;
final int len=25;
final float thresh=170;
final int NMAX=50;
boolean newDesign=false;
PImage pic;
ArrayList<PImage> imgContainer;
int n=NMAX;
//color c1, c2;
void setup() {
size(800, 800, P2D);
colorMode(RGB, 255);
background(250, 250, 250);
rectMode(CENTER);
//imageMode(CENTER);
pic=loadImage("hand.jpg");
pic.resize(width, height);
//c1 = color(200, 25, 25);
//c2 = color(25, 255, 200);
loadAllMiniImages();
println("It has been chosen to work with "+n+" images. Check="+imgContainer.size());
noLoop();
noStroke();
}
void draw() {
if (newDesign==false) {
return;
}
pic.loadPixels();
for (int y = 0; y < height; y+=40) {
for (int x = 0; x < width; x+=40) {
int index=y*width+x;
color pixelValue = pic.pixels[index];
color rgb = pixelValue;
int r = (rgb >> 16) & 0xFF; // Faster way of getting red(argb)
int g = (rgb >> 8) & 0xFF; // Faster way of getting green(argb)
int b = rgb & 0xFF;
//How far is the current color from white
float dista=dist(r, g, b, 255, 255, 255);
//50 is a threshold value allowing close to white being identified as white
//This value needs to be adjusted based on your actual background color
//Next block is processed only if the pixel not white
if (dista>30) {
float pixelBrightness = brightness(pixelValue);
//float imgPicked=constrain(pixelBrightness/thresh, 0, n-1);
float imgPicked=map(pixelBrightness, 0, 255, 0, n-1);
imgPicked=constrain(imgPicked, 0, n-1);
image(imgContainer.get((int)imgPicked), x, y);
}
}
}
}
void mouseReleased() {
newDesign=!newDesign;
redraw();
}
final FileFilter FOLDER_FILTER = new FileFilter() {
@ Override boolean accept(final File path) {
return path.isDirectory();
}
};
final FilenameFilter PIC_FILTER = new FilenameFilter() {
final String[] exts = {
".png" //, ".jpg", ".jpeg", ".gif"
};
@ Override boolean accept(final File path, String name) {
name = name.toLowerCase();
for (final String ext : exts) if (name.endsWith(ext)) return true;
return false;
}
};
void loadAllMiniImages() {
File dataFolder = dataFile("test_segments");
File[] imgDirs = dataFolder.listFiles(FOLDER_FILTER);
imgDirs = (File[]) append(imgDirs, dataFolder);
println(imgDirs.length, "folders found:");
printArray(imgDirs);
List<File[]> imgPaths = new ArrayList<File[]>();
for (File dir : imgDirs) imgPaths.add(dir.listFiles(PIC_FILTER));
println("\nImage paths found for all folders:");
int totalLength = 0;
for (File[] paths : imgPaths) {
totalLength += paths.length;
println();
printArray(paths);
}
println("Total images found in all subfolders:", totalLength);
//NOW only process up to NMAX images if there are more than NMAX images.
//Otherwise only use the images available.
if (totalLength>NMAX) {
n=NMAX;
} else {
n=totalLength;
}
imgContainer=new ArrayList<PImage>();
int ctr=0;
for (File[] paths : imgPaths) {
for (File f : paths) {
PImage pimg1=loadImage(f.getPath());
pimg1.resize(50, 50);
imgContainer.add(pimg1);
ctr++;
//Only load 50 images
if (ctr==n)
break;
}
}
}
Technically @daddydean can load all the images. He will have an initial image that will be split into mini images. So the sum of all the available mini-images should be less than managing the same single image.
To access those mini images, you will need to adapt your code to manage all these images. Currently you load 3 images manually, as we have discussed in another post. One way to do this, assuming you know how many images you want to load and they file names follow the same naming convention. For the number of mini files, I will label that number n. For the naming convention, I will stick to the concept test_i.png
where i is a number from 0 to n-1. Then loading the images will be as simple as:
imgContainer=new ArrayList<PImage>();
for(int i=0;i<n;i++){
PImage pimg1=loadImage("test_"+i+".png");
pimg1.resize(50, 50);
imgContainer.add(pimg1);
}
However what if you have 100 images... or what if you only have 25 images? For this to work, we can use code from this post: https://forum.processing.org/two/discussion/20063/load-folders-of-pimages-multiple-folders-unknown-numbers-non-sequential-filenames
The code first loads all the available file names within the data folder, and any of its subfoders and then it will pick 50 if there are more than 50 or all the images if less than 50. This is what the code looks like (NOTE: untested) (NOTE: Final note below)
import java.util.List;
import java.io.FileFilter;
import java.io.FilenameFilter;
final int len=25;
final float thresh=170;
final int NMAX=50;
boolean newDesign=false;
PImage pic;
ArrayList<PImage> imgContainer;
int n=NMAX;
void setup() {
size(800, 800, P2D);
colorMode(RGB, 255);
background(250, 250, 250);
rectMode(CENTER);
//imageMode(CENTER);
pic=loadImage("hand.jpg");
pic.resize(width, height);
color c1 = color(200, 25, 25);
color c2 = color(25, 255, 200);
loadAllMiniImages();
noLoop();
noStroke();
}
void draw() {
if (newDesign==false) {
return;
}
pic.loadPixels();
for (int y = 0; y < height; y+=40) {
for (int x = 0; x < width; x+=40) {
int index=y*width+x;
color pixelValue = pic.pixels[index];
color rgb = pixelValue;
int r = (rgb >> 16) & 0xFF; // Faster way of getting red(argb)
int g = (rgb >> 8) & 0xFF; // Faster way of getting green(argb)
int b = rgb & 0xFF;
//How far is the current color from white
float dista=dist(r, g, b, 255, 255, 255);
//50 is a threshold value allowing close to white being identified as white
//This value needs to be adjusted based on your actual background color
//Next block is processed only if the pixel not white
if (dista>30) {
float pixelBrightness = brightness(pixelValue);
float imgPicked=constrain(pixelBrightness/thresh, 0, n-1);
image(imgContainer.get((int)imgPicked), x, y);
}
}
}
}
void mouseReleased() {
newDesign=!newDesign;
redraw();
}
final FileFilter FOLDER_FILTER = new FileFilter() {
@ Override boolean accept(final File path) {
return path.isDirectory();
}
};
final FilenameFilter PIC_FILTER = new FilenameFilter() {
final String[] exts = {
".png" //, ".jpg", ".jpeg", ".gif"
};
@ Override boolean accept(final File path, String name) {
name = name.toLowerCase();
for (final String ext : exts) if (name.endsWith(ext)) return true;
return false;
}
};
void loadAllMiniImages() {
File dataFolder = dataFile("");
File[] imgDirs = dataFolder.listFiles(FOLDER_FILTER);
imgDirs = (File[]) append(imgDirs, dataFolder);
println(imgDirs.length, "folders found:");
printArray(imgDirs);
List<File[]> imgPaths = new ArrayList<File[]>();
for (File dir : imgDirs) imgPaths.add(dir.listFiles(PIC_FILTER));
println("\nImage paths found for all folders:");
int totalLength = 0;
for (File[] paths : imgPaths) {
totalLength += paths.length;
println();
printArray(paths);
}
println("Total images found in all subfolders:", totalLength);
//NOW only process up to NMAX images if there are more than NMAX images.
//Otherwise only use the images available.
if (totalLength>NMAX) {
n=NMAX;
} else {
n=totalLength;
}
imgContainer=new ArrayList<PImage>();
for (File[] paths : imgPaths) {
for (File f : paths) {
PImage pimg1=loadImage(f.getPath());
pimg1.resize(50, 50);
imgContainer.add(pimg1);
}
}
}
Final note:
To test this code, you need to have the hand file in your data folder and then you need to specify the folder where all those mini-images are. This subfolder, as i understand from prev discussions, resides inside the data folder. Then you need to change
File dataFolder = dataFile("");
for
File dataFolder = dataFile("name_of_subfolder_with_mini-images");
Kf
I don't know - see a messy discussion here:
https://stackoverflow.com/questions/596429/adjust-selected-file-to-filefilter-in-a-jfilechooser
/**
* FilenameFilter + isDirectory() (v1.0)
* GoToLoop (2017-Jan-05)
*
* forum.Processing.org/two/discussion/20063/
* load-folders-of-pimages-multiple-folders-
* unknown-numbers-non-sequential-filenames#Item_7
*
* forum.Processing.org/two/discussion/17111/
* how-to-display-a-random-image-using-processing#Item_3
*/
import java.util.List;
import java.io.FileFilter;
import java.io.FilenameFilter;
final FileFilter FOLDER_FILTER = new FileFilter() {
@ Override boolean accept(final File path) {
return path.isDirectory();
}
};
final FilenameFilter PIC_FILTER = new FilenameFilter() {
final String[] exts = {
".png", ".jpg", ".jpeg", ".gif"
};
@ Override boolean accept(final File path, String name) {
name = name.toLowerCase();
for (final String ext : exts) if (name.endsWith(ext)) return true;
return false;
}
};
PImage[] imgs;
void setup() {
size (777, 777);
File dataFolder = dataFile("");
File[] imgDirs = dataFolder.listFiles(FOLDER_FILTER);
imgDirs = (File[]) append(imgDirs, dataFolder);
println(imgDirs.length, "folders found:");
printArray(imgDirs);
List<File[]> imgPaths = new ArrayList<File[]>();
for (File dir : imgDirs)
imgPaths.add(dir.listFiles(PIC_FILTER));
println("\nImage paths found for all folders:");
int totalLength = 0;
for (File[] paths : imgPaths) {
totalLength += paths.length;
println();
printArray(paths);
}
println("Total images found in all subfolders:", totalLength);
imgs = new PImage[totalLength];
int idx = 0;
for (File[] paths : imgPaths)
for (File f : paths)
imgs[idx++] = loadImage(f.getPath());
// exit();
}
void draw() {
int y1 = 70;
for (PImage img1 : imgs) {
image(img1, 30, y1);
y1 += img1.height+33 ;
}
}
//
/**
* FilenameFilter + isDirectory() (v1.0)
* GoToLoop (2017-Jan-05)
*
* forum.Processing.org/two/discussion/20063/
* load-folders-of-pimages-multiple-folders-
* unknown-numbers-non-sequential-filenames#Item_7
*
* forum.Processing.org/two/discussion/17111/
* how-to-display-a-random-image-using-processing#Item_3
*/
import java.util.List;
import java.io.FileFilter;
import java.io.FilenameFilter;
final FileFilter FOLDER_FILTER = new FileFilter() {
@ Override boolean accept(final File path) {
return path.isDirectory();
}
};
final FilenameFilter PIC_FILTER = new FilenameFilter() {
final String[] exts = {
".png", ".jpg", ".jpeg", ".gif"
};
@ Override boolean accept(final File path, String name) {
name = name.toLowerCase();
for (final String ext : exts) if (name.endsWith(ext)) return true;
return false;
}
};
File dataFolder = dataFile("");
File[] imgDirs = dataFolder.listFiles(FOLDER_FILTER);
imgDirs = (File[]) append(imgDirs, dataFolder);
println(imgDirs.length, "folders found:");
printArray(imgDirs);
List<File[]> imgPaths = new ArrayList<File[]>();
for (File dir : imgDirs) imgPaths.add(dir.listFiles(PIC_FILTER));
println("\nImage paths found for all folders:");
int totalLength = 0;
for (File[] paths : imgPaths) {
totalLength += paths.length;
println();
printArray(paths);
}
println("Total images found in all subfolders:", totalLength);
PImage[] imgs = new PImage[totalLength];
int idx = 0;
for (File[] paths : imgPaths) for (File f : paths)
imgs[idx++] = loadImage(f.getPath());
exit();
Now's a more advanced version which includes CompiledScript for better script performance: ;;)
http://docs.Oracle.com/javase/8/docs/api/javax/script/Compilable.html
http://docs.Oracle.com/javase/8/docs/api/javax/script/CompiledScript.html
/** * Processing Nashorn JS Integration (v4.0) * GoToLoop (2016-Feb-28) * * Forum.Processing.org/two/discussion/15151/how-to-convert-string-to-a-line-of-code * Forum.Processing.org/two/discussion/7147/some-simple-pulse-equations-using-trig */ final ScriptEngine js = new ScriptEngineManager().getEngineByName("Nashorn"); final CompiledScript compiledJS = compileJS(js, // compiles P5's canvas API calls. "background(~~random(0x1000000))", "text(SENTENCES[idx = (idx+1) % SENTENCES.length], w>>1, h>>1)", "surf.setTitle('Idx: ' + idx + ' Frame: ' + frameCount)"); static final String[] SENTENCES = { "Nashorn JS is cool!", "We can draw on the canvas inside JS too!", "Let's program is JS now!!!" }; void setup() { size(400, 150); smooth(4); frameRate(.5); initJSProcessingEnv(js, this); js.put("SENTENCES", SENTENCES); // puts String[] SENTENCES. js.put("idx", 0); // creates global variable idx into JS. evalJS(js, "surf = surface || frame"); // assigns either surface or frame. println(evalJS(js, // calls P5's canvas API from JS. "textFont(createFont('DejaVu Sans', 18))", "textAlign(CENTER, BASELINE)", "fill(~~0xffFFFF00), stroke(0), strokeWeight(1.5)")); } void draw() { runJS(compiledJS); } import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.script.Invocable; import javax.script.Compilable; import javax.script.CompiledScript; static final void initJSProcessingEnv (final ScriptEngine js, final PApplet pa) { js.put("p", pa); // injects sketch's PApplet as p into JS. js.put("w", pa.width); // injects width's current value as w into JS. js.put("h", pa.height); // injects height's current value as h into JS. evalJS(js, // imports Processing's packages. "var processing = {", " core: JavaImporter(Packages.processing.core),", " data: JavaImporter(Packages.processing.data),", " event: JavaImporter(Packages.processing.event),", " awt: JavaImporter(Packages.processing.awt),", " javafx: JavaImporter(Packages.processing.javafx),", " opengl: JavaImporter(Packages.processing.opengl)", "}"); evalJS(js, // imports Processing's core classes. "var PApplet = Java.type('processing.core.PApplet'),", " PConstants = Java.type('processing.core.PConstants'),", " PFont = Packages.processing.core.PFont,", " PGraphics = Packages.processing.core.PGraphics,", " PImage = Packages.processing.core.PImage,", " PMatrix = Packages.processing.core.PMatrix,", " PMatrix2D = Packages.processing.core.PMatrix2D,", " PMatrix3D = Packages.processing.core.PMatrix3D,", " PShape = Packages.processing.core.PShape,", " PShapeOBJ = Packages.processing.core.PShapeOBJ,", " PShapeSVG = Packages.processing.core.PShapeSVG,", " PStyle = Packages.processing.core.PStyle,", " PSurface = Packages.processing.core.PSurface,", " PSurfaceNone = Packages.processing.core.PSurfaceNone,", " PVector = Packages.processing.core.PVector,", " ThinkDifferent = Packages.processing.core.ThinkDifferent"); evalJS(js, // imports Processing's data classes. "var FloatDict = Packages.processing.data.FloatDict,", " FloatList = Packages.processing.data.FloatList,", " IntDict = Packages.processing.data.IntDict,", " IntList = Packages.processing.data.IntList,", " JSONArray = Packages.processing.data.JSONArray,", " JSONObject = Packages.processing.data.JSONObject,", " JSONTokener = Packages.processing.data.JSONTokener,", " Sort = Packages.processing.data.Sort,", " StringDict = Packages.processing.data.StringDict,", " StringList = Packages.processing.data.StringList,", " Table = Packages.processing.data.Table,", " TableRow = Packages.processing.data.TableRow,", " XML = Packages.processing.data.XML"); evalJS(js, // imports Processing's event classes. "var Event = Packages.processing.event.Event,", " KeyEvent = Packages.processing.event.KeyEvent,", " MouseEvent = Packages.processing.event.MouseEvent,", " TouchEvent = Packages.processing.event.TouchEvent"); evalJS(js, // imports Processing's awt classes. "var PGraphicsJava2D = Packages.processing.awt.PGraphicsJava2D,", " PShapeJava2D = Packages.processing.awt.PShapeJava2D,", " PSurfaceAWT = Packages.processing.awt.PSurfaceAWT"); evalJS(js, // imports Processing's javafx classes. "var PGraphicsFX2D = Packages.processing.javafx.PGraphicsFX2D,", " PSurfaceFX = Packages.processing.javafx.PSurfaceFX"); evalJS(js, // imports Processing's opengl classes. "var FontTexture = Packages.processing.opengl.FontTexture,", " FrameBuffer = Packages.processing.opengl.FrameBuffer,", " LinePath = Packages.processing.opengl.LinePath,", " LineStroker = Packages.processing.opengl.LineStroker,", " PGL = Packages.processing.opengl.PGL,", " PGraphics2D = Packages.processing.opengl.PGraphics2D,", " PGraphics3D = Packages.processing.opengl.PGraphics3D,", " PGraphicsOpenGL = Packages.processing.opengl.PGraphicsOpenGL,", " PJOGL = Packages.processing.opengl.PJOGL,", " PShader = Packages.processing.opengl.PShader,", " PShapeOpenGL = Packages.processing.opengl.PShapeOpenGL,", " PSurfaceJOGL = Packages.processing.opengl.PSurfaceJOGL,", " Texture = Packages.processing.opengl.Texture,", " VertexBuffer = Packages.processing.opengl.VertexBuffer"); evalJS(js, // imports some useful Java classes. "var ArrayList = java.util.ArrayList,", " LinkedList = java.util.LinkedList,", " ArrayDeque = java.util.ArrayDeque,", " HashMap = java.util.HashMap,", " WeakHashMap = java.util.WeakHashMap,", " HashSet = java.util.HashSet,", " LinkedHashSet = java.util.LinkedHashSet,", " TreeSet = java.util.TreeSet,", " Collections = java.util.Collections,", " Arrays = java.util.Arrays,", " Objects = java.util.Objects,", " Optional = java.util.Optional,", " Comparator = java.util.Comparator,", " Timer = java.util.Timer", " TimerTask = java.util.TimerTask", " Scanner = java.util.Scanner", " File = java.io.File,", " FileFilter = java.io.FileFilter,", " FilenameFilter = java.io.FilenameFilter,", " BufferedReader = java.io.BufferedReader,", " FileReader = java.io.FileReader,", " PrintWriter = java.io.PrintWriter,", " InputStream = java.io.InputStream,", " OutputStream = java.io.OutputStream,", " IOException = java.io.IOException,", " StringBuilder = java.lang.StringBuilder,", " System = java.lang.System,", " Cloneable = java.lang.Cloneable", " Comparable = java.lang.Comparable", " Iterable = java.lang.Iterable", " Runnable = java.lang.Runnable", " Thread = java.lang.Thread", " ThreadGroup = java.lang.ThreadGroup", " ThreadLocal = java.lang.ThreadLocal", " Character = java.lang.Character", " Byte = java.lang.Byte", " Short = java.lang.Short", " Integer = java.lang.Integer", " Long = java.lang.Long", " Float = java.lang.Float", " Double = java.lang.Double", " Random = java.lang.Random", " StrictMath = java.lang.StrictMath"); evalJS(js, // transfers all PConstants' to JS global scope. "void function () {", " for each (var f in PConstants.class.getFields()) {", " var name = f.getName(), field = PConstants[name]", " if (!this[name]) this[name] = field", " }", "} ()"); evalJS(js, // transfers all PApplet's static fields to JS global scope. "void function () {", " for each (var f in PApplet.class.getFields()) {", " var name = f.getName(), field = PApplet[name]", " if (field && !this[name]) this[name] = field", " }", "} ()"); evalJS(js, // transfers all PApplet's static methods to JS global scope. "void function () {", " for each (var m in PApplet.class.getDeclaredMethods()) {", " var name = m.getName(), method = PApplet[name]", " if (method && !this[name]) this[name] = method", " }", "} ()"); // Injects PApplet's non-static members to JS global scope: evalJS(js, "Object.bindProperties(this, p)"); evalJS(js, // transfers JS' Math static properties to global scope. "void function () {", " for each (var prop in Object.getOwnPropertyNames(Math))", " if (!this[prop]) this[prop] = Math[prop]", "} ()"); } @SafeVarargs static final String evalJS (final ScriptEngine js, final String... statements) { if (statements == null) return ""; final String expression = PApplet.join(statements, PConstants.ENTER); try { js.eval(expression); } catch (final ScriptException cause) { PApplet.println(cause); System.err.println(expression); throw new RuntimeException(cause); } return expression; } @SafeVarargs static final CompiledScript compileJS (final ScriptEngine js, final String... statements) { final String expression = statements != null? PApplet.join(statements, PConstants.ENTER) : ""; try { return ((Compilable) js).compile(expression); } catch (final ScriptException cause) { PApplet.println(cause); System.err.println(expression); throw new RuntimeException(cause); } } static final Object runJS (final CompiledScript compiled) { try { return compiled.eval(); } catch (final ScriptException cause) { PApplet.println(cause); throw new RuntimeException(cause); } } @SafeVarargs static final Object invokeJS (final ScriptEngine js, final String funct, final Object... args) { try { return ((Invocable) js).invokeFunction(funct, args); } catch (final Exception cause) { PApplet.println(cause); System.err.println(funct); PApplet.printArray(args); throw new RuntimeException(cause); } }
Let's try to fix it by parts: ~:>
http://docs.oracle.com/javase/8/docs/api/java/io/File.html#File-java.lang.String-File dir = new File("C:/Users/XXX/Desktop/Files");
P.S.: Yet it's good practice placing files used by a sketch inside its "/data/" subfolder!
http://docs.oracle.com/javase/8/docs/api/java/io/File.html#listFiles-java.io.FileFilter-File[] filenames = dir.listFiles(TXTFILES);
models = new OBJModel[len];
String[][] files
!files = new String[len][];
Here's what I've come up w/ after modifying your latest attempt: O:-)
// forum.processing.org/two/discussion/10216/
// read-text-files-from-directory-into-an-array-of-arrays
import java.io.FilenameFilter;
static final FilenameFilter TXTFILES = new FilenameFilter() {
@ Override boolean accept(File f, String s) {
return s.endsWith(".txt");
}
};
String[][] txts;
void setup() {
File dir = new File("C:/Users/XXX/Desktop/Files");
File[] filenames = dir.listFiles(TXTFILES);
int len = filenames.length;
println("Found", len, "text file(s) in folder:\n" + dir + '\n');
printArray(filenames);
println();
txts = new String[len][];
for (int i = 0; i != len; txts[i] = loadStrings(filenames[i++]));
printArray(txts[0]);
exit();
}
// forum.processing.org/two/discussion/10052/
// scan-directory-and-print-folders-name
import java.io.FileFilter;
final FileFilter FOLDER_FILTER = new FileFilter() {
boolean accept(File f) {
return f.isDirectory();
}
};
File folder = dataFile("");
File[] dirs = folder.listFiles(FOLDER_FILTER);
println(folder);
println();
printArray(dirs);
println();
String[] dirNames = new String[dirs.length];
for (int i = 0; i != dirs.length; dirNames[i] = dirs[i++].getName());
printArray(dirNames);
exit();
@Moxl, your code is OK if you don't have nested folders,...
Actually, his only got folders inside "/data/". If there are any deeper subfolders within them, they're ignored.
Nonetheless, I did a shorter version of his using dataFile("") + listFiles() w/o any FileFilter: B-)
// forum.processing.org/two/discussion/6712/
// get-the-number-of-folders-in-data-path
int getNumDataFolders() {
int count = 0;
for ( File f: dataFile("").listFiles() )
if (f.isDirectory()) ++count;
return count;
}
void setup() {
int num = getNumDataFolders();
println(num);
exit();
}
Alternative version using FileFilter + listFiles() in order to recursively get a folders-only List: :bz
/**
* Get All Sub-Folders (v1.11)
* by GoToLoop (2014/Aug)
*
* forum.processing.org/two/discussion/6712/
* get-the-number-of-folders-in-data-path
*
* forum.processing.org/two/discussion/6677/
* splitting-a-text-file-using-crlf-and-parsing-file-
*/
import java.util.List;
import java.io.FileFilter;
static final FileFilter FOLDER_FILTER = new FileFilter() {
@ Override boolean accept(File path) {
return path.isDirectory();
}
};
File[] dirs;
void setup() {
boolean gotParam = args.length > 0 && !args[0].startsWith("--");
String path = gotParam? args[0] : dataPath("");
if ((dirs = getAllFolders(path)) == null || dirs.length == 0) {
println("Got no folders in \"" + path + "\"\n");
exit();
return;
}
println("Found " + dirs.length + " folder(s) in \"" + path + "\"\n");
println(dirs);
exit();
}
static final File getAllFolders(String dirPath)[] {
File f = new File(dirPath);
if (!f.isDirectory()) {
println("\nPath \"" + dirPath + "\" isn't a folder!\n");
return null;
}
List<File> folders = new ArrayList();
recursiveFolders(f, folders);
return folders.toArray( new File[folders.size()] );
}
static final void recursiveFolders(File dirPath, List<File> folders) {
for (File dir: dirPath.listFiles(FOLDER_FILTER)) {
folders.add(dir);
recursiveFolders(dir, folders);
}
}
I can only select folders?
That's true! It uses selectFolder() rather than selectInput():
http://processing.org/reference/selectFolder_.html
http://processing.org/reference/selectInput_.html
And when I select one I still get a black screen.
As you can see inside new
FilenameFilter():
final String[] EXTS = {
".png", ".jpg", ".jpeg", ".gif"
};
It only reads file names w/ those extensions! So we gotta choose a folder w/ at least 1 of those type of files.
listFiles() invokes that accept() customized method in order to filter them out.
As I've already mentioned, you gotta replace those w/ the 1s you're gonna need!
This thread below got a full example on how to get a File[] from some user-chosen folder:
http://forum.processing.org/two/discussion/6004/how-to-make-a-movie-array
Basically we use FilenameFilter interface + listFiles() method in order to only get the extensions we want to:
import java.io.FilenameFilter;
static final FilenameFilter pictFilter = new FilenameFilter() {
final String[] EXTS = {
".png", ".jpg", ".jpeg", ".gif"
};
@ Override boolean accept(final File dir, String name) {
name = name.toLowerCase();
for (final String ext: EXTS) if (name.endsWith(ext)) return true;
return false;
}
};
Just replace the image extensions w/ audio 1s. Of course, rename pictFilter to something like sndFilter! (*)
Hello guys I am really struggling to create a traverse file where upon opening the processing you will be presented with 3 or 2 options, then after choosing one you will be sent to another file where you can choose another one of the 3 or 2 option etc ... its suppose to look like a slot machine .... this is for a university work and the dead line is very soon, we are really quite struggling with this. ...
This is what we have so far ... it does go through the folders using: currentFolder = new Folder("1810-1830/Cornwall/Mine/Camborne"); but we only know how to do this manually ... can you please help? hope this makes sense
Traverse file code that we have at the moment is below:
class Folder {
java.io.File folder;
String[] images;
java.io.File[] folders;
String[] choices = new String[3];
String path;
JSONObject info;
String title;
int[] scores = new int[3];
String[] choicesText = new String[3];
// CONSTRUCTOR
Folder(String p) {
path = p;
// we'll have a look in the data folder
folder = new java.io.File(dataPath(path));
// GET IMAGES
java.io.FilenameFilter pngFilter = new java.io.FilenameFilter() {
boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".png");
}
};
// list the files in the data folder, passing the filter as parameter
images = folder.list(pngFilter);
java.io.FileFilter directoryFilter = new java.io.FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
folders = folder.listFiles(directoryFilter);
info = loadJSONObject(path + "/" + "info.json");
title = info.getString("title");
JSONArray rawScores = info.getJSONArray("score");
for (int i = 0; i < rawScores.size(); i++){
scores[i] = rawScores.getInt(i);
}
JSONArray text = info.getJSONArray("options");
for (int m = 0; m < text.size(); m++){
choicesText[m] = text.getString(m);
}
println(choicesText);
}
int getFolderNum(){
return folders.length;
}
String[] getImages(){
String[] paths = new String[images.length];
for (int i = 0; i < images.length; i++){
paths[i] = path + "/" + images[i];
}
return paths;
}
String getFolderPath(){
return path;
}
}
Yes, I more or less would like to show gifs only and hoped for a processing way, since I still know close to nothing about Java. The Arduino IDE uses Java as well, but you hardly need to know it to write a sketch for the microcontroller-board.
When searching for animated gifs I probably will save them to my standard download folder, which often is filled with tons of different filetypes. Using a filefilter while selecting and sorting on date would give me easy access.
I have been reading on this Forum for a few days though, notice... quite a lot is done with Java and I'll probably just need to step in.
Thank you for the links, I'll check whether I can easily use JFileChooser and the File class or... have to start with an "Hello World" java-application first. If it's not to difficult for me to integrate I'll use it, otherwise I'll stick with selectinput() for now, work on a more easy user interface as changing variables in my sketch and look into Java after that.
Hi. I've been making an image mosaic collage android application using processing 2.0.3.
I made this application available with CASE 1 code and get the image above. Though, as you can see below, this code loops unusefully because of the structure.(I calculate all color of image in draw() because of file and folder selections. Maybe I did use wrong codes.). So I'm trying to fix this code not to loop unusefully. So I fix the code like CASE 2 but it doesn't work because of NullPointerException. I found a problem that some calculated arrays(myArrayR, myArrayG, myArrayB..) in flagA sentence did not send their values to flagB sentence. I've tried moving color calculating part into -->void folderselected()... but it didn't work either. How can I make my code like CASE 2 or is there any way to avoid unusefully loop of flagA sentence? Help me please.. I'm begging you. I've been trying to fix this problem for weeks... I'm leaving images that describe my CASE 1 and CASE 2 codes.Thank you for read!! :) CASE 1 :Wokrs well but loop unusefully
CASE 2 :NullPointerException error in flagB part
Whole code of CASE 1
//for filefilter
import java.io.File;
import java.io.FilenameFilter;
//for GUI controller(icons)
import controlP5.*;
ControlP5 cp5;
//for searching filess and folders
import select.files.*;
public boolean accept;
//select the source image folder and a basic image
SelectLibrary folders;
int flagA = 4;
String folderadr;
SelectLibrary files;
int flagB = 0;
int flagD = 0;
PImage originalImage;
//setting the size of grids, transparency and accuracy
int gridnum;
int gridsize = 15;
int tran = 255;
int brightness = 255;
int quality = 2;
//finding average colors of original image
int[] mini;
int[] AverageR;
int[] AverageG;
int[] AverageB;
int loc = 0;
//to pick up only image(jpg, png, gif..) files
java.io.File folder;
java.io.FilenameFilter jpgFilter;
//to get image files' names to use loadimage() for analysing
String[] filenames;
PImage[] myImage;
int[] myArrayR;
int[] myArrayG;
int[] myArrayB;
//to find the colosest image in color to the original image
int[][] delta;
void setup(){
size(displayWidth, displayHeight);
//for file select
files = new SelectLibrary(this);
files.selectInput("Select a file to process:", "fileSelected");
//for folder select
folders = new SelectLibrary(this);
folders.selectFolder("Select a folder to process:", "folderSelected");
//for placing several icons
int lll = floor(displayWidth/20);
cp5 = new ControlP5(this);
//grid 7 button
cp5.addButton("buttonA")
.setPosition(lll,displayHeight-48)
.setImages(loadImage("1.gif"), loadImage("1.gif"), loadImage("6.gif"))
.updateSize();
//grid 10 button
cp5.addButton("buttonB")
.setPosition(lll*4,displayHeight-48)
.setImages(loadImage("2.gif"), loadImage("2.gif"), loadImage("6.gif"))
.updateSize();
//process button
cp5.addButton("buttonC")
.setPosition(lll*7,displayHeight-48)
.setImages(loadImage("3.gif"), loadImage("3.gif"), loadImage("6.gif"))
.updateSize();
//high acuracy button
cp5.addButton("buttonD")
.setPosition(lll*14,displayHeight-48)
.setImages(loadImage("4.gif"), loadImage("4.gif"), loadImage("6.gif"))
.updateSize();
//low accuracy button
cp5.addButton("buttonE")
.setPosition(lll*17,displayHeight-48)
.setImages(loadImage("5.gif"), loadImage("5.gif"), loadImage("6.gif"))
.updateSize();
}
//grid 7 button
public void buttonA(int theValue) {
println("a button event from buttonA: "+theValue);
gridsize = 7;
}
//grid 10 button
public void buttonB(int theValue) {
println("a button event from buttonB: "+theValue);
//flagD = 1;
gridsize = 10;
}
//process button
public void buttonC(int theValue) {
println("a button event from buttonC: "+theValue);
//quality = 3;
flagD = 1;
}
//high acuracy button
public void buttonD(int theValue) {
println("a button event from buttonD: "+theValue);
quality = 1;
}
//low accuracy button
public void buttonE(int theValue) {
println("a button event from buttonE: "+theValue);
quality = 3;
}
//select the source folder and a basic image
void fileSelected(File selection) {
if (selection == null) {
println("Nothing was selected.");
} else {
println("User selected " + selection.getAbsolutePath());
originalImage = loadImage(selection.getAbsolutePath());
flagB = 1;
}
}
void folderSelected(File selection) {
if (selection == null) {
println("Nothing was selected.");
} else {
println("User selected " + selection.getAbsolutePath());
folderadr = (selection.getAbsolutePath());
println(folderadr);
flagA = 1;
}
}
void draw(){
//run after the folder selection - flagA
if (flagA == 1){
java.io.File folder = new java.io.File(dataPath(folderadr));
java.io.FilenameFilter jpgFilter = new java.io.FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".png");
}
};
String[] filenames = folder.list(jpgFilter);
PImage[] myImage = new PImage[filenames.length];
int[] myArrayR = new int[myImage.length];
int[] myArrayG = new int[myImage.length];
int[] myArrayB = new int[myImage.length];
//find average RGB color values of multiple images
for (int a = 0; a < filenames.length; a++){
myImage[a] = loadImage(folderadr+"//" + filenames[a]);
myImage[a].loadPixels();
int sr = 0;
int sg = 0;
int sb = 0;
for (int x = 0; x < (myImage[a].width)*(myImage[a].height); x = x + quality){
color b = myImage[a].pixels[x]; // get color values without displaying
int br = int(red(b));
int bg = int(green(b));
int bb = int(blue(b));
sr = sr + br;
sg = sg + bg;
sb = sb + bb;
}
myArrayR[a] = sr/((myImage[a].width)*(myImage[a].height)/quality);
myArrayG[a] = sg/((myImage[a].width)*(myImage[a].height)/quality);
myArrayB[a] = sb/((myImage[a].width)*(myImage[a].height)/quality);
}
//run after the file(originalImage) selection - flagB
if (flagB == 1){
image(originalImage,0,0);
for (int a = 0; a < filenames.length; a++){
println("flagB = "+ flagB + " myArrayR,G,B =" + myArrayR[a]+","+myArrayG[a]+","+myArrayB[a]);
}
//finding average colors of original image
gridnum = (ceil((originalImage.width)/gridsize))*(ceil((originalImage.height)/gridsize));
int[] mini = new int[gridnum];
int[] AverageR = new int[gridnum];
int[] AverageG = new int[gridnum];
int[] AverageB = new int[gridnum];
int[][] delta = new int[gridnum][myImage.length];
//run when the "process" button was pushed
if (flagD == 1){
int m = ceil(480/gridsize);
originalImage.loadPixels();
//start analysing the "k" th grid
for (int k = 0; k < (ceil((originalImage.width)/gridsize))*(ceil((originalImage.height)/gridsize)); k++){
int h = gridsize*floor(k/m);
int w = gridsize*(k - (h/gridsize)*(ceil(originalImage.width/gridsize)));
// get average colors of each area of original image
int SumOfR = 0;
int SumOfG = 0;
int SumOfB = 0;
int AverR = 0;
int AverG = 0;
int AverB = 0;
int l = w+(h*originalImage.width);
for (int a = 0; a < gridsize; a++){
for (int c = 0; c < gridsize; c++){
color myPixel = originalImage.pixels[l+a+(originalImage.width*c)];
int R = int (red(myPixel));
int G = int (green(myPixel));
int B = int (blue(myPixel));
SumOfR = SumOfR + R;
SumOfG = SumOfG + G;
SumOfB = SumOfB + B;
}
}
AverR = SumOfR / (gridsize * gridsize);
AverG = SumOfG / (gridsize * gridsize);
AverB = SumOfB / (gridsize * gridsize);
AverageR[k] = AverR;
AverageG[k] = AverG;
AverageB[k] = AverB;
for(int i = 0; i < myImage.length; i++){
delta[k][i] = (AverageR[k]-myArrayR[i])*(AverageR[k]-myArrayR[i]) + (AverageG[k]-myArrayG[i])*(AverageG[k]-myArrayG[i]) + (AverageB[k]-myArrayB[i])*(AverageB[k]-myArrayB[i]);
}
mini[k] = min(delta[k]);
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
for(int j = 0; j < myImage.length; j++){
if(mini[k] == delta[k][j]){
//tint(brightness, tran);
image(myImage[j], w, h, gridsize, gridsize);
}
}
flagA = 7;
} //end analysing the "k" th grid
} //if flagD == 1
} //if flagB == 1
} //if flagA == 1
} //void draw()
:D