Triggering infinite animated objects - arrays

I would like to display, in Processing, one photo fading up and fading down over 15 seconds, with a second photo doing the same one second later, and another, etc, ad infinitum.
This example displays 15 objects, but they all start together:
PImage[] imgs = new PImage[42];
int Timer;
Pic[] pics = new Pic[15];
void setup() {
size(1000, 880);
for (int i = 0; i < pics.length; i++) {
pics[i] = new Pic(int(random(0, 29)), random(0, 800), random(0, height));
}
for (int i = 0; i < imgs.length; i++) {
imgs[i] = loadImage(i+".png");
}
}
void draw() {
background(255);
for (int i = 0; i < pics.length; i++) {
pics[i].display();
}
}
class Pic {
float x;
float y;
int num;
int f = 0;
boolean change = true;
Pic(int tempNum, float tempX, float tempY) {
num = tempNum;
x = tempX;
y = tempY;
}
void display() {
imageMode(CENTER);
if (change)f++;
else f--;
if (f==0||f==555)change=!change;
tint(0, 153, 204, f);
image(imgs[num], x, y);
}
}
Thanks!!!

The main issue is you're updating/rendering all images all Pic instances at once. Perhaps you meant to display one at a time (one after the other).
There other sections that raise questions as well:
Timer is never used: it's a good idea to simplify/cleanup code as much as possible
f is used for both the tint alpha (0-255 range) and to fake a delay across multple frames (==555 check)
num is asigned to a random value which means potentially the same pic may be repeated (potentially even consecutively ?) making it hard to notice the effect
I recommend slowing down and breaking the problem down:
fade a single image in and out
determine when a fade in/out cycle is complete
increment a single index (so the next image can fade in and out)
Ideally you want to take the timing (15 seconds into account).
You can work out across how many frames you'd need to fade over 15 seconds. Processing's frameRate property can help with that:
numAlphaSteps = 15 * frameRate;
(e.g. at 60 fps that would be 15 * 60 = 900 frames)
That being said, it takes a few frames for frameRate to "warm up" and become stable. The safer option would be to call frameRate() passing the resired frames per second and reusing that number for the animation
The next step is to map each increment to an alpha value, as it needs to ramp up and back down. You could use a bit of arithmetic.
If you subtract half the number of total fade frames (e.g. 900 / 2 = 450) from each frame number you'd get a value that goes from -half the number of frames to half the number of frames. Here's a minimal sketch you can try out:
int numFrames = 10;
int numFramesHalf = numFrames / 2;
for(int i = 0 ; i < numFrames; i++){
println("frame index", i, "ramp value", i - numFramesHalf);
}
Here's the same, visualised:
background(0);
int numFrames = 10;
int numFramesHalf = numFrames / 2;
for(int i = 0 ; i < numFrames; i++){
int ramp = i - numFramesHalf;
println("frame index", i, "ramp value", ramp);
// visualise numbers
fill(0, 128, 0);
rect(i * 10, 50, 10, map(ramp, 0, 5, 0, 39));
fill(255);
text(i + "\n" + ramp, i * 10, height / 2);
}
(Feel free to change numFrames to 900, 10 is easier to see in console).
If you pass the subtraction result to abs() you'll get positive values:
int numFrames = 10;
int numFramesHalf = numFrames / 2;
for(int i = 0 ; i < numFrames; i++){
println("frame index", i, "ramp value", abs(i - numFramesHalf));
}
and the visualisation:
background(0);
int numFrames = 10;
int numFramesHalf = numFrames / 2;
for(int i = 0 ; i < numFrames; i++){
int ramp = abs(i - numFramesHalf);
println("frame index", i, "ramp value", ramp);
// visualise numbers
fill(0, 128, 0);
rect(i * 10, 0, 10, map(ramp, 0, 5, 0, 39));
fill(255);
text(i + "\n" + ramp, i * 10, height / 2);
}
If you look in Processing Console you should see values that resemble a linear ramp (e.g. large to 0 then back to large).
This is a range that can be easily remapped to a the 0 to 255 range, required for the alpha value, using map(yourValue, inputMinValue, inputMaxValue, outputMinValue, outputMaxValue).
Here's a sketch visualising the tint value going from 0 to 255 and back to 255:
size(255, 255);
int numFrames = 10;
int numFramesHalf = numFrames / 2;
for(int i = 0 ; i <= numFrames; i++){
int frameIndexToTint = abs(i - numFramesHalf);
float tint = map(frameIndexToTint, 0, numFramesHalf, 255, 0);
println("frame index", i, "ramp value", frameIndexToTint, "tint", tint);
rect((width / numFrames) * i, height, 1, -tint);
}
Now with these "ingredients" it should be possible to switch from a for loop draw():
int numFrames = 180;
int numFramesHalf = numFrames / 2;
int frameIndex = 0;
void setup(){
size(255, 255);
}
void draw(){
// increment frame
frameIndex++;
// reset frame
if(frameIndex > numFrames){
frameIndex = 0;
println("fade transition complete");
}
// compute tint
int frameIndexToTint = abs(frameIndex - numFramesHalf);
float tint = map(frameIndexToTint, 0, numFramesHalf, 255, 0);
// visualise tint as background gray
background(tint);
fill(255 - tint);
text(String.format("frameIndex: %d\ntint: %.2f", frameIndex, tint), 10, 15);
}
Notice that using custom index for the transition frame index makes it easy to know when a transition is complete (so it can be reset): this is useful to also increment to the next image:
int numFrames = 180;
int numFramesHalf = numFrames / 2;
int frameIndex = 0;
int imageIndex = 0;
int maxImages = 15;
void setup(){
size(255, 255);
}
void draw(){
// increment frame
frameIndex++;
// reset frame (if larger than transition frames total)
if(frameIndex >= numFrames){
frameIndex = 0;
// increment image index
imageIndex++;
// reset image index (if larger than total images to display)
if(imageIndex >= maxImages){
imageIndex = 0;
}
println("fade transition complete, next image: ", imageIndex);
}
// compute tint
int frameIndexToTint = abs(frameIndex - numFramesHalf);
float tint = map(frameIndexToTint, 0, numFramesHalf, 255, 0);
// visualise tint as background gray
background(tint);
fill(255 - tint);
text(String.format("frameIndex: %d\ntint: %.2f\nimageIndex: %d", frameIndex, tint, imageIndex), 10, 15);
}
These are the main ingredients for your program. You can easily swap the placeholder background drawing with your images:
int numFrames = 180;
int numFramesHalf = numFrames / 2;
int frameIndex = 0;
int imageIndex = 0;
int maxImages = 15;
PImage[] imgs = new PImage[42];
int[] randomImageIndices = new int[maxImages];
void setup(){
size(255, 255);
// load images
for (int i = 0; i < imgs.length; i++) {
imgs[i] = loadImage(i+".png");
}
// pick random images
for (int i = 0; i < maxImages; i++) {
randomImageIndices[i] = int(random(0, 29));
}
}
void draw(){
// increment frame
frameIndex++;
// reset frame (if larger than transition frames total)
if(frameIndex >= numFrames){
frameIndex = 0;
// increment image index
imageIndex++;
// reset image index (if larger than total images to display)
if(imageIndex >= maxImages){
imageIndex = 0;
}
println("fade transition complete, next image: ", imageIndex);
}
// compute tint
int frameIndexToTint = abs(frameIndex - numFramesHalf);
float tint = map(frameIndexToTint, 0, numFramesHalf, 255, 0);
// visualise tint as background gray
background(0);
PImage randomImage =imgs[randomImageIndices[imageIndex]];
tint(255, tint);
image(randomImage, 0, 0);
//debug info
fill(255);
text(String.format("frameIndex: %d\ntint: %.2f\nimageIndex: %d", frameIndex, tint, imageIndex), 10, 15);
}
The x, y position of the image isn't random, but that should be easy to replicated based on how the random image index is used.
Alternatively you can use a single random index and position that get's reset at the end of each transition:
int numFrames = 180;
int numFramesHalf = numFrames / 2;
int frameIndex = 0;
int imageIndex = 0;
int maxImages = 15;
PImage[] imgs = new PImage[42];
int randomImageIndex;
float randomX, randomY;
void setup(){
size(255, 255);
// load images
for (int i = 0; i < imgs.length; i++) {
imgs[i] = loadImage(i+".png");
}
// pick random index
randomImageIndex = int(random(0, 29));
randomX = random(width);
randomY = random(height);
}
void draw(){
// increment frame
frameIndex++;
// reset frame (if larger than transition frames total)
if(frameIndex >= numFrames){
frameIndex = 0;
// increment image index
imageIndex++;
// reset image index (if larger than total images to display)
if(imageIndex >= maxImages){
imageIndex = 0;
}
// reset random values
randomImageIndex = int(random(0, 29));
randomX = random(width);
randomY = random(height);
println("fade transition complete, next image: ", imageIndex);
}
// compute tint
int frameIndexToTint = abs(frameIndex - numFramesHalf);
float tint = map(frameIndexToTint, 0, numFramesHalf, 255, 0);
// visualise tint as background gray
background(0);
PImage randomImage =imgs[randomImageIndex];
tint(255, tint);
image(randomImage, randomX, randomY);
//debug info
fill(255);
text(String.format("frameIndex: %d\ntint: %.2f\nimageIndex: %d", frameIndex, tint, imageIndex), 10, 15);
}
And you can also encapsulate instructions grouped by functionality into functions (removing the redundant imageIndex since we're using a random index):
int numFrames = 180;
int numFramesHalf = numFrames / 2;
int frameIndex = 0;
int imageIndex = 0;
int maxImages = 15;
PImage[] imgs = new PImage[42];
int randomImageIndex;
float randomX, randomY;
void setup(){
size(255, 255);
// load images
for (int i = 0; i < imgs.length; i++) {
imgs[i] = loadImage(i+".png");
}
// pick random index
randomizeImage();
}
void draw(){
updateFrameAndImageIndices();
background(0);
PImage randomImage =imgs[randomImageIndex];
tint(255, tintFromFrameIndex());
image(randomImage, randomX, randomY);
}
float tintFromFrameIndex(){
int frameIndexToTint = abs(frameIndex - numFramesHalf);
return map(frameIndexToTint, 0, numFramesHalf, 255, 0);
}
void updateFrameAndImageIndices(){
// increment frame
frameIndex++;
// reset frame (if larger than transition frames total)
if(frameIndex >= numFrames){
frameIndex = 0;
// increment image index
imageIndex++;
// reset image index (if larger than total images to display)
if(imageIndex >= maxImages){
imageIndex = 0;
}
// reset random values
randomizeImage();
println("fade transition complete, next image: ", imageIndex);
}
}
void randomizeImage(){
randomImageIndex = int(random(0, 29));
randomX = random(width);
randomY = random(height);
}
If the goal of this coding excecise is to practice using classes, you can easily further encapsulate the image fade related functions and variables into a class:
PImage[] imgs = new PImage[42];
ImagesFader fader;
void setup(){
size(255, 255);
frameRate(60);
// load images
for (int i = 0; i < imgs.length; i++) {
imgs[i] = loadImage(i+".png");
}
// setup fader instance
// constructor args: PImage[] images, float transitionDurationSeconds, int frameRate
// use imgs as the images array, transition in and out within 1s per image at 60 frames per second
fader = new ImagesFader(imgs, 1.0, 60);
}
void draw(){
background(0);
fader.draw();
}
class ImagesFader{
int numFrames;
int numFramesHalf;
int frameIndex = 0;
PImage[] images;
int maxImages = 15;
int randomImageIndex;
float randomX, randomY;
ImagesFader(PImage[] images, float transitionDurationSeconds, int frameRate){
numFrames = (int)(frameRate * transitionDurationSeconds);
numFramesHalf = numFrames / 2;
println(numFrames);
this.images = images;
// safety check: ensure maxImage index isn't larger than the total number of images
maxImages = min(maxImages, images.length - 1);
// pick random index
randomizeImage();
}
void draw(){
updateFrameAndImageIndices();
PImage randomImage = imgs[randomImageIndex];
// isolate drawing style (so only the image fades, not everything in the sketch)
pushStyle();
tint(255, tintFromFrameIndex());
image(randomImage, randomX, randomY);
popStyle();
}
float tintFromFrameIndex(){
int frameIndexToTint = abs(frameIndex - numFramesHalf);
return map(frameIndexToTint, 0, numFramesHalf, 255, 0);
}
void updateFrameAndImageIndices(){
// increment frame
frameIndex++;
// reset frame (if larger than transition frames total)
if(frameIndex >= numFrames){
frameIndex = 0;
// randomize index and position
randomizeImage();
println("fade transition complete, next image: ", randomImageIndex);
}
}
void randomizeImage(){
randomImageIndex = int(random(0, 29));
randomX = random(width);
randomY = random(height);
}
}
If you're comfortable using Processing libraries, you can achieve the same with a tweening library like Ani:
import de.looksgood.ani.*;
import de.looksgood.ani.easing.*;
PImage[] imgs = new PImage[42];
float tintValue;
int randomImageIndex;
float randomX, randomY;
AniSequence fadeInOut;
void setup(){
size(255, 255);
frameRate(60);
// load images
for (int i = 0; i < imgs.length; i++) {
imgs[i] = loadImage(i+".png");
}
randomizeImage();
// Ani.init() must be called always first!
Ani.init(this);
// create a sequence
// dont forget to call beginSequence() and endSequence()
fadeInOut = new AniSequence(this);
fadeInOut.beginSequence();
// fade in
fadeInOut.add(Ani.to(this, 0.5, "tintValue", 255));
// fade out (and call sequenceEnd() when on completion)
fadeInOut.add(Ani.to(this, 0.5, "tintValue", 0, Ani.QUAD_OUT, "onEnd:sequenceEnd"));
fadeInOut.endSequence();
// start the whole sequence
fadeInOut.start();
}
void draw(){
background(0);
tint(255, tintValue);
image(imgs[randomImageIndex], randomX, randomY);
}
void sequenceEnd() {
randomizeImage();
fadeInOut.start();
}
void randomizeImage(){
randomImageIndex = int(random(0, 29));
randomX = random(width);
randomY = random(height);
}
Update Based on your comment regarding loading images, can you try this sketch ?
void setup(){
size(1000, 500);
textAlign(CENTER);
PImage[] images = loadImages("Data","png");
int w = 100;
int h = 100;
for(int i = 0; i < images.length; i++){
float x = i % 10 * w;
float y = i / 10 * h;
image(images[i], x, y, w, h);
text("["+i+"]",x + w / 2, y + h / 2);
}
}
PImage[] loadImages(String dir, String extension){
String[] files = listPaths(dir, "files", "extension=" + extension);
int numFiles = files.length;
PImage[] images = new PImage[numFiles];
for(int i = 0 ; i < numFiles; i++){
images[i] = loadImage(files[i]);
}
return images;
}
It should load images in the "Data" folder (as the comment mentions, not "data" which is commonly used in Processing). If "Data" is a typo, fix the path first (as Processing is key sensitive ("Data" != "data")). If the 50 images load correctly, it should display in a 10x5 grid at 100x100 px each (e.g. disregarding each image's aspect ratio). This should help test if the images load correctly. (Again, breaking the problem down to individual steps).

Related

Radial Waves in Processing

I am currently a bit stuck! Lets say, have a grid of shapes (nested For-Loop) and I want to use a wave to animate it. The wave should have an offset. So far, i can achieve it. Currently the offset affects the Y-axis … But how can I manage to have a RADIAL offset – you know – like the clock hand, or a radar line… I really would like the offset to start from (width/2, height/2) – and then walks around clockwise. Here is my code and the point where I am stuck:
void setup() {
size(600, 600);
}
void draw () {
background(255);
float tiles = 60;
float tileSize = width/tiles;
for (int x = 0; x < tiles; x++) {
for (int y = 0; y < tiles; y++) {
float waveOffset = map(y, 0, 60, 0, 300);
float sin = sin(radians(frameCount + waveOffset));
float wave = map(sin, -1, 1, 0, tileSize);
fill(0);
noStroke();
pushMatrix();
translate(tileSize/2, tileSize/2);
ellipse(x*tileSize, y*tileSize, wave, wave);
popMatrix();
}
}
}
I tried different things – like the rotate(); function etc. but I can't manage to combine it!
Thank you for any kind of help!
Right now, you're defining the size of the ellipses based on a transformation of sin(y). A transformation means it looks like a * sin(b * y + c) + d, and in this case you have
a = tileSize / 2
b = 300 / 60 = 5
c = frameCount
d = tileSize / 2
If you want to do a different pattern, you need to use a transformation of sin(theta) where theta is the "angle" of the dot (I put "angle" in quotes because it's really the angle from the vector from the center to the dot and some reference vector).
I suggest using the atan2() function.
Solution:
float waveOffset = 2*(atan2(y - tiles/2, x - tiles/2));
float sin = sin((frameCount/20.0 + waveOffset));
void setup() {
size(600, 600);
}
void draw () {
background(255);
float tiles = 60;
float tileSize = width/tiles;
for (int x = 0; x < tiles; x++) {
for (int y = 0; y < tiles; y++) {
float waveOffset = atan2(y - tiles/2, x - tiles/2)*0.5;
float sin = sin((frameCount*0.05 + waveOffset));
float wave = map(sin, -1, 1, 0, tileSize);
fill(0);
noStroke();
pushMatrix();
translate(tileSize/2, tileSize/2);
ellipse(x*tileSize, y*tileSize, wave, wave);
popMatrix();
}
}
}

How to do: for looping + increasing of radius each loop?

How do I create a clean and simple code that creates a circle of point/dots within the larger one? Or something similar (I can't post an image of what I want sorry). I was told to try using a for loop around the outside of my code and have the radius increase slightly each iteration of the loop. However, i don't know how to increase the radius?
This is the code I've been experimenting with so far:
size (400, 400);
background(255);
noStroke();
fill(0);
smooth();
translate(width/2, height/2);
int numpoints = 10;
float angleinc = 2 * PI / numpoints;
int radius = 100;
for (int i = 0; i < numpoints; i++) {
float x = cos(angleinc * i) * radius;
float y = sin(angleinc * i) * radius;
ellipse(x, y, 4, 4);
}
Please, any quick help would be appreciated. Also, I'm fairly new to processing and coding, so I'm not the best...
You'll have better luck if you break your problem down into smaller steps. Step one is creating a function that draws a single "ring" of smaller circles. You already have that step done, all you need to do is separate it into its own function:
void drawCircle(int outerRadius, int innerRadius) {
int numpoints = 10;
float angleinc = 2 * PI / numpoints;
for (int i = 0; i < numpoints; i++) {
float x = cos(angleinc * i) * outerRadius;
float y = sin(angleinc * i) * outerRadius;
ellipse(x, y, innerRadius, innerRadius);
}
}
Then, to draw a set of rings of increasing size, you simply call the function multiple times:
drawCircle(50, 8);
drawCircle(75, 12);
drawCircle(100, 16);
Which you can condense into a for loop:
for(int i = 2; i <= 4; i++){
drawCircle(25*i, 4*i);
}
The whole thing would look something like this:
void setup() {
size (400, 400);
}
void draw() {
background(255);
noStroke();
fill(0);
smooth();
translate(width/2, height/2);
for(int i = 2; i <= 4; i++){
drawCircle(25*i, 4*i);
}
}
void drawCircle(int outerRadius, int innerRadius) {
int numpoints = 10;
float angleinc = 2 * PI / numpoints;
for (int i = 0; i < numpoints; i++) {
float x = cos(angleinc * i) * outerRadius;
float y = sin(angleinc * i) * outerRadius;
ellipse(x, y, innerRadius, innerRadius);
}
}
This is just an example, and you'll have to play around with the numbers to make it look exactly like what you want, but the process is the same: break your problem down into smaller steps, isolate those steps into functions that do one thing, and then call those functions to accomplish your overall goal.
I hope i got your question right-
The formula of a circle around the origin is x=Rcos(angle) y=Rsin(angle) where angel is going between 0 to 2*pi
if you want to draw the circle around point lets say around (x',y'), the formula will be x= x' + Rcos(angle) y= y' + rsin(angle)
The code:
float epsilon = 0.0001f;
float R = 5.5.f;
for (float angle = 0.0; angle < 2*PI; angle += epsilon ) {
float x = x' + R*cos(angle);
float y = y' + R*sin(angle);
drawPoint(x,y);
if( /*condition for changing the radius*/ )
{
R = R*2; // or any change you want to do for R
}
}
It's probably easiest if you use two for loops: one for loop to draw the circle at a certain radius and another for loop which has the previous for loop in it which increases the radius.
int numCircles = 3;
//This for loop increases the radius and draws the circle with another for loop
for (int j = 0; j < numCircles; j++)
{
//This for loop draws the actual circle
for (int i = 0; i < numpoints; i++)
{
float x = cos(angleinc * i) * radius;
float y = sin(angleinc * i) * radius;
ellipse(x, y, 4, 4);
}
//(add code here that increases the radius)
}

Last clicked image in array

I have an array of images, when i click on one of them, I want it to loop and create a pattern. (This part already works). When i want to get the last clicked image out of my array i get a 'NullPointerException'
PImage[] patronen = new PImage[7];
int pLength = patronen.length;
PImage selectedPatroon = patronen[patronen.length-1];
void setup(){
size(1024, 768);
}
void draw(){
createPGrid();
image(selectedPatroon, xPos, yPos);
}
void createPGrid(){
for(int j = 0; j < gpLength; j++){
// Grid maanmaken
xPos = xOffset + ((j % cols) * (size+padding));
yPos = yOffset + ((j / cols) * (size+padding));
// Thumbs
patronen[j] = loadImage( j + ".png");
image(patronen[j], xPos, yPos);
// Check if thumb is clicked
if((mouseX >= xPos && mouseX <= xPos+size) &&
(mouseY >= yPos && mouseY <= yPos+size)){
if (mousePressed){
// grid patronen
xPos = 0;
yPos = 0;
// Loop pattern
while( yPos < height ){
while( xPos < width ){
patronen[j] = loadImage(j + "groot" + ".png");
selectedPatroon = patronen[j]
xPos += 500;
}
yPos +=500;
xPos = 0;
}
rect(xPos, yPos, size, size);
}
}
}
}
EDIT: The thing is, it works perfectly without
PImage selectedPatroon = patronen[patronen.length-1];
but then the looped pattern comes above all my others functions. And i want it to be under that.
You are creating an array at the top of your code then setting an image to the last element in the array, but you're not populating the array first.
PImage[] patronen = new PImage[7]; <<< Blank 7 element array.
int pLength = patronen.length;
PImage selectedPatroon = patronen[patronen.length-1];
To answer the questions you've put in the comments, you cannot populate an array of PImages with ints, those are different variable types. Try something like this in setup():
PImage patronen = new PImage[7];
for(int i = 0; i < patronen.length; i++){
patronen[i] = loadImage("image" + i + ".png"); // or whatever format your filenames are
}
The loadImage(String name) function returns a PImage, so you can insert it directly into your array. Just trying to insert the numbers won't work because the computer doesn't know that the numbers represent the filename without you telling it with loadImage().

How would one draw to the sub display of a ds as if it was a framebuffer?

I need to draw raw pixel data to the Nintendo DS's "sub" screen, such as if I was drawing to the main screen in "framebuffer" mode or "Extended Rotation" mode. How can I do this with the current version of libnds (which seems to place restrictions on the use of VRAM_C)?
#include <nds.h>
int main(void)
{
int x, y;
//set the mode to allow for an extended rotation background
videoSetMode(MODE_5_2D);
videoSetModeSub(MODE_5_2D);
//allocate a vram bank for each display
vramSetBankA(VRAM_A_MAIN_BG);
vramSetBankC(VRAM_C_SUB_BG);
//create a background on each display
int bgMain = bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0,0);
int bgSub = bgInitSub(3, BgType_Bmp16, BgSize_B16_256x256, 0,0);
u16* videoMemoryMain = bgGetGfxPtr(bgMain);
u16* videoMemorySub = bgGetGfxPtr(bgSub);
//initialize it with a color
for(x = 0; x < 256; x++)
for(y = 0; y < 256; y++)
{
videoMemoryMain[x + y * 256] = ARGB16(1, 31, 0, 0);
videoMemorySub[x + y * 256] = ARGB16(1, 0, 0, 31);
}
while(1)
{
swiWaitForVBlank();
}
}
Here is a simple example which creates a 16 bit frame buffer on the main and sub screens and fills each with either red or blue.

Tracking objects using histogram data in OpenCV

I am trying to track objects inside an image using histogram data from the object. I pass in a reference image to get the histogram data and store it in a Mat. From there I load in an image and try and use the histogram data to detect the object. The problem I am coming with is not only is it not tracking the object, but it's not updating the detection. If I load image "1.jpg" the detection will claim that the object is in the top right corner when it's in the bottom left. When I pass in the second image the detection field does not move at all. This continues for the next batch of images as well. Below is a code snippet of my application.
This is being done in a Windows 7 32-bit environment using OpenCV2.3 in VS2010. Thanks in advance for any help
int main( int argc, char** argv )
{
vector<string> szFileNames;
IplImage* Image;
Mat img, hist, backproj;
Rect trackWindow;
// Load histogram data
hist = ImageHistogram("C:/Users/seb/Documents/redbox1.jpg", backproj);
Image = cvLoadImage("C:/Users/seb/Documents/1.jpg");
img = Mat(Image);
trackWindow = Rect(0, 0, Image->width, Image->height);
imshow("Histogram", hist);
while(true)
{
Detection(img, backproj, trackWindow);
imshow("Image", img);
char c = cvWaitKey(1);
switch(c)
{
case 32:
{
cvReleaseImage(&Image);
Image = cvLoadImage("C:/Users/seb/Documents/redbox2.jpg");
img = Mat(Image);
break;
}
}
}
cvReleaseImage(&Image);
// Destroy all windows
cvDestroyWindow("Histogram");
cvDestroyWindow("Image");
return 0;
}
Mat ImageHistogram(string szFilename, Mat& backproj)
{
// Create histogram values
int vmin = 10;
int vmax = 256;
int smin = 30;
int hsize = 16;
float hranges[] = {0,180};
const float* phranges = hranges;
// Load the image
IplImage* Image = cvLoadImage(szFilename.c_str());
Rect rect = Rect(0, 0, Image->width, Image->height);
// Convert Image to a matrix
Mat ImageMat = Mat(Image);
// Create and initialize the Histogram
Mat hsv, mask, hue, hist, histimg = Mat::zeros(200, 320, CV_8UC3);
cvtColor(ImageMat, hsv, CV_BGR2HSV);
// Create and adjust the histogram values
inRange(hsv, Scalar(0, smin, vmin), Scalar(180, 256, vmax), mask);
int ch[] = {0, 0};
hue.create(hsv.size(), hsv.depth());
mixChannels(&hsv, 1, &hue, 1, ch, 1);
Mat roi(hue, rect), maskroi(mask, rect);
calcHist(&roi, 1, 0, maskroi, hist, 1, &hsize, &phranges);
normalize(hist, hist, 0, 255, CV_MINMAX);
histimg = Scalar::all(0);
int binW = histimg.cols / hsize;
Mat buf(1, hsize, CV_8UC3);
for( int i = 0; i < hsize; i++ )
buf.at<Vec3b>(i) = Vec3b(saturate_cast<uchar>(i*180./hsize), 255, 255);
cvtColor(buf, buf, CV_HSV2BGR);
for( int i = 0; i < hsize; i++ )
{
int val = saturate_cast<int>(hist.at<float>(i)*histimg.rows/255);
rectangle( histimg, Point(i*binW,histimg.rows),
Point((i+1)*binW,histimg.rows - val),
Scalar(buf.at<Vec3b>(i)), -1, 8 );
}
calcBackProject(&hue, 1, 0, hist, backproj, &phranges);
backproj &= mask;
cvReleaseImage(&Image);
return histimg;
}
void Detection(Mat& image, Mat& backproj, Rect& trackWindow)
{
RotatedRect trackBox = CamShift(backproj, trackWindow, TermCriteria( CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 10, 1 ));
int test2 = trackWindow.area();
if(trackBox.size.height > 0 && trackBox.size.width > 0)
{
if( trackWindow.area() <= 1 )
{
int cols = backproj.cols, rows = backproj.rows, r = (MIN(cols, rows) + 5)/6;
trackWindow = Rect(trackWindow.x - r, trackWindow.y - r,
trackWindow.x + r, trackWindow.y + r) &
Rect(0, 0, cols, rows);
}
int test = trackBox.size.area();
if(test >= 1)
{
rectangle(image, trackBox.boundingRect(), Scalar(255,0,0), 3, CV_AA);
ellipse( image, trackBox, Scalar(0,0,255), 3, CV_AA );
}
}
}
I've figured out the issue. It had to deal with me not converting the image that I'm checking upon. I had to get histogram data from my colored box and then I had to get the histogram from the image I was using to search.

Resources