从 jpg / png 加载像素不正确的处理

loadpixels from jpg / png incorrect processing

我正在尝试使用图像的底层颜色在图像上绘制网格以填充圆圈。但是有些像素没有得到正确的颜色。 在这种情况下,圆圈被绘制成白色,但它们不应该被绘制成白色...

查看下面我的代码:

import processing.pdf.*;

PImage img;
color background = color(255);

void setup() {
  size(1038, 525);
  ellipseMode(CORNER);
  noStroke();

  //img = loadImage("noise2.jpg");
  //img = loadImage("air.png");
  img = loadImage("accidents.png");

  image(img, 0, 0, width, height);
  visualGrid(20, 0.4, false);
}

//void draw() {
//  fill(noise.get(mouseX, mouseY));
//  rect(width - 100, height - 100, 100, 100);
//}

void visualGrid(int circleSize, float fillSmoothing, boolean debug) {
  float halfCircle = circleSize / 2.0;
  int amountX = floor(width / circleSize);
  int amountY = floor(height / circleSize);
  amountY += floor(amountY * 0.1);
  
  float offsetX = (width - (amountX * circleSize  + halfCircle)) / 2 + halfCircle;
  float offsetY = (height - amountY * circleSize + amountY * circleSize * 0.1) / 2;
  
  for (int x = 0; x < amountX; x++) {
    for (int y = 0; y < amountY; y++) {
      float styledOffsetX = (y % 2 == 0) ? offsetX - halfCircle : offsetX;
      float xpos = x * circleSize + styledOffsetX;
      float ypos = circleSize * 0.9 * y + offsetY;
      
      int sectionSize = round(circleSize * fillSmoothing);
      float sectionOffset = (circleSize - sectionSize) / 2;
      
      color c = getAvgImgColor(img.get(round(xpos + sectionOffset), round(ypos + sectionOffset), sectionSize, sectionSize));
      //fill(noise.get(round(xpos), round(ypos)));
      
      if(debug) {
        stroke(255, 0, 255);
        strokeWeight(1);
      }
      
      fill(c);
      ellipse(xpos, ypos, circleSize, circleSize);
      
      if(debug) {
        noStroke();
        fill(255, 0, 255);
        rect(round(xpos + sectionOffset), round(ypos + sectionOffset), sectionSize, sectionSize);
      }
    }
  }
}

color getAvgImgColor(PImage section) {
  
  section.loadPixels();
  
  int avgR = 0, avgG = 0, avgB = 0;
  int totalPixels = section.pixels.length;
  
  for (int i = 0; i < totalPixels; i++) { 
    color pixel = section.pixels[i];
    //if(pixel == background) continue;
    
    avgR += red(pixel);
    avgG += green(pixel);
    avgB += blue(pixel);
  } 
  
  return color(
    round(avgR / totalPixels),
    round(avgG / totalPixels),
    round(avgB / totalPixels)
  );
}

这是我在相关图像上绘制网格时得到的结果:
正如您在圆圈区域中看到的那样,并非所有圆圈都应填充白色...这种情况发生在更多地方,而不仅仅是圆圈区域只是将此图像与下面的图像进行比较。

下面我会上传原图,大家可以调试使用

您的草图尺寸 (1038 x 525) 与您采样的图像尺寸 (2076 x 1048) 不匹配,这可能是不对齐的原因。

如果 size(2076, 1048) 不是一个选项,请在图像加载到 setup() 后尝试调整图像大小:

...
img = loadImage("accidents.png");
img.resize(width, height);
...