Processing - cannot convert float to int - compilation
I have a code like this:
float[] x = {5,11,17,23,26,23,18,12,7,4,5,6,7,6,3,2,5,5,4,3,3,5,10,18,26,32,26,18,10,5,2,10,12,14,15,9,8,14,13,9,7,5,3,8,17,33,49,32,16,7,3,1,13,16,23,31,26,25,30,22,14,9,7,0,1,9,38,101,38,9,0,1,0,12,17,32,60,89,88,59,30,15,8,6,6,14,19,10,279,10,19,14,8,3,6,10,26,89,360,359,88,25,9,4,2,10,30,82,259,1000,260,82,32,13,5,5,9,26,89,358,359,89,26,9,4,3,6,13,19,9,280,9,20,14,8,3,11,17,31,60,89,89,60,31,16,9,6,0,1,9,38,102,38,9,0,1,0,12,16,23,30,25,25,31,22,14,10,7,3,8,17,33,50,33,17,8,3,1,9,11,13,14,8,9,15,13,10,7,6,5,10,18,27,33,27,18,11,6,3,5,6,6,6,2,3,6,6,5,4,1,5,11,18,24,27,24,18,12,7,3};
void setup(){
size(620,620);
float k=1;
float q=0;
for (float j=0;j<height;j=j+30){
if(k%2!=0){
for(float i=30;i<width;i=i+60){
fill(kolor(x[q]));
rect(i,j,20,20);
q=q+1;
}
k++;
} else {
for(float i=0;i<width;i=i+60){
fill(kolor(x[q]));
rect(i,j,20,20);
q=q+1;
}
k++;
}
}
}
float kolor(float input){
return map(input,0,1000,0,255);
}
When I try to compile, I get "cannot convert float to int" error, connected with lines fill(kolor(x[q]));.
I tried changing this to fill((int)kolor(x[q]));.
Do you have any idea how to fix this?
The problem with line fill((int)kolor(x[q]) is that x is an array, and you can only access array members by using ints, while you access it using q which is a float.
Try changing float q = 0; to int q = 0;
By the way, it looks like java code, is it java?
Why are you using floats in the first place? You probably should be using ints, especially with the % in there.
Here is the signature of the fill() command, for those interested.
Related
Segmentation Fault accessing qpscale_table in AVFrame
I'm modifying this file slightly: https://gist.github.com/yohhoy/f0444d3fc47f2bb2d0e2 This code decodes a video and makes opencv Mats out of the frame pixels as it goes. In particular I only want to grab frames that have specific macroblock-related data. I'm attempting to get that data like this: total_qp = get_total_qp(decframe->qscale_table, mb_width, mb_height, mb_stride); However, whenever I try to access the data by iterating over that array, I get a segmentation fault: static float get_total_qp(int8_t *qscale_table, int mb_width, int mb_height, int mb_stride) { int mb_count = mb_height * mb_width; int y, x; float qp_total = 0.0f; for (y = 0; y < mb_height; y++) { for (x = 0; x < mb_width; x++) { qp_total += qscale_table[x + y * mb_stride]; <-- SEGFAULT here } } return qp_total; } I've also tried sending in: frame->qscale_table and I've tried populating it, but this own't compile because it can't find that function: int8_t *qscale_table = av_frame_get_qp_table(decframe->qscale_table, &mb_stride, &qscale_type); So my question is this: Given an AVFrame* how do I ensure that the qscale_table is populated and access it?
It turns out that the qpscale_table doesn't get exported onto the decoded frame after the decoding happens in h264dec.c. In order to retrieve the values I had to modify the finalize_frame method in h264dec to export the qscale_table onto the frame, like so: static int h264_export_qp_table(H264Context *h, AVFrame *f, H264Picture *p, int qp_type) { AVBufferRef *ref = av_buffer_ref(p->qscale_table_buf); int offset = 2*h->mb_stride + 1; if(!ref) return AVERROR(ENOMEM); av_assert0(ref->size >= offset + h->mb_stride * ((f->height+15)/16)); ref->size -= offset; ref->data += offset; return av_frame_set_qp_table(f, ref, h->mb_stride, f->qscale_type); } and add in the call into finalize_frame: ... if (CONFIG_MPEGVIDEO) { ff_print_debug_info2(h->avctx, dst, NULL, out->mb_type, out->qscale_table, out->motion_val, NULL, h->mb_width, h->mb_height, h->mb_stride, 1); // NT: make the qscale_table accessible! h264_export_qp_table(h, dst, out, FF_QSCALE_TYPE_H264); } ... And then recompile FFmpeg using these instructions: https://trac.ffmpeg.org/wiki/CompilationGuide/Ubuntu
Cannot convert from float to int Processing/Java
I have some code here: int mutate(float x){ if (random(1) < .1){ float offset = randomGaussian()/2; float newx = x + offset; return newx; } else { return x; } } This code gives an error on both samples of returning a value saying "Type mismatch: Cannot convert from float to int." What is wrong with my code? Thanks in advance.
You need to change the return type to float in order to return decimal values (if that's what you are interested in): float mutate(float x){ if (random(1) < .1){ float offset = randomGaussian()/2; float newx = x + offset; return newx; } else { return x; } }
First off, remember what int and float are: int can only hold whole numbers without decimal places, like 1, 42, and -54321. float can hold numbers with decimal places, like 0.25, 1.9999, and -543.21. So, you need to figure out what you meant to return from your function: should it be an int or a float value? If it's supposed to be a float value, then you can simply change the return type of the function to float. If you want it to return an int value, then you'll have to rethink the logic inside your function so it's using int values instead. Note that you can convert from a float to an int using the int() function. More info can be found in the reference.
Matrix Text rain effect in Processing 3.3
I'm working on making a matrix text rain effect in Processing 3.3 as a simple starter project for learning the processing library and Java. My code so far: class Symbol { int x, y; int switchInterval = round(random(2, 50)); float speed; char value; Symbol(int x, int y, float speed) { this.x = x; this.y = y; this.speed = speed; } //Sets to random symbol based on the Katakana Unicode block void setToRandomSymbol() { if(frameCount % switchInterval == 0) { value = char((int) random(0x30A0, 0x3100)); } } //rains the characters down the screen and loops them to the top when they // reach the bottom of the screen void rain() { if(y <= height) { y += speed; }else { y = 0; } } } Symbol symbol; class Stream { int totalSymbols = round(random(5, 30)); Symbol[] symbols = new Symbol[500]; float speed = random(5, 20); //generates the symbols and adds them to the array, each symbol one symbol //height above the one previous void generateSymbols() { int y = 0; int x = width / 2; for (int i = 0; i <= totalSymbols; i++) { symbols[i] = new Symbol(x, y, speed); symbols[i].setToRandomSymbol(); y -= symbolSize; } } void render() { for(Symbol s : symbols) { fill(0, 255, 70); s.setToRandomSymbol(); text(s.value, s.x, s.y); s.rain(); } } } Ok, so that was a lot of code, Let me explain my dilemma. The issue I'm having is that when I run the code I get a NullpointerException at the s.setToRandomSymbol(); method call in the for each loop in the render function. The weird part about this NullPointerException error and the part I'm not understanding is that it's being thrown on a method that doesn't take in any arguments that could be coming back empty, and the method itself is void, so it shouldn't be returning anything, right? Why is this returning Null and what did I do wrong to have it return this way?
First you come up with a random number betwen 5 and 30: int totalSymbols = round(random(5, 30)); Then you create an array that holds 500 instances of your Symbol class: Symbol[] symbols = new Symbol[500]; Note that this array holds 500 null values at this point. Then you add a maximum of 30 instances of Symbol to your array: for (int i = 0; i <= totalSymbols; i++) { symbols[i] = new Symbol(x, y, speed); Note that this array now holds at least 470 null values at this point. Then you iterate over all 500 indexes: for(Symbol s : symbols) { s.setToRandomSymbol(); But remember that at least 470 of these indexes are null, which is why you're getting a NullPointerException. Some basic debugging would have told you all of this. I would have started by adding a basic println() statement just before you get the error: for(Symbol s : symbols) { println("s: " + s); s.setToRandomSymbol(); This would have showed you that you're iterating over null values. Anyway, to fix your problem you need to stop iterating over your entire array, or you need to stop making room for indexes you never use. In the future, please try to narrow your problem down to a MCVE before posting. Note that this much smaller example program shows your error: String[] array = new String[10]; array[0] = "test"; for(String s : array){ println(s.length()); }
Simple image processing algorithm causes Processing to freeze
I've written an algorithm in Processing to do the following: 1. Instantiate a 94 x 2 int array 2. Load a jpg image of dimensions 500 x 500 pixels 3. Iterate over every pixel in the image and determine whether it is black or white then change a variable related to the array 4. Print the contents of the array For some reason this algorithm freezes immediately. I've put print statements in that show me that it freezes before even attempting to load the image. This is especially confusing to me in light of the fact that I have written another very similar algorithm that executes without complications. The other algorithm reads an image, averages the color of each tile of whatever size is specified, and then prints rectangles over the region that was averaged with the average color, effectively pixelating the image. Both algorithms load an image and examine each of its pixels. The one in question is mostly different in that it doesn't draw anything. I was going to say that it was different for having an array but the pixelation algorithm holds all of the colors in a color array which should take up far more space than the int array. From looking in my mac's console.app I see that there was originally this error: "java.lang.OutOfMemoryError: GC overhead limit exceeded". From other suggestions/sources on the web I tried bumping the memory allocation from 256mb to 4000mb (doing this felt meaningless because my analysis of the algorithms showed they should be the same complexity but I tried anyways). This did not stop freezing but changed the error to a combination of "JavaNativeFoundation error occurred obtaining Java exception description" and "java.lang.OutOfMemoryError: Java heap space". Then I tried pointing processing to my local jdk with the hope of utilizing the 64 bit jdk over processing's built in 32 bit jdk. From within Processing.app/Contents I executed the following commands: mv Java java-old ln -s /Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk Java Processing would not start after this attempt with the following error populating my console: "com.apple.xpc.launchd[1]: (org.processing.app.160672[13559]) Service exited with abnormal code: 1" Below is my code: First the noncompliant algorithm int squareSize=50; int numRows = 10; int numCols = 10; PFont myFont; PImage img; //33-126 void setup(){ size(500,500); count(); } void count(){ ellipseMode(RADIUS); int[][] asciiArea = new int[94][2]; println("hello?"); img=loadImage("countingPicture.jpg"); println("image loaded"); for(int i=0; i<(500/squareSize); i++){ for(int j=0; j<(500/squareSize); j++){ int currentValue=i+j*numCols; if(currentValue+33>126){ break; } println(i+", "+j); asciiArea[currentValue][0]=currentValue+33; asciiArea[currentValue][1]=determineTextArea(i,j,squareSize); //fill(color(255,0,0)); //ellipse(i*squareSize,j*squareSize,3,3); } } println("done calculating"); displayArrayContents(asciiArea); } int determineTextArea(int i, int j, int squareSize){ int textArea = 0; double n=0.0; while(n < squareSize*squareSize){ n+=1.0; int xOffset = (int)(n%((double)squareSize)); int yOffset = (int)(n/((double)squareSize)); color c = img.get(i*squareSize+xOffset, j*squareSize+yOffset); if(red(c)!=255 || green(c)!=255 || blue(c)!=255){ println(red(c)+" "+green(c)+" "+blue(c)); textArea++; } } return textArea; } void displayArrayContents(int[][] arr){ int i=0; println("\n now arrays"); while(i<94){ println(arr[i][0]+" "+arr[i][1]); } } The pixelation algorithm that works: PImage img; int direction = 1; float signal; int squareSize = 5; int wideness = 500; int highness = 420; int xDimension = wideness/squareSize; int yDimension= highness/squareSize; void setup() { size(1500, 420); noFill(); stroke(255); frameRate(30); img = loadImage("imageIn.jpg"); color[][] colors = new color[xDimension][yDimension]; for(int drawingNo=0; drawingNo < 3; drawingNo++){ for(int i=0; i<xDimension; i++){ for(int j=0; j<yDimension; j++){ double average = 0; double n=0.0; while(n < squareSize*squareSize){ n+=1.0; int xOffset = (int)(n%((double)squareSize)); int yOffset = (int)(n/((double)squareSize)); color c = img.get(i*squareSize+xOffset, j*squareSize+yOffset); float cube = red(c)*red(c) + green(c)*green(c) + blue(c)*blue(c); double grayValue = (int)(sqrt(cube)*(255.0/441.0)); double nAsDouble = (double)n; average=(grayValue + (n-1.0)*average)/n; average=(grayValue/n)+((n-1.0)/(n))*average; } //average=discretize(average); println(i+" "+j+" "+average); colors[i][j]=color((int)average); fill(colors[i][j]); if(drawingNo==0){ //stroke(colors[i][j]); } stroke(210);} if(drawingNo==1){ stroke(150); } if(drawingNo==2){ stroke(90); } //stroke(colors[i][j]); rect(drawingNo*wideness+i*squareSize,j*squareSize,squareSize,squareSize); } } } save("imageOut.jpg"); }
You're entering an infinite loop, which makes the println() statements unreliable. Fix the infinite loop, and your print statements will work again. Look at this while loop: while(i<94){ println(arr[i][0]+" "+arr[i][1]); } When will i ever become >= 94? You never increment i, so its value is always 0. You can prove this by adding a println() statement inside the while loop: while(i<94){ println("i: " + i); println(arr[i][0]+" "+arr[i][1]); } You probably wanted to increment i inside the while loop. Or just use a for loop instead.
Use class method as `op` argument to `accumulate`
I'm trying to create a class that calculates its variance from a vector<float>. It should do this by using its previously calculated this->mean in diffSquaredSum. I'm trying to call the method diffSquaredSum inside of accumulate but have no idea what the magical syntax is. What is the correct syntax to use the diffSquaredSum class method as the op argument to accumulate in setVariance? float diffSquaredSum(float sum, float f) { // requires call to setMean float diff = f - this->mean; float diff_square = pow(diff,2); return sum + diff_square; } void setVariance(vector<float>& values) { size_t n = values.size(); double sum = accumulate( values.begin(), values.end(), 0, bind(this::diffSquaredSum)); this->variance = sum / n; }
double sum = std::accumulate( values.begin(), values.end(), 0.f, [&](float sum, float x){ return diffSquaredSum(sum,x);} ); bind is only rarely useful. Prefer lambdas, they are easier to write and read. You could instead get fancy with binding, but why?