Rotate image implementation

I’m implementing the matrix rotation from here

My code works but the rotated image has holes, I guess it’s because of the rounding of the values of sin () and cos ()

How to fill the holes in the rotated image?





PImage img;

int angle=0;

int xpos=0;
int ypos=0;

void setup()
{
  size(370, 360, P3D);
  
  loadPixels();  
img = loadImage("img.png");
  img.loadPixels(); 



 updatePixels(); 
  background(0);
}







void draw()
{
 background(0);
loadPixels();




updatePixels();



//increment angle 
 if (keyPressed && key=='v'){  
   angle+=1;
 }
 
 

 
 

   for(int xx = 1; xx < img.width ; xx++)
{
    for(int yy = 1; yy < img.height-1 ; yy++)
 {
 
xpos=(100+floor((xx)*cos(radians(angle)))-floor((yy)*sin(radians(angle))));
ypos=(180+floor((xx)*sin(radians(angle)))+floor((yy)*cos(radians(angle)))); 

if (ypos>1 && ypos<height){
  setpixel( xpos, ypos, getpixel(img,xx,yy));
}
}
}


ellipse(100,180,10,10);








}//fin draw






void setpixel(PImage arr , int x, int y , color col)
{
arr.pixels[x+arr.width*y]=color(col);
}


void setpixel(PGraphics arr , int x, int y , color col)
{
arr.pixels[x+arr.width*y]=color(col);
}



void setpixel( int x, int y , color col)
{
pixels[x+width*y]=color(col);
}


int getpixel(PGraphics arr, int x, int y )
{
return int(arr.pixels[x+arr.width*y]);
}


int getpixel( int x, int y )
{
return int(pixels[x+width*y]);
}



int getpixel(PImage arr, int x, int y )
{
return int(arr.pixels[x+arr.width*y]);
}

There is easier way to rotate an image, try this:-

PImage img;
int angle = 0;

void setup() {
  size(370, 360, P2D);
  smooth(8);
  img = loadImage("img.png");
  imageMode(CENTER); 
}

void draw() {
  background(0);
  fill(255);
  translate(width / 2, height / 2);
  rotate(angle * TWO_PI / 360);
  image(img, 0, 0, 300, 300);  
  ellipse(170,0,10,10); // corrected for translation
}

void keyPressed(){
  if (key == 'v'){
    angle += 1;
  }
}

Also I don’t know why you are specifying P3D mode? If you don’t want ellipse to rotate wrap rotation stuff with pushMatrix()/popMatrix().

Hi molo32,

You are marching through your source picture. What you should do instead is marching through the destination picture. Then you can compute from which pixel of the original image it comes from. This way you assure that you won’t miss any.

Of course you’ll never get an exact pixel so after it is up to you to decide how to deal with that problem: choosing the closest pixel only, compute the average weighted by distance or by surface area…

1 Like