如何在Processing中转换颜色数据

时间:2014-01-20 08:43:44

标签: processing

我的目标是从输入图像中获取每个像素,根据其值对每个像素进行排序,然后根据排序的像素值数组输出原始图像的重组版本。我相当确定我需要使用hex()函数来格式化颜色数据,以便Processing可以再次解释它,但是我没有得到所需的结果。实际上,当我运行草图时,我只获得全黑像素数组。

size(150, 150);
PImage myImage = loadImage("image.jpg");
image(myImage, 0, 0);

int[] colors = new int[22500];

loadPixels();
for (int i = 0; i < 22500; i++) {
  colors[i] = pixels[i];
}
updatePixels();

int x = 1;
int y = 1;

colors = sort(colors);

for (int i = 0; i < 22500; i++) {
  color c = colors[i];
  fill(c);
  rect(x, y, 1, 1);

  x = x + 1;

  if (x > width-3) {
    x = 1;
    y = y + 1;
  }
}

2 个答案:

答案 0 :(得分:3)

我认为你过分复杂了......你可以这样做(这是整个草图):

PImage myImage = loadImage("image.jpg");
size(myImage.width*2, myImage.height);
myImage.loadPixels();
image(myImage, 0, 0);
myImage.pixels = sort(myImage.pixels);
myImage.updatePixels();
image(myImage, myImage.width, 0);

我有一种感觉,但结果并不完全符合你的期望......如果你想要在颜色之间平滑过渡,那么“排序”功能将无法做到,因为颜色不会像那样存储。快速解释: 每个像素的颜色都是红绿和蓝三种颜色的组合(让我们暂时保留透明度)。所以带有典型颜色选择器的橙色是255(R)204(G)0(B)。这三个值彼此相邻附加以存储最终颜色。如果将它们转换为十六进制,则更容易理解:FF(R)CC(G)00(B)。十六进制的最终值如下所示:FFCC00。如果你再次将它转换为十进制,以便你可以存储它,你得到16763904,这是像素[]数组填充。好吧,如果你按照你想要的那样对像素[]数组进行排序,你得到的本质上是一个像这样排序的数组:

 R   G   B
000 000 000
000 000 001 // a bit blue but almost black
000 000 002 // getting bluer
.
.
.
000 000 255 // all blue
000 001 000 // a bit green but almost black
000 001 001 // a bit green and a bit blue
.
.
.
000 255 000 // all green
000 255 001 // all green and a bit blue (going to cyan)
.
.
.
000 255 255 // cyan
001 000 000 // a bit red but almost black
001 001 000 // a bit red and a bit green
.
.
.
255 000 000 // all red
.
.
.
255 255 000 // yellow
.
.
.
255 255 255 // white

最终效果(主要是黑色+青色图像):

enter image description here

答案 1 :(得分:1)

您的草图缺少noStroke()。您需要在绘制第1边的矩形的for循环之前的某处添加它,否则矩形的边框(黑色)将填充整个草图。

或者,替换

  fill(c);
  rect(x, y, 1, 1);

  stroke(c);
  rect(x, y, 1, 1);

您也可以使用point代替rect,但之后需要添加noSmooth()

  noSmooth();
  stroke(c);
  point(x, y);

只是为了好玩,这是一张用你的剧本排序的蒙德里安图片

未排序:enter image description here已排序:enter image description here

如果您正在寻找其他颜色排序方法,您可以编写自己的方法或使用可用的库,例如http://toxiclibs.org/