使用处理随机重新排列图像的某些部分



我正在尝试通过网格将图像切成四个方形部分,然后随机重新排列它们。我以为我可以使用副本();实现此目的的函数 – 将图像切割成四个部分 – 然后将这些部分加载到 PGraphics 数组中。下一步是将它们从数组中取出,并将它们随机分布到网格中。我认为为此网格应该由二维数组构建......

这是我到目前为止提出的:

PImage src;
int[][] grid = new int[2][2];
PGraphics[] pgs = new PGraphics[4];
void setup() {
size(1080, 1080);
frameRate(5);
src = loadImage("dog.jpg");
src.resize(width, height);

for (int i = 0; i < pgs.length; i++) { 
pgs[i] = createGraphics(width, height);
}
}
void draw() {
background(255);
//image(src, 0, 0, width, height);
// Variables for the grid  
int tilesX = grid.length;
int tilesY = grid.length;  
int tileW = int(width/tilesX);
int tileH = int(width/tilesY);
// Build the grid
for (int y = 0; y < tilesY; y++) {
for (int x = 0; x < tilesX; x++) {

// These build the coordinates we copy from 
int sx = x * tileW;
int sy = y * tileH;
int sw = tileW;
int sh = tileH;
// These build the coordinates we copy to
int dx = grid[x][y];
int dy = grid[x][y];
int dw = tileW;
int dh = tileH;       
for (int i = 0; i < pgs.length; i++) {    
pgs[i].beginDraw();
pgs[i].copy(src, sx, sy, sw, sh, dx, dy, dw, dh);
pgs[i].endDraw();
}
int selector = int(random(pgs.length));
grid[x][y] = selector;
push();
translate(selector*tileW, selector*tileH);
image(pgs[grid[x][y]], 0, 0);
pop();
}
}
}

所以我设法通过不同的步骤从头开始构建代码——但替换太疯狂了——我不再确定我是否走在正确的轨道上!是否可以将复制函数中复制的部分作为单个 PGraphics 加载到数组中?

感谢您的任何提示或帮助!

这是使用PGraphics的一种方法:

PImage src;
PGraphics[] pgs = new PGraphics[4];
void setup() {
size(1080, 1080);
frameRate(5);
src = loadImage("dog.jpg");
src.resize(width, height);
for (int i = 0; i < imgs.length; i++) {
pgs[i] = createGraphics(width/2, height/2);
pgs[i].beginDraw();
pgs[i].copy(src, (i % 2) * width/2, floor(i/2) * height/2, width/2, height/2, 0, 0, width/2, height/2);
pgs[i].endDraw();
}
}
void draw() {
background(255);
for (int i = 0; i < pgs.length; i++) {
image(pgs[int(random(pgs.length))], (i % 2) * width/2, floor(i / 2) * height/2);
}
}

您也可以使用PImage

PImage src;
PImage[] imgs = new PImage[4];
void setup() {
size(1080, 1080);
frameRate(5);
src = loadImage("dog.jpg");
src.resize(width, height);
for (int i = 0; i < imgs.length; i++) {
imgs[i] = createImage(width/2, height/2, RGB);
imgs[i].copy(src, (i % 2) * width/2, floor(i/2) * height/2, width/2, height/2, 0, 0, width/2, height/2);
}
}
void draw() {
background(255);
for (int i = 0; i < imgs.length; i++) {
image(imgs[int(random(imgs.length))], (i % 2) * width/2, floor(i / 2) * height/2);
}
}

您也可以在没有图像数组的情况下执行此操作,只需每帧直接从源复制:

PImage src;
void setup() {
size(1080, 1080);
frameRate(5);
src = loadImage("dog.jpg");
src.resize(width, height);
}
void draw() {
background(255);
for (int i = 0; i < 4; i++) {
int j = int(random(4));
copy(src, (j % 2) * width/2, floor(j / 2) * height/2, width/2, height/2, (i % 2) * width/2, floor(i / 2) * height/2, width/2, height/2);
}
}

尽管最后一种方法更耗费资源,事后更难操作。

最新更新